I'm trying to program a VLookup in VBA that references another workbook. Basically I'm trying to vlookup across 2 workbooks.
Here is a simple outline of my goal:
- Look up values in all rows in column A of workbook1
- Pull the information in from column A (values that correspond to Column A in workbook1) and Column C (values to be copied) of workbook2 and place in column B of workbook1 in the corresponding cells (rows). Additional conditions: (1) if there are already values in the cells, overwrite and (2) if no value has been found for a cell, then keep cell unchanged. So also no #N/A.
- Move on and repeat the process until there are no more entries left in column A of workbook1
Below is the code that I already have. I stumble upon the fact that the code does not work. I keep getting #N/As for each row in column B, while there should at least be some values found and pasted into some cells. For testing purposes, I copied the reference table in workbook2 to a worksheet in workbook1 and when I reference to that specific worksheet in the same workbook1 then the code seems to work.
Sub Import()
Dim rw As Long, x As Range
Dim extwbk As Workbook, twb As Workbook
Set twb = ThisWorkbook
Set extwbk = Workbooks.Open("C:\Documents\workbook2.csv")
Set x = twb.Worksheets("Sheet1").Range("A1:H100")
With twb.Sheets("Sheet1")
For rw = 2 To .Cells(Rows.Count, 1).End(xlUp).Row
.Cells(rw,2) = Application.Vlookup(.Cells(rw,1).Value2,x,3,False)
Next rw
End With
End Sub
Do you see an error in my code? Or does anyone have a better way of accomplishing this task? Preferably, I also would like to open a selected file instead of referring to a full path.
Thanks in advance!