【问题标题】:Textbox activates code when enter is pressed按下回车时文本框激活代码
【发布时间】:2014-04-30 05:34:44
【问题描述】:

我在 excel 中有两列有相应的项目。我的程序需要检查 textbox3 的值,如果第一列中存在该值(不区分大小写),则 textbox4 将采用相应的值。所以基本上用户在 textbox3 中输入项目的名称并按下回车键(键,而不是按钮)。如果存在,则 textbox4 将采用相应的值。

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = 13 Then
        Dim i As Integer
        Dim abrv As String
        abrv = TextBox3.Text
        Sheet2.Activate
        For i = 1 To 2494
            If abrv = Range("a" & i).Value Then
                TextBox4.Text = Range("b" & i).Value
            End If
        Next i
        If TextBox4.Text = "" Then
            TextBox4.Text = "Abbreviation does not exist."
        End If
    End If
End Sub

【问题讨论】:

    标签: excel vba textbox key enter


    【解决方案1】:

    您必须指定范围所在的工作表。试试这个:

    Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = 13 Then
        Dim i As Integer
        Dim abrv As String
        abrv = TextBox3.Text
        Sheet2.Activate
        For i = 1 To 2494
            If abrv = Sheet2.Range("a" & i).Value Then
                TextBox4.Text = Sheet2.Range("b" & i).Value
            End If
        Next i
        If TextBox4.Text = "" Then
            TextBox4.Text = "Abbreviation does not exist."
        End If
    End If
    

    你也可能会遇到这样的错误:

     Range("a" & i)
    

    如果你使用这个:

    Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        If KeyCode = 13 Then
            Dim i As Integer
            Dim abrv As String
            abrv = TextBox3.Text
            Sheet2.Activate
            For i = 1 To 2494
                If abrv = Sheet2.Range("a" & strings.trim(str(i))).Value Then
                    TextBox4.Text = Sheet2.Range("b" & strings.trim(str(i))).Value
                End If
            Next i
            If TextBox4.Text = "" Then
                TextBox4.Text = "Abbreviation does not exist."
            End If
        End If
    

    【讨论】:

    • 当我在输入缩写后单击用户表单中的输入时,光标会移动到下一个文本框,而不是检索相应的值。另外, sheet2.activate 是否不让范围查看表 2?只是好奇,我不知道它是如何工作的。
    • 您可以使用类似 TextBox1.SetFocus 的方式将焦点返回到上一个文本框。 Sheet2.activate 仅将焦点带到 sheet2。
    • 谢谢,您发布的第一组代码完美运行!我只是忘记将 textbox1_keydown 更改为 textbox3_keydown
    • np,很高兴我能帮上忙 :)
    猜你喜欢
    • 2013-06-10
    • 2011-02-13
    • 2014-06-29
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2013-05-03
    • 1970-01-01
    相关资源
    最近更新 更多