Antoine P
Antoine P

Reputation: 27

How to use Vlookup in VBa?

This is a code I wrote to use Vlookup in Vba, but I keep getting

Run-time error 1004 Unable to get the Vlookup property of the Worksheet function class

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!

Upvotes: 0

Views: 455

Answers (2)

Ahmed AU
Ahmed AU

Reputation: 2777

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. If You are using Msform.ListBox on worksheet the may try

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)

Upvotes: 0

Tim Williams
Tim Williams

Reputation: 166126

Application.WorksheetFunction.VLookup will always raise a run-time error if there's no match found - you cannot handle that using IsNA()

You can do it like this without the 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

Upvotes: 1

Related Questions