How To Add Formula In Excel Vba

To add a formula in Excel VBA, you can use the Formula property of a Range object. The Formula property allows you to specify a formula as a string, just like you would do in Excel.

Here’s an example:

Sub AddFormula()
    Dim rng As Range
    
    ' Set the range where you want to add the formula
    Set rng = Range("A1")
    
    ' Add a formula to the range
    rng.Formula = "=SUM(B1:B5)"
End Sub

In this example, we set the rng variable to Range("A1") to specify that we want to add the formula to cell A1. Then, we assign the formula =SUM(B1:B5) to the Formula property of the range.

You can use any valid Excel formula in the Formula property. You can also reference other cells by using their cell references, such as B1 in the example above.

If you want to add the formula to multiple cells at once, you can use the Range object with multiple cells. Here’s an example:

Sub AddFormulaToRange()
    Dim rng As Range
    
    ' Set the range where you want to add the formula
    Set rng = Range("A1:A5")
    
    ' Add a formula to the range
    rng.Formula = "=SUM(B1:B5)"
End Sub

In this example, the formula =SUM(B1:B5) will be added to cells A1 to A5.

Related Post

Leave a comment