Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SUM() in VBA

If I have a set of cells in a worksheet that I want to add up, I can use the formula:

=SUM(Sheet1!A1:A10)

To do this in a sub, I would use:

Sub example1()
    Dim r As Range, v As Variant

    Set r = Sheets("Sheet1").Range("A1:A10")
    v = Application.WorksheetFunction.Sum(r)
End Sub

If, however, I want to add up a single cell across many worksheets, I use the formula:

=SUM(Sheet1:Sheet38!B2)

In VBA this line fails miserably, as explained in Specify an Excel range across sheets in VBA:

Sub dural()
    v = Application.WorksheetFunction.Sum("Sheet1:Sheet3!B2")
End Sub

I have two workarounds. I can the the sum by programming a loop:

Sub example2()
    Dim i As Long
    Dim v As Variant

    v = 0
    For i = 1 To 38
        v = v + Sheets(i).Range("B2")
    Next i
End Sub

or by using Evaluate():

v = Evaluate("Sum(Sheet1:Sheet3!B2)")

Is it possible to use Application.WorksheetFunction.Sum() for this calculation, or should I stick the loop?

like image 567
Gary's Student Avatar asked May 27 '16 20:05

Gary's Student


2 Answers

I believe the issue with the worksheetfunction.sum is that it needs arguments to evaluate not string. WorksheetFunction.Sum("Sheet1!A1:A3") fails as well. However, this succeeds

Application.WorksheetFunction.Sum(Sheet1.Range("A1"), Sheet2.Range("A1"))

The Ranges could be whatever you like.

like image 96
mongoose36 Avatar answered Nov 25 '22 10:11

mongoose36


I was able to get it to work just by the line:

Cells(x,y) = WorksheetFunction.sum(range(a,b:a,d))
like image 24
L DeFramce Avatar answered Nov 25 '22 09:11

L DeFramce