无法从WorkSheetFunction类获取VLookup属性

问题描述 投票:0回答:1

我是初学者,使用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属性

excel vba
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.