Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime error 1004 when inserting formula into cell VBA Excel

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
like image 524
J.Fleming Avatar asked Apr 21 '26 21:04

J.Fleming


1 Answers

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.