Application.VLookup function always returns #N/A - vba

I am trying to use the Application.VLookup function in Visual Basic to find a value in a different workbook. However, whenever I use it, it always returns #N/A.
This is the layout of my function. LastRow() just returns the row number of the last row. SHORTAGE_SBT is a variable containing the source workbook name. SBT_Last is the last row of SHORTAGE_SBT. The ID that I'm searching with in in the B column, hence why I use "B" & ind to refer to it.
For ind = 4 To LastRow()
Range("H" & ind).Select
ActiveCell.Value = Application.VLookup("B" & ind, Workbooks(SHORTAGE_SBT).Sheets(1).Range("A14:DZ" & SBT_Last), Range("DZ1").Column, False)
Next
I have tried recording a macro for VLookup to see if it would help me understand the problem. The macro gave me this function, which worked but could not be used because it contains the hardcoded file name instead of using the variable.
Range("H" & ind).FormulaR1C1 = "=VLOOKUP(RC[-6],'[filename.xls]Sheet1'!R14C1:R2382C130, COLUMN(R[-3]C[122]), FALSE)"
I cannot see any significant difference between the way the macro lays out the arguments of the function as opposed to mine, other than using more direct references. I have tried using direct numbers in my code but doing so hasn't helped either.

Application.VLookup("B" & ind, Workbooks(SHORTAGE_SBT).Sheets(1).Range("A14:DZ" & SBT_Last), Range("DZ1").Column, False)
"B" & ind will be searched for "literally"; it will not be transformed into a range address because it is interpreted here by VBA, not by Excel. Try:
Application.VLookup(Range("B" & ind), Workbooks(SHORTAGE_SBT).Sheets(1).Range("A14:DZ" & SBT_Last), Range("DZ1").Column, False)
' ^^^^^^^^^^^^^^^^

Combine the two approaches:
Range("H" & ind).FormulaR1C1 = _
& "=VLOOKUP(RC[-6],'[" & Workbooks(SHORTAGE_SBT) _
& "]Sheet1'!R14C1:R2382C130, COLUMN(R[-3]C[122]), FALSE)"

Related

Writing a formula with concatenated parts into a cell

Scenario: I have a code that should write a formula to a worksheet cells. This formula is for an API to retrieve some value. My formula is inside a loop (this is done for multiple columns) and references the first row for an identifier.
The original formula:
=FS(B1;"FI(DATE,,DATE)")
The modified formula with the floating reference (inside the loop):
For i = 1 To lColumn
If wb.Worksheets("Dates").Cells(i, 1).Value <> "" Then
wb.Worksheets("Dates").Cells(i,2).value = "=FS(" & i & "1;"FI(DATE,,DATE)")"
End If
Next i
Where lColumn is some pre-defined number.
Issue: I keep getting the "Unexpected end of statement" error in the formula part of the loop.
What I already tried: I tried different variations, repositioning the "s and 's, for example:
wb.Worksheets("Dates").Cells(i,2).value = "'"=FS(" & i & "1;"FI(DATE,,DATE)")""
or
wb.Worksheets("Dates").Cells(i,2).value = "'=FS(" & i & "1;"FI(DATE,,DATE)")"
or
wb.Worksheets("Dates").Cells(i,2).value = "'""=FS(" & i & "1;"FI(DATE,,DATE)")"
and so on. But the error still persists.
Question: What is the proper way to do this operation?
Working with formulas in VBA is a little bit tricky:
To write a formula, use the range.formula property, not the .value.
You have to write the formula as if you are using an english Excel. Parameter-separator is comma (not semicolon).
If a formula needs a quote, double it so that the VBA compiler understands that you want a quote within a string.
I find it helpfull to write a formula into a variable before assigning it - you can check in the debugger if it is exactly how it should before assigning it.
To check how the formula should look like, write it into a cell, change to the VBA-editor, open the immediate window and write ? activecell.formula
Try (untested as the formula you need is not valid to us):
with wb.Worksheets("Dates")
dim f as string, adr as string
adr = cells(i, 1).address(false, false) ' get rid of Dollar signs
f = "=FS(" & adr & ",""FI(DATE,,DATE)"")"
.Cells(i, 2).formula = f
end with
wb.Worksheets("Dates").Cells(i,2).formula = "=FS(" & Cells(1, i).Address(0,0) & ";""FI(DATE,,DATE)"")"
There may be a better way to convert the column number to a letter (which is the problem you are having, along with the double quotes)!

VBA CountIFS With Multiple Criteria

I have a VBA procedure that scans a worksheet and produces counts where cell C is not equal to certain colors, but column I is set to one value. This is the procedure:
FormulaR1C1 = "=COUNTIFS(Sheet1!C[-2],RC[-2],Sheet1!C,""<>Red"",
Sheet1!C,""<>Blue"",Sheet1!C,""<>Green"",Sheet1!C,""<>Black"",
Sheet1!C,""<>Purple"",Sheet1!C,""<>White"",
Sheet1!C[6],""Temp"")"
Conditions have changed and I need to add in another criteria for count condition so I thought it would be a quick fix of adding in a comma and the criteria to the end like this
FormulaR1C1 = "=COUNTIFS(Sheet1!C[-2],RC[-2],Sheet1!C,""<>Red"",
Sheet1!C,""<>Blue"",Sheet1!C,""<>Green"",Sheet1!C,""<>Black"",
Sheet1!C,""<>Purple"",Sheet1!C,""<>White"",
Sheet1!C[6],""Temp"",Sheet1!C[6],""Perm"")"
However - now this always returns 0. What is the correct way to add in a secondary condition in VBA to a CountIFS()
EDIT
That second parameter I want to add, should be an "OR" condition as well, so Sheet1!C[6] = Temp OR Perm
EDIT 2
I tried to edit my syntax like this
FormulaR1C1 = "=COUNTIFS(Sheet1!C[-2],RC[-2],Sheet1!C,""<>Red"",
Sheet1!C,""<>Blue"",Sheet1!C,""<>Green"",Sheet1!C,""<>Black"",
Sheet1!C,""<>Purple"",Sheet1!C,""<>White"",
Sheet1!C[6],""Temp"")"
+
"COUNTIFS(Sheet1!C[-2],RC[-2],Sheet1!C,""<>Red"",
Sheet1!C,""<>Blue"",Sheet1!C,""<>Green"",Sheet1!C,""<>Black"",
Sheet1!C,""<>Purple"",Sheet1!C,""<>White"",
Sheet1!C[6],""Perm"")"
but this gives me an error of
application defiend or object defined error
Dim f
f = "=COUNTIFS(Sheet1!C[-2],RC[-2],Sheet1!C,'<>Red'," & _
"Sheet1!C,'<>Blue',Sheet1!C,'<>Green',Sheet1!C,'<>Black'," & _
"Sheet1!C,'<>Purple',Sheet1!C,'<>White'," & _
"Sheet1!C[6],'Temp') + COUNTIFS(Sheet1!C[-2],RC[-2],Sheet1!C,'<>Red'," & _
"Sheet1!C,'<>Blue',Sheet1!C,'<>Green',Sheet1!C,'<>Black'," & _
"Sheet1!C,'<>Purple',Sheet1!C,'<>White',Sheet1!C[6],'Perm')"
FormulaR1C1 = Replace(f, "'", """")

VBA FormulaR1C1 property across new sheet and multiple columns

I'm afraid I can't wrap my head around the FormulaR1C1 property when trying to find multiple columns in another sheet, I have these formulas currently (very slowly) autofilling:
LastRow = Range("A" & Rows.Count).End(xlUp).Row
Range("F2:F" & LastRow).FormulaR1C1 = "=IFERROR(VLOOKUP(R2,LU!C[1]:C[5]),"""")"
Range("F2:F" & LastRow).Formula = _
"=IFERROR(VLOOKUP(A2,LU!A:E,2,true),"""")"
Range("G2:G" & LastRow).Formula = _
"=IFERROR(VLOOKUP(A2,LU!A:E,3,true),"""")"
Range("H2:H" & LastRow).Formula = _
"=IFERROR(VLOOKUP(A2,LU!A:E,4,true),"""")"
Range("I2:I" & LastRow).Formula = _
"=IFERROR(VLOOKUP(A2,LU!A:E,5,true),"""")"
Range("J2:J" & LastRow).Formula = _
"=COUNTIF(A:A,'Pivot Counter'!A7)"
You can see in the top formula, I've attempted it to no success. I keep getting an application defined error, but don't know enough about the property to fix it.
The formula
Range("F2:F" & LastRow).Formula ="=IFERROR(VLOOKUP(A2,LU!A:E,2,true),"""")"
converted to R1C1 reference style is
Range("F2:F" & LastRow).FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-5],LU!C[-5]:C[-1],2,True),"""")"
To understand it completely considering the following:
the cell location where you enter the formula is the starting point
starting column is F
column A is 5 columns to the left of F, so A2 converts to RC[-5] (same row, 5 columns to the left of starting point (or think of 6th column (F) and move -5 from there))
same principle for the range lookup. You want to look in columns A:E in sheet LU. So -5 columns from column F (remember starting point is column F, even though it's now looking at a different sheet) to -1 column
Knowing this, you can convert the other formulas, even the COUNTIF.
Also, if you get stuck again, following #BruceWayne's suggestion of turning R1C1 reference style under Excel > Options > Formulas to see what the formula would be when you type in manually.

VBA 1004 error : Application defined or object defined error

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?
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)"
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.

Specifying cells and sheets in formula using VBA

I need my macro to input the following formula:
Worksheets("U_NEDC_COLD_online_0").Cells(3, A).formula = "=IF(" & Worksheets (U_NEDC_COLD_online_0).Cells(3, AA).Value & "=" & Worksheets(U_NEDC_COLD_online).Cells(3, AA).Value & ";" & Worksheets(U_NEDC_COLD_online).Cells(3, A).Value & ";" & Worksheets(U_NEDC_COLD_online_0).Cells(3, A).Value & ")"
I've also tried the same formula with the ".Address" property and it doesn't work. What am I doing wrong?
The final formula should look like this:
=IF($AA3 = U_NEDC_COLD_online!$AA3; U_NEDC_COLD_online!A3; U_NEDC_COLD_online_0!A3)
PS: Worksheets("U_NEDC_COLD_online_0") is not the same as Worksheets(U_NEDC_COLD_online_0). (its not a typo)
Thanks.
Use commas instead of semicolons to separate the arguments of the IF statement.
Your formula appears to have a circular relationship; the formula is going into cell A3 and references cell A3... I'll leave that to you to work out.
Always use Option Explicit. Once you put that line at the top of your module, you'll get the error: Variable not defined for the variables: A, AA, and possibly U_NEDC_COLD_online and U_NEDC_COLD_online_0 that you probably intended to use as string literals. (see next bullet for a workaround)
If U_NEDC_COLD_online_0 is truly a variable/constant name and is not equal to the string literal that you use elsewhere (e.g. U_NEDC_COLD_online_0), you should really change the variable name to something else!
If the only reason you are dynamically building the formula is to accommodate variable row indexes, use this where the 3 can be replaced by a variable:
Worksheets("U_NEDC_COLD_online_0").Cells(3, 1).Formula = "=IF($AA" & 3 & "=" & "U_NEDC_COLD_online!AA" & 3 & ", U_NEDC_COLD_online!A" & 3 & ", A" & 3 & ")"
If you don't even need variable row indexes, just use this:
Worksheets("U_NEDC_COLD_online_0").Range(A3).Formula = "=IF($AA3=U_NEDC_COLD_online!AA3, U_NEDC_COLD_online!A3, A3)"