简体   繁体   中英

excel 2003 vba: write formula into cell

I tried to write a formula into a range and get the following message: Run-time error '1004': Application-defined or object-defined error. I use the following code but I don't understand why this is not working:

LastRow = Sheets("Source").Cells(Rows.Count, "B").End(xlUp).Row

For Each cell In Sheets("Target").Range("I2:I" & CStr(LastRow)).Cells

    cell.Formula = "=IF(D2=E2;""OLD"";""NEW"")"

Next

As already indicated in the comments, you're facing an issue with the regional settings. The Range.Formula property is using the English default, ie you need to replace the German separator ; with , . This way it is ensured that your code will run on any language version.

For completeness: You can also use the Range.FormulaLocal property, where you can provide the German formula. However, I would strongly recommend to use this property read-only (if at all). If you write a formula with this property, you're code is guaranteed to break on any non-German system!

Two more comments on your code though:

  1. At the moment, you're placing the same formula in each cell without adjusting the row number, ie each row will have the same result based on the input in row 2. You could either build each formula, replacing the 2 with a counter. Or much easier, use the RC1 notation:

     cell.FormulaR1C1 = "=IF(RC[-5]=RC[-4],""OLD"",""NEW"")" 
  2. There is actually no need to loop and allocate the formula to each cell individually. Instead, simply replace your For loop with this line:

     Sheets("Target").Range("I2").Resize(LastRow-1).Formula= _ "=IF(D2=E2,""OLD"",""NEW"")" 

This way, you don't even need to bother about the references, as Excel automatically apply the right formula!

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