简体   繁体   中英

Problem with using VBA to insert formula in Excel sheet

I recently ran into an issue when using VBA to insert a formula into an Excel sheet. Below the relevant piece of code;

Calculatie_cell.Offset(n, 5) = "=SOM(H" & (n + 3 - 1) & ":H" & (n + 3 - Onderdelen_aantal) & ")"
Calculatie_cell.Offset(n, 8) = "=SOM(K" & (n + 3 - 1) & ":K" & (n + 3 - Onderdelen_aantal) & ")"

For the first iteration where it triggers, the expected output is;

=SOM(H4:H7)
=SOM(K4:K7)

The output I recieve is;

=@SOM(H4:H7)
=@SOM(K4:K7)

This output yields a #NAME? error. Pressing F2, enter on the cell (like inputting it by hand), gives an error stating that this formula is not supported by older versions of Excel with the option to correct it to the expected output. If I accept this it works.

I can't find why Excel thinks it needs the @ and the code below does not filter the @ from the formule (but it does filter it out of random text with an @)

Calculatie_cell.Offset(n, 5) = Replace(Calculatie_cell.Offset(n, 5), "@", "")
Calculatie_cell.Offset(n, 8) = Replace(Calculatie_cell.Offset(n, 8), "@", "")

Does anyone have a suggestion how I can get rid of the @, or another way to make the formula work? Thanks in advance!

Relevant note; I use Excel 2016 in Dutch, meaning "SOM" is the correct way to spell "SUM"

User @Solar Mike was right.

Even though Excel wants the code to be "SOM" (Dutch spelling), in VBA it needs to ben SUM (English spelling). It auto-translates and works right of the bat. Thank you for your help!

If you post it as an answer, I will accept it as such.

First of all, regardless of your Office installation language, VBA asks for engligh input.
Therefore, replace SOM by SUM in your code.
It should appear as SOM in the workbook, but not in the code.

Second of all, using oCell = "=SOME_FORMULA" usually does not yield the intended result.
Instead, one should use oCell.Formula2 = "=SOME_FORMULA" .
This is why an @ shows up in the formula.

See this article for information.


Finally, your code should be

Calculatie_cell.Offset(n, 5).Formula2 = "=SUM(H" & (n + 3 - 1) & ":H" & (n + 3 - Onderdelen_aantal) & ")"
Calculatie_cell.Offset(n, 8).Formula2 = "=SUM(K" & (n + 3 - 1) & ":K" & (n + 3 - Onderdelen_aantal) & ")"

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