按下输入时,文本框激活代码

时间:2014-04-30 05:34:45

标签: excel vba textbox key enter

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

1 个答案:

答案 0 :(得分:0)

您必须指定范围所在的工作表。请尝试以下操作:

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