# How do I sum values in a range in VBA?

You can use the VBA WorksheetFunction.Sum method to calculate the sum of values in a range. This method takes two parameters: the range of cells you would like to sum, and an optional criteria range. You can use this method to quickly sum a range of cells in your worksheet. You can also combine this method with loops to sum multiple ranges at once.


You can use the following basic syntax to calculate the sum of values in a range using VBA:

Sub SumValues()
    Range("D2") = WorksheetFunction.Sum(Range("B2:B11"))
End Sub

This particular example calculates the sum of values in the range B2:B11 and assigns the result to cell D2.

If you would instead like to display the sum of values in a message box, you can use the following syntax:

Sub SumValues()
    'Create variable to store sum of values
    Dim sum As Single
    
    'Calculate sum of values in range
    sum = WorksheetFunction.Sum(Range("B2:B11"))
    
    'Display the result
    MsgBox "Sum of Values in Range: " & sum
End Sub

The following examples shows how to use each of these methods in practice with the following dataset in Excel that contains information about various basketball players:

Example 1: Calculate Sum of Range Using VBA and Display Results in Cell

Suppose we would like to calculate the sum of values in the points column and output the results in a specific cell.

We can create the following macro to do so:

Sub SumValues()
    Range("D2") = WorksheetFunction.Sum(Range("B2:B11"))
End Sub

When we run this macro, we receive the following output:

Notice that cell D2 contains a value of 245.

This tells us that the sum of values in the points column is 245.

Example 2: Calculate Sum of Range Using VBA and Display Results in Message Box

Suppose we would instead like to calculate the sum of values in the points column and output the results in a message box.

Sub SumValues()
    'Create variable to store sum of values
    Dim sum As Single
    
    'Calculate sum of values in range
    sum = WorksheetFunction.Sum(Range("B2:B11"))
    
    'Display the result
    MsgBox "Sum of Values in Range: " & sum
End Sub

When we run this macro, we receive the following output:

VBA sum values in range

The message box tells us that the sum of values in the range B2:B11 is 245.

Note that in this example we calculated the sum of values in the range B2:B11.

However, if you’d like to instead calculate the sum of values in an entire column you could type B:B instead.

This will calculate the sum of values for every cell in column B.

x