Excel – VBA reference to a table in different worksheet

definitionexcelexternalvba

I'm trying to use vlookup in VBA.

  1. Filename = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls), *.xls", Title:="Please select a file")
  2. Table1 = Sheet1.Range("A3:A7000") ' SiteID
  3. Table2 = [Filename]Sheet1.Range("A3:I13")
  4. Roww = Sheet1.Range("E2").Row
  5. Coll = Sheet1.Range("E2").Column
  6. For Each cl In Table1
  7. Sheet1.Cells(Roww, Coll) = Application.WorksheetFunction.VLookup(cl, Table2, 1, False)
  8. Roww = Roww +1
  9. Next cl

My question is how do I define the table located in different worksheet/file on line 3?

Best Answer

This should work:

Sub vLook()

Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Range1, myValue
Set wb1 = ThisWorkbook
Set wb2 = Workbooks.Open("C:\Code\Book4.xlsx")

Range1 = wb2.Sheets(1).Range("A1:C5")
myValue = Application.WorksheetFunction.VLookup("Test", Range1, 2, False)

End Sub
Related Topic