Writing a formula with concatenated parts into a cell - vba

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)!

Related

VBA script to insert INDEX/MATCH formula with dynamic reference/arrays

I'm looking to simply insert an INDEX/MATCH formula in the column next to an existing selection (this will be part of a larger Sub). The reference/look-up array in the formula needs to be dynamic.
So far I've managed to successfully insert the formula. However, the reference/lookup-arrays have been manually input by me as I know the current Range (which is likely to change):
Selection.Offset(0, 1) = "=INDEX($J$3:$J$31,MATCH(INDIRECT(""RC[-2]"",0),$H$3:$H$31,0))"
How can I amend the $J$3:$J$31 and the $H$3:$H$31 to update dynamically? I've had success separately with something like 'Range("J3", Range("J3").End(xlDown))', but I can't seem to work it into the code above.
You can integrate variables into the formula, it becomes a bit tricky, and I imagine there are better ways to accomplish this, but it's the method I use when I need dynamic ranges in formulas in VBA. I'll provide an example below that should help:
I'm assuming the J3 and H3 will remain the same, but the end of the range is what you expect to change. If this is not the case, let me know.
You're essentially replacing the "31" in your range reference with " & [variable] & " (quotes included).
EDIT: I use Sheet1 as an example for the row count; so just update that to whatever the applicable sheet & range would be.
Dim rCount As Long
rCount = Sheet1.Range("A" & Rows.Count).End(xlUp).Row
Selection.Offset(0, 1) = "=INDEX($J$3:$J$" & rCount & ",MATCH(INDIRECT(""RC[-2]"",0),$H$3:$H$" & rCount & ",0))"

Application.VLookup function always returns #N/A

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

How do I set a formula in a cell using R1C1 notation from variables?

I've got a series of IF/ELSE clauses to see if items fit into one of three categories. If an item doesn't fit into any of them, its category field should simply read "SELECT".
Now, with simple text strings it works fine. But I also want to include a simple formula (as in most of the other autopopulated fields in the sheet) to blank the field if it's on an empty line. Based on the code I've used in other cases, I would want to set the cell's formula to
=IF(ISBLANK($A2, "", "SELECT")
(...where the cell itself is B2)
Problem is, the cell to look at will depend on which line it's on; A2, A3, A4 and so on. The column number remains constant, but the row number is defined by the variable iImportCounter.
I've tried both .Value and .Formula, both """ and Chr(34), and it still doesn't seem to work. The full code for that line as it stands is
Else:
wsCalc.Cells(iImportCounter, 3).Formula = "=IF(ISBLANK($" & Application.ConvertFormula(Cells(iImportCounter, 2), xlA1) & ", " & Chr(34) & Chr(34) & ", " & Chr(34) & "SELECT" & Chr(34) & ")"
Is there something terribly obvious I'm missing?
I've seen comments elsewhere that the fact that it's in a module rather than a sheet-based macro could make some of that code malfunction, but I'm not sure what or how.
It depends on what the iImportCounter starts at. If it is 3 (row 3 in B3) then the formula would be,
with wsCalc.Cells(iImportCounter, 3)
.FormulaR1C1 = "=IF(ISBLANK(R[-1]C1), """", ""SELECT"")
end with
The R in RC1 means the same row that you are putting the formula on so if you are putting on row 2 and you want to reference A2 then R is all you need. If the formula is going into B3 then you need to reference the current row minus 1 with R[-1]C1.
The C1 in RC1 means a 'locked' (absolute) column A (the first column). This doesn't seem absolutely necessary as the formula does not travel laterally.
Assuming wsCalc is a reference to a range of cells:
wscalc.FormulaR1C1 = "=IF(ISBLANK(RC1),"""",""SELECT"")"
As a working example:
Sub Test()
ThisWorkbook.Worksheets("Sheet1").Range("B1:B10").FormulaR1C1 = "=IF(ISBLANK(RC1),"""",""SELECT"")"
End Sub

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.

Convert Excel array formula VBA

I'm trying to do "vlookup" with 2 different criteria(Column A and G values) using "Index" and "Match" functions.
and here is the line i used for the Excel command.
=INDEX(Database!A:KG,MATCH(1,(Database!A:A='TempSheet'!A2)*(Database!G:G='TempSheet'!G2),0),10)
How would I do it with VBA? It's keep giving me the error message "Compile error: Expected end of statement".
Selection= _
"=Index(DB.Range("A:KG"), Match(1, (DB.Range("A" = Temp.Range("A" & i).Value)) * (DB.Range("G" = Temp.Range("G" & i).Value)), 0), 10)"
Thanks
Every time you use a spreadsheet formula inside a VBA code, you need to precede it with <Excel.WorksheetFunction.> or <Application.WorksheetFunction.>.
For example:
Application.WorksheetFunction.Match
instead of Match only.
I have had little luck getting array formulas to work correctly via VBA, and use the 'IFERROR' as a workaround like so:
=IFERROR(VLOOKUP(A1, Database!A:Z,1,FALSE),VLOOKUP(B1, Database!A:Z,1,FALSE))
This function will attempt to match A1, and in case of a #VALUE error, it will match B1.
To get this kind of formula populated on a sheet in VBA, you can loop down your sheet using the '.formula' approach.
' get length of source data
Dim RowCount As Long
RowCount = ThisWorkbook.Sheets("Database").Cells(Rows.Count, 1).End(xlUp).Row
' now starting from row 2 to preserve headings
For i = 2 To RowCount
ThisWorkbook.Sheets("Summary").Cells(i, 1).Formula = "=IF(ISERROR(SEARCH(""ISO"",V" & i & ")),""Order type not supported"",""Transit"")"
ThisWorkbook.Sheets("Summary").Cells(i, 6).Formula = "=IFERROR(TEXT(VLOOKUP(B" & i & ",Database!A:N,7,FALSE),""dd-mmm-yyyy HH:MM AM/PM""),"""")"
Next
Not exactly what you were after, but hope it helps!