如何编写一个VBA函数来总结一个无限的范围

我需要编写一个VBA函数,它将从我的范围中select所有值,然后将范围的总和显示在单元格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 

为什么在已经有一个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))) 

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

  • 使用WorksheetFunction ,错误将被视为VBA错误,可使用On Error语法进行捕获。
  • 通过Application ,他们返回一个包含在Variant中的Excel错误代码。 您可以使用IsError查看返回的variables是否为错误types变体。

更多细节在这里 。

如果你一定要重新发明轮子,下面是你如何显式计算总和:

 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 
 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.