Using SUM() in VBA

寵の児 提交于 2019-12-01 03:11:06

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.

You need to use the loop to perform the calculation across all of the sheets, it's the most efficient way by the looks of things. As mentioned above you can type each range separately instead.

Might be worth converting the range your adding up to a double (or single, integer, etc) because sometimes VBA reads numbers as text.

v = v + Cdbl(Sheets(i).Range("B2"))

The reason why you're having issues with Application.WorksheetFunction.Sum("Sheet1:Sheet3!B2") is because if you type that formula into Excel, the range 'Sheet1:Sheet3!B2' won't be recognised by excel.

To use a Application.WorksheetFunction it has to work in excel outside of VBA.

Hope that helps.

 Sub SumWorksheets()
    Dim ws As Worksheet
    Dim v As Variant
    For Each ws In ThisWorkbook.Worksheets
'    If ws.Name <> ThisWorkbook.ActiveSheet.Name Then ' (Sum other sheets only)
    If ws.Name <> "" Then
    Application.DisplayAlerts = False
    v = v + ws.Range("B2")
    Application.DisplayAlerts = True
    End If
    Next ws
    MsgBox v
    End Sub
L DeFramce

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

Cells(x,y) = WorksheetFunction.sum(range(a,b:a,d))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!