繁体   English   中英

如何在VBa中使用Vlookup?

[英]How to use Vlookup in VBa?

这是我编写的在Vba中使用Vlookup的代码,但我不断

运行时错误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)

我该如何解决? 谢谢!

如果找不到匹配项, Application.WorksheetFunction.VLookup将始终引发运行时错误-您无法使用IsNA()处理该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

像这样工作

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)

暂无
暂无

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

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