简体   繁体   English

使用VBA在Excel单元格中编写公式

[英]Write a formula in an Excel Cell using VBA

I'm trying to use VBA to write a formula into a cell in Excel. 我正在尝试使用VBA将公式写入Excel中的单元格。 My problem is that when I use a semicolon ( ; ) in my formula, I get an error: 我的问题是,当我在公式中使用分号( ; )时,我收到一个错误:

Run-time error 1004

My macro is the following : 我的宏如下:

Sub Jours_ouvres()
    Dim Feuille_Document As String
    Feuille_Document = "DOCUMENT"        
    Application.Worksheets(Feuille_Document).Range("F2").Formula = "=SUM(D2;E2)"    
End Sub

You can try using FormulaLocal property instead of Formula. 您可以尝试使用FormulaLocal属性而不是Formula。 Then the semicolon should work. 然后分号应该工作。

Treb, Matthieu's problem was caused by using Excel in a non-English language. Treb,Matthieu的问题是由于使用非英语语言的Excel引起的。 In many language versions ";" 在许多语言版本中“;” is the correct separator. 是正确的分隔符。 Even functions are translated (SUM can be SOMMA, SUMME or whatever depending on what language you work in). 甚至函数都被翻译(SUM可以是SOMMA,SUMME或其他任何取决于你使用的语言)。 Excel will generally understand these differences and if a French-created workbook is opened by a Brazilian they will normally not have any problem. Excel通常会理解这些差异,如果法语创建的工作簿由巴西人打开,他们通常不会有任何问题。 But VBA speaks only US English so for those of us working in one (or more) foreign langauges, this can be a headache. 但是VBA只说美国英语,所以对于我们这些在一个(或多个)外国语言工作的人来说,这可能是个头疼的问题。 You and CharlesB both gave answers that would have been OK for a US user but Mikko understod the REAL problem and gave the correct answer (which was also the correct one for me too - I'm a Brit working in Italy for a German-speaking company). 你和CharlesB都给出了一个美国用户可以接受的答案,但是Mikko低估了真正的问题并给出了正确的答案(这对我来说也是正确的答案 - 我是一个英国人在意大利工作,讲德语公司)。

在这种情况下,以使用正确的字符是一个完整的冒号( : ),而不是一个分号( ; )。

The correct character (comma or colon) depends on the purpose. 正确的字符(逗号或冒号)取决于目的。

Comma ( , ) will sum only the two cells in question. 逗号( , )将仅对所讨论的两个单元格求和。

Colon ( : ) will sum all the cells within the range with corners defined by those two cells. 冒号( : )将总结所有小区的范围内与由这两个小区中定义的角。

I don't know why, but if you use 我不知道为什么,但如果你使用

(...)Formula = "=SUM(D2,E2)"

(' , ' instead of ' ; '), it works. (' '而不是' ; '),它有效。

If you step through your sub in the VB script editor (F8), you can add Range("F2").Formula to the watch window and see what the formular looks like from a VB point of view. 如果在VB脚本编辑器(F8)中单步执行子程序,则可以在监视窗口中添加Range("F2").Formula ,并从VB的角度查看公式。 It seems that the formular shown in Excel itself is sometimes different from the formular that VB sees... 似乎Excel中显示的公式有时与VB看到的公式不同......

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

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