0

I am a novice at Excel VBA and am running into an error 1004 while compiling a portion of the code:

Cells(i, j).Formula = _"=vlookup(Cells(i,1).Value,SKULifeCycle_Table_Temp!R1C1:R5000C500,match(Cells(1,j).Value,'SKULifeCycle_Table_Temp'!R1C1:R1C500,0),0)"

i and j have been defined previously as integers and are part of a for loop. Could anyone please help me out on this?

2 Answers 2

3

A few things wrong there:

First, you're using the literal text "Cells(i, 1).Value" and "Cells(1, j).Value" in the formula string. You would need to concatenate the values into the string like this:

Cells(i, j).FormulaR1C1 = "=vlookup(" & Cells(i,1).Value & ",SKULifeCycle_Table_Temp!R1C1:R5000C500,match(" & Cells(1,j).Value & ",'SKULifeCycle_Table_Temp'!R1C1:R1C500,0),0)"

Second, you used the .Formula property but passed R1C1 style references, so you should use the .FormulaR1C1 property (as I did above).

Third, if the values in the cells that you are using for the lookup values are text, you need to enclose them in quotes:

    Cells(i, j).FormulaR1C1 = "=vlookup(""" & Cells(i,1).Value & """,SKULifeCycle_Table_Temp!R1C1:R5000C500,match(""" & Cells(1,j).Value & """,'SKULifeCycle_Table_Temp'!R1C1:R1C500,0),0)"

or use the addresses (in R1C1 format) instead:

Cells(i, j).FormulaR1C1 = "=vlookup(RC1,SKULifeCycle_Table_Temp!R1C1:R5000C500,match(R1C,'SKULifeCycle_Table_Temp'!R1C1:R1C500,0),0)"
Sign up to request clarification or add additional context in comments.

Comments

1

One issue that is clear (maybe the cause of the whole error), is that variables are being used within a string. So, what does that mean? I'll simplify using the code below as a template:

Sub Test1()
    Dim i as Integer
    Dim j as Integer

    i = 2
    j = 3

    Cells(i, j).Value = "The row number is i and the column number is j"
End Sub

In the Cells line, it correctly refers to cell C2, which is the second row and third column. But what value is inserted into the cell? It's literally "The row number is i and the column number is j" using the letters, and not their corresponding numbers. Similarly, in your case, the formula will read: VLOOKUP(CELLS(i,1)... using the letter i, which is incorrect.

Additionally, a cell's formula doesn't use the CELLS syntax. You instead need to build a string using the variables. It would look a lot like:

"=VLOOKUP(" & Cells(i, 1).Address & "SKULifeCycle_Table_Temp!R1C1:R5000C500, Match(" & Cells(i, 1)Address ... "

Try to build out your formula string and refer back to this post with any specific questions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.