0
votes

Hi I am new of VBA programming and I am trying to do search look up, yes I can search single data but if the search count is >1 then I need to do a msgbox that will appear based on how many times the string exist

enter image description here

and I got this result:

enter image description here

Yes I got the exact result but its only good for the first row of lookup how about the next row which contains Salary: 234,871 and SSN of 241-652?

I guess I need to loop according to vlookup count but how to do it?

I need to see 2x MsgBox since it has two entries so when I click first msgbox ok then the other one will follow .. Please help Thanks!

this is my code

Private Sub CommandButton2_Click()
On Error GoTo MyErrorHandler:
Dim E_name As String
E_name = InputBox("Enter the Employee Name :")
If Len(E_name) > 0 Then
For i = 1 To 3
  Sal = Application.WorksheetFunction.VLookup(E_name, Sheets("sample").Range("B3:D8"), 3, False)
  SSN = Application.WorksheetFunction.VLookup(E_name, Sheets("sample").Range("B3:D8"), 2, False)
  MsgBox "Salary is : $ " & Sal & Chr(13) & "SSN is : " & SSN
Next i
Else
  MsgBox ("You entered an invalid value")
End If
Exit Sub
MyErrorHandler:
If Err.Number = 1004 Then
  MsgBox "Employee Not Present in the table."
End If
End Sub
2

2 Answers

1
votes

This is how I would do it:

Private Sub CommandButton2_Click()
Dim E_name As String
E_name = InputBox("Enter the Employee Name :")
If Len(E_name) > 0 Then
    lastRow = Range("C65000").End(xlUp).Row
    For i = 2 To lastRow
        If Cells(i, 2) = E_name Then
            found = 1
            MsgBox "Salary is : $ " & Cells(i, 4) & Chr(13) & "SSN is : " & Cells(i, 3)
        End If
    Next i
    If found <> 1 Then MsgBox "Employee Not Present in the table."
Else
    MsgBox ("You entered an invalid value")
End If
End Sub
1
votes

This will also work.

Private Sub CommandButton2_Click()

    Dim E_name, salary, ssn As String
    Dim row As Integer

    E_name = InputBox("Enter the Employee Name :")

    'Set the start row
    row = 3

    If Len(E_name) > 0 Then

        'Do until the name colum is blank
        Do While Sheets("sample").Range("B" & row) <> ""

            'If name are equal, show message box
            If E_name = Sheets("sample").Range("B" & row) Then

                salary = Sheets("sample").Range("D" & row)

                ssn = Sheets("sample").Range("C" & row)

                MsgBox "Salary is : $ " & salary & Chr(13) & "SSN is : " & ssn

            End If

            'Increase row
            row = row + 1

        Loop

    Else

        MsgBox ("You entered an invalid value")

    End If

End Sub