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?
evaluate
? – findwindowSet r = Sheets("Sheet1").Range("Sheet1:Sheet3!B2")
and then doSum
onr
? Or similar... whatever you need to do to create a range from the sheets. You're probably better off using one of your other approaches though. – gmileyEvaluate()
and it works fine....but if I have to calculate based on a dynamic range (same on all sheets), there is an extra step making the string I must supply toEvaluate()
– Gary's Studentv = Evaluate("Sum(START:FINISH!B2)")
– Scott Cranerrng
it would bev = Evaluate("Sum(START:FINISH!" & rng.Address(1,1) & ")")
– Scott Craner