Write formulas into cells with VBA

A macro can work out a result and enter it as a fixed number. Often a real formula is the better choice: it keeps calculating when a value changes later, and anyone can see in the cell how the result comes about. Here you learn how to write formulas with VBA.

In short: Range("B7").Formula = "=SUM(B2:B6)" writes a formula, exactly as you would type it into the cell. VBA uses English function names and commas here, whatever language Excel runs in.

What you need to know: finding the last row and worksheet functions in VBA.

Try it right now

Add a total row with a real formula below the sales figures. Check makes sure the cell holds a formula and tests with more branches.

Task The macro AddTotal writes the word "Total" in column A below the last branch, and next to it in column B a formula that adds up all sales from row 2. It must be a real formula that updates when someone corrects a figure later.

ABCD
1BranchSales
2Manchester48,200
3London51,750
4Chicago39,900
5Boston62,300
6Glasgow27,450

Formula, FormulaR1C1, FormulaLocal

The same formula can be written three ways. In B7, all three lines give the same total of B2 to B6:

Range("B7").Formula = "=SUM(B2:B6)"
Range("B7").FormulaR1C1 = "=SUM(R[-5]C:R[-1]C)"
Range("B7").FormulaLocal = "=SUM(B2:B6)"   ' in English Excel; a German Excel expects =SUMME(B2:B6)
PropertyHow it is writtenUse it when
FormulaEnglish function names, commas between arguments, a dot as decimal point, A1 references.Always, by default. It works in every Excel, whatever the language.
FormulaR1C1English names, references as row and column relative to the cell: R[-1]C is one row up, same column.The same formula goes into many rows; it then looks identical everywhere.
FormulaLocalThe way you type it in your own Excel. In English Excel that matches Formula; in a German Excel it would be SUMME with semicolons.Rarely. It ties the macro to one language version.

To VBA, the formula is just text in quotation marks. You insert the variable parts with &: "=SUM(B2:B" & lastRow & ")" becomes =SUM(B2:B6) when lastRow = 6. As soon as the formula is in the cell, Excel calculates it.

Value or formula?

' fixed number: never changes again
Range("B7").Value = WorksheetFunction.Sum(Range("B2:B6"))

' formula: recalculates when B2 to B6 change
Range("B7").Formula = "=SUM(B2:B6)"

A fixed number is right when the result is a snapshot, in an archive for example. A formula is right when the table stays in use and people correct figures. For a report others will open and want to follow, the formula is usually the better choice.

One formula for a whole range

Give Formula to a range of several cells and Excel writes the formula into each of them, adjusting the relative references just as when you fill a formula down. So you write the formula for the first row, and no loop is needed.

Range("D2:D" & lastRow).Formula = "=B2*C2"     ' D3 gets =B3*C3 and so on

Task Column D should hold a formula quantity times unit price in every row (so =B2*C2 in D2). The macro LineTotals writes the formula into the whole range from D2 to the last row in one step, without a loop.

ABCD
1ItemQtyUnit priceTotal
2Lever arch file402.49
3Copy paper254.95
4Ballpoint pen1200.89
5Sticky notes601.75
6Hole punch812.90

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Quotation marks inside formulas

When the formula contains text, as IF often does, there is a snag: the VBA string ends at the next quotation mark. The fix is the same as for any VBA string: write quotation marks inside the text twice. "" in the code becomes " in the cell.

Range("D2").Formula = "=IF(C2>5000,""check"",""ok"")"
' in the cell: =IF(C2>5000,"check","ok")

Task Receipts over 5000 need the manager's approval. The macro ApprovalFormulas writes an IF formula into column D of each row: if the amount in C is greater than 5000, it shows "check", otherwise "ok".

ABCD
1ReceiptDepartmentAmountApproval
2B-301Purchasing1,250.00
3B-302IT7,400.00
4B-303Marketing980.00
5B-304IT5,000.00
6B-305Sales12,800.00

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

R1C1 in brief

R1C1MeaningSeen from D5
RC[-2]same row, two columns leftB5
R[-1]Cone row up, same columnD4
R2C4row 2, column 4, fixed (like $D$2)D2
R2Crow 2 fixed, same columnD2

The advantage: =RC[-2]*RC[-1] reads exactly the same in every row, while the A1 formula has different addresses in each row. That makes R1C1 handy in loops.

In real Excel

The macro recorder records typed formulas as ActiveCell.FormulaR1C1 = "…". If that puzzles you: it is the same formula, just in R1C1 notation.

Excel with dynamic arrays (Microsoft 365, Excel 2021 and later) also has Formula2. According to Microsoft it supersedes Formula there, while Formula stays for backward compatibility. The difference affects formulas that pass a range to a function expecting a single value, and formulas meant to spill. For formulas like =SUM(B2:B6) or =B2*C2, Microsoft notes there is often no difference. If you share files with older versions, stick with Formula. The exercises here only have Formula.

Many users run Excel in another language. With Formula your macro does not care: a colleague with German Excel sees =SUMME(B2:B6) in the formula bar for the same cell.

Common mistakes

Quotation marks not doubled

"=IF(C2>5000,"check","ok")" ends the VBA string after =IF(C2>5000,, and the rest makes no sense to VBA. Before the macro even starts you get "Compile error: Expected: end of statement".

Variable inside the text instead of joined on

"=SUM(B2:BlastRow)" puts the word lastRow into the formula, and Excel cannot do anything with "BlastRow". In the exercise, the cell then shows #NAME?. The variable belongs outside the quotation marks: "=SUM(B2:B" & lastRow & ")".

Result instead of formula

If you calculate with WorksheetFunction.Sum and enter the result, you have the right number but no formula. Where the task asks for a formula, the exercise reports: "B7 should contain a formula (Range("B7").Formula = "=…"), not just its result."

Semicolons or decimal commas

Formula expects the English notation: commas between arguments and a dot as decimal point, as in =ROUND(B2*1.2,2). Copying a formula from a colleague's German Excel with semicolons will not work with Formula.

FAQ

Does Range("B7").Value = "=SUM(B2:B6)" work too?

Yes, text that starts with = becomes a formula through Value as well. With Formula, though, the code makes clear what you mean.

How do I read a formula?

Range("B7").Formula returns it as text. Whether there is a formula at all is answered by Range("B7").HasFormula.

How do I turn formulas into fixed values?

With Range("D2:D20").Value = Range("D2:D20").Value, as in the copy and paste lesson: Value reads the results and writes them back as numbers.

How do I write a fixed reference like $G$1?

Exactly like that, inside the text: "=C2*$G$1". When written to a range, the fixed part stays the same in every row. In R1C1 the same reference is R1C7.

Do numbers in formulas need a dot?

In Formula, yes, just like in VBA itself: "=B2*1.2". See also Operators.

Learn this next: With and faster macros

With saves you repeating the same object over and over, and ScreenUpdating makes long macros noticeably faster.

Learn With

Write to us

Choose language

Select your preferred language