Reputation: 1
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
Upvotes: 0
Views: 9810
Reputation: 17475
As already indicated in the comments, you're facing an issue with the regional settings. The Range.Formula
property is using the English default, i.e. 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:
At the moment, you're placing the same formula in each cell without adjusting the row number, i.e. 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"")"
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!
Upvotes: 1