我是使用vba尝试做简单程序的初学者,一旦用户单击列表框中的项目,它就会有一个列表框,该条目的其他信息应显示在表单中。
Private Sub ListBox1_Click()
Dim ename As String
Dim star As Integer
ename = ListBox1.Value
Lblname.Caption = " Employee Name: " & ename
star = Application.WorksheetFunction.VLookup(ename, Range("employee"), 4, False)
LblStart.Caption = "Time to come: " & star
End Sub
显示错误消息
无法从WorkSheetFunction类获取VLookup属性
答案 0 :(得分:1)
请改用Application对象的VLookup方法。这样,当没有匹配项时,会出现 不间断 错误,您可以使用IsError函数对其进行测试。因此,例如,首先将star声明为Variant,因为VLookup还可以返回错误...
Dim star As Variant
然后按如下所示测试结果...
star = Application.VLookup(ename, Range("employee"), 4, False)
If Not IsError(star) Then
LblStart.Caption = "Time to come: " & star
Else
LblStart.Caption = "Time to come: N/A"
End If
编辑
由于您的查找范围在Range(“ employee”)的第二列中,因此您需要使用INDEX / MATCH。因此,请尝试以下操作...
Private Sub ListBox1_Click()
Dim ename As String
Dim vMatchVal As Variant
ename = ListBox1.Value
Lblname.Caption = " Employee Name: " & ename
With Application
vMatchVal = .Match(ename, .Index(Range("employee"), 0, 2), 0) '2 = second column
If Not IsError(vMatchVal) Then
LblStart.Caption = "Time to come: " & .Index(Range("employee"), vMatchVal, 4) '4 = fourth column
Else
LblStart.Caption = "Time to come: N/A"
End If
End With
End Sub