嗨,我是VBA编程的新手 而我正在尝试搜索查找, 是的我可以搜索单个数据,但如果搜索计数> 1,那么我需要 根据字符串存在的次数显示一个msgbox
我得到了这个结果:
是的我得到了确切的结果,但它对第一行查找只有好处 包含薪水的下一行怎么样:234,871和SSN为241-652?
我想我需要根据vlookup计数进行循环,但是怎么做呢?
我需要看2x MsgBox,因为它有两个条目,所以当我点击第一个msgbox ok 那么另一个将遵循..请帮助谢谢!
这是我的代码
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
答案 0 :(得分:1)
我就是这样做的:
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 :(得分:1)
这也可以。
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