如何在VBa中使用Vlookup?

时间:2019-02-07 00:52:58

标签: excel vba vlookup

这是我编写的在Vba中使用Vlookup的代码,但我一直在获得

运行时错误1004 无法获取工作表函数类的Vlookup属性

dotnet publish --self-contained=False -r ""

我该如何解决? 谢谢!

2 个答案:

答案 0 :(得分:1)

Application.WorksheetFunction.VLookup始终会在找不到匹配项时引发运行时错误-您无法使用IsNA()

您可以在没有WorksheetFunction的情况下这样做:

Dim m    

m = Application.VLookup(ListBox1.Selected(0), Range("B4:C7"), 2, False))

If IsError(m) Then
    'Create row
     Range("EndlineFM").Insert Shift:=xlDown
     'Initialise Detail and montant of new row
     Range("TotalF").Offset(-1, 0) = FraisM.ListBox1.Selected(0)
     Range("TotalF").Offset(-1, 1) = CSng(FraisM.Chiffremontant)
     'etc

答案 1 :(得分:0)

它像这样工作

Dim Txt As Variant
On Error Resume Next 
Txt = Application.WorksheetFunction.VLookup(FraisM.ListBox1.List(FraisM.ListBox1.ListIndex), Range("B4:C7"), 2, False)
             If Err.Number <> 0 Then
             MsgBox " Not found" ''optional, no need to do anything
             Err.Clear
             Exit Sub   ' Or may use Goto label
             End If
     On Error GoTo 0
    'Create row
     Range("EndlineFM").Select
     Selection.Insert Shift:=xlDown
    'Initialise Detail and montant of new row
     Range("TotalF").Offset(-1, 0) = Txt

我已将FraisM作为用户表单名称,并假设代码从Module运行。如果您在工作表上使用Msform.ListBox,则可以尝试

Dim MyLB  As Object
Set MyLB = Sheet1.Shapes("List Box 1")
Txt = Application.WorksheetFunction.VLookup(MyLB.ControlFormat.List(MyLB.ControlFormat.ListIndex), Range("B4:C7"), 2, False)