I'm trying to use vlookup in VBA.
My question is how do I define the table located in different worksheet/file on line 3?
You can set the workbook, worksheet and range to objects in VBA and refer to them by name..
example:
Sub test()
Dim filename As String
Dim fullRangeString As String
Dim returnValue As Variant
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
'get workbook path
filename = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls), *.xls", Title:="Please select a file")
'set our workbook and open it
Set wb = Application.Workbooks.Open(filename)
'set our worksheet
Set ws = wb.Worksheets("Sheet1")
'set the range for vlookup
Set rng = ws.Range("A3:I13")
'Do what you need to here with the range (will get error (unable to get vlookup property of worksheet) if value doesn't exist
returnValue = Application.WorksheetFunction.VLookup("test4", rng, 2, False)
MsgBox returnValue
'If you need a fully declared range string for use in a vlookup formula, then
'you'll need something like this (this won't work if there is any spaces or special
'charactors in the sheet name
'fullRangeString = "[" & rng.Parent.Parent.Name & "]" _
& rng.Parent.Name & "!" & rng.Address
'Sheet1.Cells(10, 10).Formula = "=VLOOKUP(A1," & fullRangeString & ",8,False)"
'close workbook if you need to
wb.Close False
End Sub