Doing a VLOOKUP function i use 1 column from sheet1 and 2 columns from sheet "Files" inside the same workbook. I have a problem with defining range from sheet called "Files":
Sub VLOOKUP()
Dim Dept_Row, Dept_Clm As Long
Dim LastRowA, LastRowB As Long
Set currentsheet = ActiveWorkbook.Sheets(1)
ctr = 0
LastRowB = currentsheet.Range("B" & Rows.Count).End(xlUp).Row
LastRowA = Sheets("Files").Range("A" & Rows.Count).End(xlUp).Row
Table1 = currentsheet.Range("B11:B" & LastRowB)
Table2 = Sheets("Files").Range("A1:A" & LastRowA)
Dept_Row = currentsheet.Range("F11").Row
Dept_Clm = currentsheet.Range("F11").Column
For Each cl In Table1
currentsheet.Cells(Dept_Row, Dept_Clm).FormulaR1C1 = "=VLOOKUP(RC[-4], Files!R1C1:R & LastRowA & Files!C2, 2, False)"
Dept_Row = Dept_Row + 1
ctr = ctr + 1
Next cl
'Sal = Application.VLOOKUP(currentsheet.Range("B11").Value, ActiveWorkbook.Sheets("Files").Range("$A$1:$B$" & LastRowA), 1, False)
End Sub
The problem appears at line currentsheet.Cells(Dept_Row, Dept_Clm).FormulaR1C1 = "=VLOOKUP(RC[-4], Files!R1C1:R & LastRowA & Files!C2, 2, False)"
or
Sal = Application.VLOOKUP(currentsheet.Range("B11").Value, ActiveWorkbook.Sheets("Files").Range("$A$1:$B$" & LastRowA), 1, False)
.
I found similar topics here: Using VBA to enter a vlookup function in a cell using user chosen file and VBA Vloopup using 2 different workbooks
But did not manage to make it work. Maybe someone could help, how to define range in the right way, using different Sheets and LastRow as a variable? Thanks!
Rows
. When used asRows
it refers to theActivesheet
of theActiveworkbook
. You might want to trycurrentsheet.Rows
instead, and the same for the other sheet. Also, yourDept_Row
andLast_Row
variables are actuallyVariant
, notLong
.. You might want to declare them explicitly asLong
. One more thing: I hope the actualSub
name is notVLOOKUP()
? :) – Ioannis