简体   繁体   English

Excel 2003 VBA:将公式写入单元格

[英]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. 我试图将一个公式写入一个范围并得到以下消息:运行时错误'1004':应用程序定义或对象定义的错误。 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 ; Range.Formula属性使用的是英语默认值,即您需要替换德语的分隔符; 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. 为了完整Range.FormulaLocal :您还可以使用Range.FormulaLocal属性,在其中可以提供德语公式。 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. 目前,您要在不调整行号的情况下在每个单元格中放置相同的公式,即,根据第2行中的输入,每行将具有相同的结果。您可以构建每个公式,用一个计数器替换2。 Or much easier, use the RC1 notation: 或者更容易使用RC1表示法:

     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: 相反,只需将您的For循环替换为此行:

     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! 这样,您甚至都不必担心引用,因为Excel会自动应用正确的公式!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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