PDA

View Full Version : Vlookup not working when Table array refers to a cell with variable



Endered5
10-03-2020, 06:54 AM
Hi,

I have some problem with VBA coding when i want to make a Vlookup and the TableArray always starts from Column "A" to "K", but the rows can differ depending on the situation.

For example

Range("P1").Value = Range("O2").Value & Range("M2").Value
Range("P2").Value = Range("O3").Value & Range("M3").Value

I have written "A" in cell "O2" and "K" in cell "O3". M2 and M3 is a row number I will get from a formula. So lets say M2=10 and M3=20, this means my "P1" will be A10 and "P2" will be K20. So the table array i want in Vlookup is A10:K20. But somehow the code is wrong, when i use "ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-8], Indirect(P1): Indirect(P2), 10, FALSE)"

I have tried many and different solution, but it didnt work out. This is my latest, but failed solution. I attach a file since maybe my explanation is not that good. It is supposed to do Vlookup under any column under "Last week" and to get the "current week" comments.

The whole code is here:


ActiveCell.Offset(-2, -9).Select
ActiveCell.Copy
Range("M1").PasteSpecial

Range("M1") = Range("M1").Value

Range("M2") = "=Match(M1-4,A:A,0)"
Range("M3") = "=Match(M1-3,A:A,0)"
Range("M4") = "=Match(M1-0,A:A,0)"

Range("M4").Copy

Range("M10").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False

Range("M10") = Range("M10").Value
Range("M2") = Range("M2").Value
Range("M3") = Range("M3").Value

Range("P1").Value = Range("O2").Value & Range("M2").Value
Range("P2").Value = Range("O3").Value & Range("M3").Value

I = Range("M10").Value

Cells(I + 2, 10).Select

ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-8], Indirect(P1): Indirect(P2), 10, FALSE)"

End Sub

Bob Phillips
10-03-2020, 10:12 AM
You are only getting the cell address, you need the range of that address


Range("P1").Value = Range(Range("O2").Value & Range("M2").Value).Value
Range("P2").Value = Range(Range("O3").Value & Range("M3").Value).Value

Endered5
10-03-2020, 12:34 PM
You are only getting the cell address, you need the range of that address


Range("P1").Value = Range(Range("O2").Value & Range("M2").Value).Value
Range("P2").Value = Range(Range("O3").Value & Range("M3").Value).Value

I tried it, the value I get for "P1" is without "A". For "P2" I get nothing

Bob Phillips
10-04-2020, 10:51 AM
Nothing wrong with the code I gave, it all depends upon where you start and what gets injected into M1.