Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, 2013, 2016, 2019, and Excel in Microsoft 365. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Using SUM In a Macro.

Using SUM In a Macro

Written by Allen Wyatt (last updated May 23, 2020)
This tip applies to Excel 2007, 2010, 2013, 2016, 2019, and Excel in Microsoft 365


5

Bob has a need to use the SUM function in a macro in order to find the sum of all the values in a column. The problem is that the number of cells to be summed will vary; for one run of the macro it could be 100 cells, while on the next it could be 300 and on the third only 25.

First, it is easy to use most worksheet functions (such as SUM) from within a macro. All you need to do is to preface the function name with "Application.WorksheetFunction." or simply "WorksheetFunction." Thus, if you know that each run of the macro will require summing A1:A100, then A1:A300, and finally A1:A25, you could use a macro like this:

Public Sub Sum_Demo()
    Dim myRange
    Dim Results
    Dim Run As Long

    For Run = 1 To 3
        Select Case Run
        Case 1
            myRange = Worksheets("Sheet1").Range("A1", "A100")
        Case 2
            myRange = Worksheets("Sheet1").Range("A1", "A300")
        Case 3
            myRange = Worksheets("Sheet1").Range("A1", "A25")
        End Select
        Results = WorksheetFunction.Sum(myRange)
        Range("B" & Run) = Results
    Next Run
End Sub

This macro uses a For . . . Next loop to specify different ranges of cells to be summed. It then uses the SUM worksheet function to assign the sum to the Results variable, which is (finally) stuffed into a cell in column B. The results of the first run are put in B1, the second in B2, and the third in B3.

While this particular macro may not be that useful, it shows several helpful techniques, such as how to define a named range, how to use the SUM function, and how to stuff the sum into a cell. What the macro doesn't do is to show how to select a variable number of cells to be summed. To do this, it is best to rely upon the End method of the Range object. The following code line shows how you can stuff the sum of the range starting at A1 and extending to just before the first blank cell in the column:

myRange = ActiveSheet.Range("A1", Range("A1").End(xlDown))
Range("B1") = WorksheetFunction.Sum(myRange)

Note that a range (myRange) is defined as beginning with A1 and extending through whatever the End method returns. This is then summed and stuffed into B1.

Note:

If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (9180) applies to Microsoft Excel 2007, 2010, 2013, 2016, 2019, and Excel in Microsoft 365. You can find a version of this tip for the older menu interface of Excel here: Using SUM In a Macro.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Creating a New Document in VBA

When working with documents in a macro, it makes sense that you may need to create a document from time to time. Here's ...

Discover More

Using Message Boxes

If your macro needs to communicate with a user, one simple way to do it is to use a message box. Here's how to use this ...

Discover More

Excel 2013 Filters and Filtering (Table of Contents)

Excel provides two ways to filter your data so that only what you want to see is displayed. Discover how filtering works ...

Discover More

Comprehensive VBA Guide Visual Basic for Applications (VBA) is the language used for writing macros in all Office programs. This complete guide shows both professionals and novices how to master VBA in order to customize the entire Office suite for their needs. Check out Mastering VBA for Office 2010 today!

More ExcelTips (ribbon)

Executing a Macro Every 15 Minutes

Need to run a macro at a given interval? It's easy to do when you learn how to use the .OnTime method, described in this tip.

Discover More

Declaring Variables

Macros depend on the use of variables to do their work. This tip examines how variables are declared in a macro, using ...

Discover More

Highlighting Pattern Violations

A common part of working with text strings in a worksheet is normalizing those strings so that they follow whatever rules ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] (all 7 characters, in the sequence shown) in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is two less than 9?

2020-06-22 09:14:28

Peter Atherton

peter

I'm sure sure that this is what you want, but you could try the INDIRECT and ADDRESS functions The figure shows a couple of ways you can get the result. The sums shown are the sum of the column numbers in the range.

(see Figure 1 below)

Figure 1. Sum of Column Numbers


2020-06-21 17:15:36

peter

hi

i'm looking to sum elements of a non-printed matrix, within a certain predfined range.

For example, A is a 1024 x 312 matrix, and i'd like to sum all items f.e between rows 5 and 10, and between columns 10 and 20.

Is there a worksheet function for this in excel, or am i forced to write nested for loops?

thanks,
peter


2020-05-24 10:09:38

J. Woolley

@Willy Vanhaelen
I forgot about Application.Evaluate. Here's yet another way to express the macro:

Public Sub Sum_Demo()
[B1] = [Sum(A1:A100)]
[B2] = [Sum(A1:A300)]
[B3] = [Sum(A1:A25)]
End Sub


2020-05-23 11:58:54

J. Woolley

@Allen
Your macro works because myRange is Variant. But you really should use
Dim myRange As Range
...
Set myRange = ...

To reference a built-in Excel function F(...) in VBA, you can use either
V = Application.WorksheetFunction.F(...)
or V = WorksheetFunction.F(...)
or V = Application.F(...).
With the first two alternatives, execution will halt with a debug dialog if F(...) produces an error; in this case, 'On Error Resume Next' can be used to avoid the dialog and check for an error.
With the third alternative V = Application.F(...), any error will be recorded in V which should be tested using IsError(V).

BTW, you might be interested in my new web site:
https://sites.google.com/view/MyExcelToolbox/


2020-05-23 11:51:08

Willy Vanhaelen

This tip's macro has 15 lines of code. The following 3 lines macro does the same job !!!

Public Sub Sum_Demo()
[B1] = Application.Sum(Range("A1", "A100"))
[B2] = Application.Sum(Range("A1", "A300"))
[B3] = Application.Sum(Range("A1", "A25"))
End Sub


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.