简体   繁体   English

如何在VBa中使用Vlookup?

[英]How to use Vlookup in VBa?

This is a code I wrote to use Vlookup in Vba, but I keep getting 这是我编写的在Vba中使用Vlookup的代码,但我不断

Run-time error 1004 Unable to get the Vlookup property of the Worksheet function class 运行时错误1004无法获取工作表函数类的Vlookup属性

If WorksheetFunction.IsNA(Application.WorksheetFunction.VLookup(ListBox1.Selected(0), Range("B4:C7"), 2, False)) = True Then
'Create row
 Range("EndlineFM").Select
   Selection.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)

How can I fix it? 我该如何解决? Thanks! 谢谢!

Application.WorksheetFunction.VLookup will always raise a run-time error if there's no match found - you cannot handle that using IsNA() 如果找不到匹配项, Application.WorksheetFunction.VLookup将始终引发运行时错误-您无法使用IsNA()处理该IsNA()

You can do it like this without the WorksheetFunction : 您可以在没有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

It is working like this 像这样工作

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

I have taken FraisM as Userform Name and assumed code running from Module. 我已经将FraisM用作用户名,并假设代码是从Module运行的。 If You are using Msform.ListBox on worksheet the may try 如果您在工作表上使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM