Hello,
I have this code below and I am trying to convert Vlookup function into VBA. I have a little database called “MyDatabase" in a separate workbook, first sheet. My lookup starts comparison of column “B” from “WorkingFile” to “MyDatabase” of column “B”. Position of these columns is fixed, so there is no need to make them dynamic. Once there is a match, corresponding value in column “E” (Offset(0,3) from “MyDatabase” file should be copied to corresponding column “E” (Offset(0,3) in destination file which is “WorkingFile”.
When I ran this code I’ve got “Compile error: Statement invalid outside Type block” and it points to lrow1 variable that I set up as integer. I tried to change it to Long and it didn’t work. Please let me know what is wrong with my codes. Data type that I am trying to look up is numbers.
Thanks a lot!
I have this code below and I am trying to convert Vlookup function into VBA. I have a little database called “MyDatabase" in a separate workbook, first sheet. My lookup starts comparison of column “B” from “WorkingFile” to “MyDatabase” of column “B”. Position of these columns is fixed, so there is no need to make them dynamic. Once there is a match, corresponding value in column “E” (Offset(0,3) from “MyDatabase” file should be copied to corresponding column “E” (Offset(0,3) in destination file which is “WorkingFile”.
When I ran this code I’ve got “Compile error: Statement invalid outside Type block” and it points to lrow1 variable that I set up as integer. I tried to change it to Long and it didn’t work. Please let me know what is wrong with my codes. Data type that I am trying to look up is numbers.
Thanks a lot!
Code:
Sub MyLookup()
'Define variables
Dim wb1 As Workbook
Dim wb2 As Workbook
lrow1 As Integer
lrow2 As Integer
c1 As Range
c2 As Range
'Define workbooks
Set wb1 = Workbooks("MyDatabase.xlsx")
Set wb2 = Workbooks("WorkingFile.xlsx")
'Define last row of each column in each workbook for vlookup
lrow1 = wb1.Sheets(1).Range("B" & Rows.Count).End(xlUp).Row
lrow2 = wb2.Sheets(1).Range("B" & Rows.Count).End(xlUp).Row
'Loop through column B of MyDatabase and test if there is anything matching with column B in WorkingFile
'Once found value in MyDatabase copy value from 3rd column to 3rd column on WorkingFile
For Each c1 In lrow1
If c1.Value <> "" Then
For Each c2 In lrow2
If c1.Value = c2.Value Then
c1.Offset(0, 3).Value = c2.Offset(0, 3).Value
Exit For
End If
Next c2
End If
Next c1
End Sub