Search code examples
excelvbanumbersvlookupuserform

Userform textbox fills in if Vlookup finds the information related to the numbers inserted


I have an userform where people have to fill in with data. If the data already exists, when they put the information in the DocumentTitleBox, other textboxes should automatically fill in.

My code works with letters, but not with numbers.

For example, when I put "aaa", it returns the vlookup values. But if I put "123", it won't do anything, even though there is a vlookup for it.

I cannot figure it out why. This is part of my code:

Private Sub DocumentTitleBox_Change()

On Error Resume Next
    Result = WorksheetFunction.VLookup(DocumentTitleBox.Value, Worksheets("example").Range("D:E"), 2, False)
    FIND = WorksheetFunction.VLookup(DocumentTitleBox.Value, Worksheets("example").Range("D:E"), 1, False)
On Error GoTo 0

If FIND = DocumentTitleBox.Value Then
    NameBox.Value = Result
End If

Thank you in advance!


Solution

  • I always use this kind of thing. Could be cleaned up and stuff but I like the flexibility and I change stuff all the time so this works for me.

    Private Sub DocumentTitleBox_Change()
    
    If IsNumeric(DocumentTitleBox.Value) Then
        ReturnRow = Application.IfError(Application.Match(DocumentTitleBox.Value + 0, Worksheets("example").Columns(4), 0), "Not Found")
        Find = Application.IfError(Application.Index(Worksheets("example").Columns(5), ReturnRow), "Not Present")
    Else
        ReturnRow = Application.IfError(Application.Match(DocumentTitleBox.Value, Worksheets("example").Columns(4), 0), "Not Found")
        Find = Application.IfError(Application.Index(Worksheets("example").Columns(5), ReturnRow), "Not Present")
    End If
    
    If Not Find Like "Not Present" Then
        NameBox.Value = Find
    Else
        NameBox.Value = ""
    End If
    
    End Sub
    

    PS: I don´t know how to avoid the match functions odd behaviour with strings/numbers so I just go with the +0 and IsNumeric trick. One thing to note is case sensitivity, adjust that as needed, right now its not.