首页 > 解决方案 > 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 

正确的最终结果
图 1 - 正确的最终结果

标签: excelvba

解决方案


以下代码总结了“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

推荐阅读