【问题标题】:How to write a VBA function to sum an infinite range如何编写 VBA 函数来求和无限范围
【发布时间】:2014-11-19 20:52:07
【问题描述】:

我需要编写一个 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

【问题讨论】:

  • 您求和的范围是多少?在哪一栏?
  • 试试Application.Sum(Range("A:A"))

标签: vba excel sum range


【解决方案1】:

既然已经有 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,它们会返回包装在变体中的 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

【讨论】:

  • 他的一些其他语法是错误的,比如Sheet1.Range 应该是Sheets("Sheet1").Range,他使用End Function 而不是End Sub
  • 这可行,但它使用工作表函数。指定无法使用工作表函数。
  • 再次感谢您的反馈。
  • @Chrismas007: Sheet1.Range(...) 实际上是完全正确的语法。 Sheet1. 使用工作表的代号,而 Sheets("Sheet1") 使用工作表的 Name 属性。参见例如this answer了解详情。
  • @Winfred:当然,您指定不能使用“工作表函数”,但我不清楚这意味着什么。我以为你的意思是,不能在工作表的单元格中编写函数,并不是说你不能在 VBA 中使用 WorksheetFunction 对象。为什么会有这个限制?
【解决方案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.

【讨论】:

  • 感谢您的反馈。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-29
  • 2012-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多