如何编写VBA函数来求和无穷范围

时间:2014-11-19 20:52:08

标签: excel vba excel-vba sum range

我需要编写一个VBA函数,它将从我的范围中选择所有值,然后将范围的总和显示在单元格D7中。这就是我迄今为止所做的一切。它不能是工作表函数。

Sub Statistics()

'count number of cell in Range
Dim count As Long
Sheets("sheet1").Activate
Range("a1").Select
count = Sheet1.Range("A" & Rows.count).End(xlUp).Row

'output count of cells in Range
Range("D6").Select
ActiveCell.Value = count

'This is where I need to write the sum function and output it to D7



End Sub

2 个答案:

答案 0 :(得分:3)

为什么在有一个Sum函数的时候写一个Sum函数?

Range("D6").Value = count
Range("D7").Value = WorksheetFunction.Sum(Range("A1").Resize(count)))

请注意,您可以通过Application对象而不是WorksheetFunction对象调用相同的内置函数来获得相同的结果:

Range("D7").Value = Application.Sum(Range("A1").Resize(count)))

这是完全相同的Sum函数。唯一的区别是如何处理错误:

  • 使用WorksheetFunction,错误被视为VBA错误,可使用On Error语法进行捕获。
  • 使用Application,它们会返回包含在Variant中的Excel错误代码。您可以使用IsError查看返回的变量是否为错误类型变体。

More details here

如果你绝对必须重新发明轮子,这里你可以明确地计算总和:

Dim i As Long
Dim sumTotal As Double
Dim arr As Variant
arr = Range("A1").Resize(count)
For i = 1 To count
    sumTotal = sumTotal + arr(i, 1)
Next i
'sumTotal now contains the sum

答案 1 :(得分:2)

Sub Statistics()

'count number of cell in Range

Dim count As Long
count = Sheets("Sheet1").Range("A" & Rows.count).End(xlUp).Row

'output count of cells in Range
Sheets("Sheet1").Range("D6").Value = count

'Assumes you are looking to sum all values in column A.
'IF NOT change the two values of "A" below and the one above in Rows.Count
Sheets("Sheet1").Range("D7").Value = Application.Sum(Range("A1:A" & count))

End Sub 'This started as a sub so has to end as sub.