Trying to get Vlookup working in VBA

Luke Hawtrey 1 Reputation point
2021-03-30T23:10:04.647+00:00

I have a worksheet that already uses Vlookup to find values. When I tried to use this code, it returned a "Error 1004" What could be the issue here?

If Me.txt_BarcodeScanIn.Value >= 0 Then

Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("IN_OUT")

Dim lr As Long
lr = Application.WorksheetFunction.CountA(sh.Range("A:A"))

''''example vlookup Application.WorksheetFunction.VLookup(Me.cmb_Product, ThisWorkbook.Sheets("Product_Master").Range("B:D"), 2, 0)''''
Dim Barcode As String

Barcode = Me.txt_BarcodeScanIn.Value

sh.Range("A" & lr + 1).Value = lr
sh.Range("B" & lr + 1).Value = Application.WorksheetFunction.VLookup(Barcode, ThisWorkbook.Sheets("Master_Copy").Range("B:D"), 2, 0)
sh.Range("C" & lr + 1).Value = "Received"
sh.Range("D" & lr + 1).Value = 1
sh.Range("E" & lr + 1).Value = Application.WorksheetFunction.VLookup(Barcode, ThisWorkbook.Sheets("Master_Copy").Range("B:D"), 3, 0)
sh.Range("G" & lr + 1).Value = Me.txt_BarcodeScanIn.Value
sh.Range("H" & lr + 1).Value = Format(Now, "dd-mmm-yyyy")
Else: Me.txt_BarcodeScanIn.Value = ""

End If

''''''''''''Clear Boxes''''''''''''
Me.txt_BarcodeScanIn.Value = ""

0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Tom van Stiphout 1,621 Reputation points MVP
    2021-03-31T01:31:34.62+00:00

    Set a breakpoint at the top. Step through. At which line are you getting the error?


  2. Tom van Stiphout 1,621 Reputation points MVP
    2021-04-01T02:46:47.16+00:00

    At that point in the code, stepping through in the debugger, enter this in the Immediate window:
    ?Application.WorksheetFunction.VLookup(Barcode, ThisWorkbook.Sheets("Master_Copy").Range("B:D"), 2, 0)
    This will evaluate the right-hand-side of the assignment, and may inform you better about what's not working. Maybe such worksheet does not exist.

    0 comments No comments