Question

I have a two columns in excel which have corresponding items. My program needs to check textbox3 for its value and if that value exists (case insensitive) in the first column then textbox4 will take on the corresponding value. So basically the user types in the name of an item in textbox3 and presses enter (the key, not a button). If it exists then textbox4 will take on the corresponding value.

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
Was it helpful?

Solution

You have to specify which sheet the range is in. Try this:

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

Also you might get an error with this:

 Range("a" & i)

If you do use this:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top