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, ie 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 the Address
property:
formulaString = "=BDH(" & Cells(i,3).Address(False, False) & ",""PX LAST""," & Cells(i,6).Address(False, False) & ","""",""Dir=H"",""days=w"",""DTS=H"",""cols=1;rows=1"")"
However what you actually want is switching to the R1C1 notation :
formulaStringR1C1 = "=BDH(RC3,""PX LAST"",RC6,"""",""Dir=H"",""days=w"",""DTS=H"",""cols=1;rows=1"")"
and then using
Cells(i,8).FormulaR1C1 = formulaStringR1C1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.