excel - Excel VBA:对具有可变行数的数据集中的列求和的最佳方法是什么?
问题描述
我需要对数据集中的两列(B 和 C)求和。包含数据的行数将在 1 到 17 之间变化。我需要在最后一行数据下方添加两行总和(图 1 中的最终结果示例)。
我的代码在一个数据集上运行良好,但出现错误
运行时错误'6':溢出
对于不同的数据集。我究竟做错了什么?
'Units total
Windows("Final_Files.xlsb").Activate
Sheets("Revenue Summary").Select
lastrow = Worksheets("Revenue Summary").Cells(Rows.Count, 2).End(xlUp).Row
Dim a As Integer
a = 10000
For i = lastrow To 2 Step by - 1
a = a + Worksheets("Revenue Summary").Cells(i, 2).Value
Next
Worksheets("Revenue Summary").Cells(lastrow + 2, 2).Value = a
解决方案
以下代码总结了“B2”和“C2”下的所有行。使其适应您的需求。
' Keep a reference to the worksheet
Dim ws as Worksheet
Set ws = Worksheets("Revenue Summary")
' This is how many rows there are.
Dim rowCount as Long
rowCount = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row-1
' This is the summation operation over each column
Dim b as Double, c as Double
b = WorksheerFunction.Sum(ws.Range("B2").Resize(rowCount,1))
c = WorksheerFunction.Sum(ws.Range("C2").Resize(rowCount,1))
' This writes the sum two cells under the last row.
ws.Range("B2").Cells(rowCount+2,1).Value = b
ws.Range("C2").Cells(rowCount+2,1).Value = c
推荐阅读
- excel - 在 Excel 中使用别名“MAX”调用 DLL 函数
- javascript - 将音频缓冲区放入可由音频元素播放的 blob 的最佳方法是什么?
- rxjs - 如果用户多次重新打开他的应用程序,NativeScript 应用程序中可能存在内存泄漏
- excel - MailMerge:从 Excel 到 Word 为每条记录保存单个文档,同时保持到源的链接
- java - 文件未正确保存
- python - 将列添加到更高维度
- sql-server - 在 SQL Management Studio 中为没有所有者权限的特定用户隐藏所有数据库,但只有一个数据库
- sql - SQL - Max Case 什么时候不拉最大值?
- iis - 将 parameters.xml 或 setParams.xml 替换为 Azure DevOps Release Pipeline 变量
- c# - Unity 中的一个简单的开始按钮