tags:

views:

11483

answers:

5

Hello,

I'm trying to use VBA to write a formula into a cell in Excel. My problem is that when I use a semicolon (;) in my formula I get an 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


Thanks in advance,

Matthieu

+5  A: 

The correct character to use in this case is a full colon (:), not a semicolon (;).

e.James
A: 

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. It seems that the formular shown in Excel itself is sometimes different from the formular that VB sees...

Treb
That formula adds only cells D2 and E2. It works in this case, because that range only had two cells. If the range was D2:G2, for example, using the comma would add only the first and last cells in the range: D2 and G2, not all four of them.
e.James
To the downvoters: While eJames is correct in his more genereic answer, my answer is correct in this specific case. If you downvote, explain why.
Treb
A: 

Thanks Treb, it's Working.

Matthieu
Please read my comment above in case you ever use this for a range that has more than two cells in it!
e.James
+3  A: 

You can try using FormulaLocal property instead of Formula. Then the semicolon should work.

Good point! I did not realize that excel formulas could use different characters in different locales (!) what a nightmare!
e.James
+4  A: 

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.

KnomDeGuerre