I am trying to use VBA to to insert a formula in excel that would look like the following in excel:
=BDH(C2,"PX LAST",F2,"","Dir=H","days=w","DTS=H","cols=1;rows=1")
This actually represents just the first row of this formula, which I want to be copied down a certain column. Therefore I have to use a loop with index i
and then reference the appropriate cells with Cells notation, i.e. C2=Cells(i,3)
and F2=Cells(i,6)
. After looking through some discussions on this site and others, I know that in order to create a literal quote within a string, you use a double quote (""
).
formulaString = "=BDH(Cells" & CStr(i) & ",3),""PX LAST"",Cells(" & CStr(i) & ",6),"""",""Dir=H"",""days=w"",""DTS=H"",""cols=1;rows=1"")"
I want to insert these formulas in the 8th column of the corresponding row, so I do this with
Cells(i,8).Formula = formulaString
However, when I do this I get the error "application defined or object-defined error". I also saw that this can similarly be done with the code
Cells(i,8).Value = Evaluate(formulaString)
This does not throw an error, but when it runs the cells in which I want the formula read #Value
.
Could someone please help me identify what I am doing wrong?
You should not be putting the
Cells
inside the formula string, and you should be using theAddress
property:However what you actually want is switching to the R1C1 notation:
and then using