I am getting runtime error 1004 when trying to insert a formula into a cell in VBA.
In my excel sheet I have a date in column A and a stock ticker in row 1 starting in column B every 3 columns, so B, E, H etc.
In cell C2 I am trying to divide the value in B2 by the value in row 2 under the column heading "FTSE". Putting this formula into the cell directly works:
=IFERROR(B2/(VLOOKUP($A2,$A$2:$GMQ$261,MATCH("FTSE",$B$1:$GMQ$1,0)+1,FALSE)),"")
I am trying to do this using vba. This is the code I have:
Sub InsertFormula()
Range("C2").Select
ActiveCell.Formula = _
"=IFERROR(B2/(VLOOKUP($A2,$A$2:$GMQ$261,MATCH(""FTSE"",$B$1:$GMQ$1,0)+1,FALSE)),"")"
End Sub
You can reduce the confusion generated by double-double-quotes¹ with the TEXT function used as TEXT(,). This returns a zero-length string just as "" does and there are no quotes to double up like """".
Range("C2").Formula = _
"=IFERROR(B2/(VLOOKUP($A2, $A$2:$GMQ$261, MATCH(""FTSE"", $B$1:$GMQ$1 ,0)+1, FALSE)), TEXT(,))"
'without the offset and subsequent adjustment with full column references
Range("C2").Formula = _
"=IFERROR(B2/VLOOKUP($A2, $A:$GMQ, MATCH(""FTSE"", $1:$1 ,0), FALSE), TEXT(,))"
¹ See How to create strings containing double quotes in Excel formulas? for more examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With