简体   繁体   中英

Insert Formula into cell using VBA?

I am trying to insert a formula into a cell using vba. This formula will need to have references to activecell.row range or dynamic reference.

I am using the following vba code:

Range("P" & ActiveCell.Row).Formula = "=IF(OR(G & ActiveCell.Row <>"",""H"" & ActiveCell.Row <>"",""I"" & ActiveCell.Row <>"",""J"" & ActiveCell.Row <>"",""M"" & ActiveCell.Row <>""),TODAY(),"")"

I get an Application defined or object defined error. Please can someone show me where i am going wrong? Thanks in advance.

assuming that what you want is this formula:

=IF(OR(G1<>"",H1<>"",I1<>"",J1<>"",M1<>""),TODAY(),"")

Try this

Range("P" & ActiveCell.Row).Formula = "=IF(OR(G" & ActiveCell.Row & "<>"""",H" & ActiveCell.Row & "<>"""",I" & ActiveCell.Row & "<>"""",J" & ActiveCell.Row & "<>"""",M" & ActiveCell.Row & "<>""""),TODAY(),"""")"

我会使用R1C1表示法和CountA()来简化一点

Range("P" & ActiveCell.row).FormulaR1C1 = "=if(counta(RC7:RC10,RC13)>0,Today(),"""")"

I think the issue is with the double-quotes. You have:

...).Formula = "=IF(OR(G & ActiveCell.Row <>"",""H"" & ActiveCell..."

While it should be:

...).Formula = "=IF(OR(G & ActiveCell.Row <>"""",""""H"""" & ActiveCell..."

Remember: In a string enclosed within -"- chars, any appearance of the same char within the string must be doubled.

Didn't check this though, but I quite sure this is an error (perhaps not THE error).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM