简体   繁体   中英

VBA: Using VLOOKUP formula with a dynamic lookup_value

I am trying to embed a VLOOKUP formula into my last column after performing formatting on a sheet. My lookup value is for a column that has the following column header: "Company State". This is my current flow:

  1. Find the Column number with the Column Header: "Company State":

    CompanyStateColumnNumber = WorksheetFunction.Match("Company State", ws.Range("1:1"), 0)

  2. Declare the range for lookup. In this case, it exists in a worksheet/workbook that is not the active workbook/worksheet. Hence, I am referencing it using ( I have already declared TZsrcRange as a Range type):

    Set TZsrchRange = TemplateWS.Range("A:C")

  3. Now, I am trying to embed the vlookup into my last column (I found my last column in the sheet and it is stored in the variable " NewestLCol". I want to embed it into the column until the very last row (stored in variable "LastRow") :

     For x = 2 To LastRow Set dynamic_lookup_value = Cells(x, CompanyStateColumnNumber) Cells(x, NewestLCol).Formula = " =VLOOKUP(" & _ dynamic_lookup_value.Address(0, 0) & _ ", Templatews.Range(A:C).Address(0,0),3, FALSE)" Next x
  4. Now, when I run it, it doesn't embed the formula and doesn't give me a value. What could my issue be?

Try replacing your formula assignment with this one

Cells(x, NewestLCol).Formula = "=VLOOKUP(" & _
                                dynamic_lookup_value.Address(0, 0) & _
                                "," & _
                                TZsrchRange.Address(External:=True) & _
                                ",3, FALSE)"

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