简体   繁体   中英

How to perform an excel vlookup with dynamic lookup_value using VBA?

I am new to VBA and need to perform a vlookup with a dynamic lookup_value . The reason for this is that the actual lookup_value column can be on different column indices for different input sheets.

The original vlookup formula looks like this:

"=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'static vlookup

What I am trying to accomplish should look like this:

1) Find the actual column index with the lookup_value inside (in the above case it's C2)

With ws
    Set FindRng = .Rows(1).Find(what:="Column Name") ' should be 3 for C
        FiltCol = FindRng.Column ' get the column number where "Column Name" was found
End With

2) Set lookup_value dynamically (in this case C2)

Dim dynamic_lookup_value as Range
dynamic_lookup_value = ws.Cells(FiltCol, 2) ' should be column C cell 2

3) Set dynamic reference to lookup_value to actual vlookup formula (ie repalce hardcoded C2 with reference to C2 )

foobar = "=VLOOKUP(dynamic_lookup_value,lookup!$A$2:$B$14,2,FALSE)" 'dynamic vlookup

However, (3) yields Run-time error '91' Object variable or With-block variable not set .

How to perform an excel vlookup with dynamic lookup_value using VBA?

first you have the columns and rows reversed here:

ws.Cells(FiltCol, 2)

It should be:

ws.Cells(2,FiltCol) 

Second you Set a range:

Set dynamic_lookup_value = ws.Cells(2,FiltCol) 

Then you do not put variables inside the quotes but concatenate them with &

foobar = "=VLOOKUP(" & dynamic_lookup_value.Address(0,0) & ",lookup!$A$2:$B$14,2,FALSE)" 

Another piece of advice:

FiltCol = FindRng.Column

Will error if the value is not found. Put it in an If statement to check if the value was found or not:

If  not FindRng is nothing Then
    ...
End IF

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM