如何在Excel-VBA中连续计算总值

时间:2017-07-11 15:15:31

标签: excel-vba vba excel

我有一个带有一些值的电子表格,我想要总计这些值;但是,这些值位于不同的列(2A,2B,2C等)

在Excel中使用VBA,如何计算行中单元格的总和?我搜索过的所有解决方案都向我展示了如何计算列中的值。

3 个答案:

答案 0 :(得分:0)

尝试下面的代码(代码中的解释作为注释):

Option Explicit

Sub SumRow()

Dim LastCol As Long

With Worksheets("Sheet2") ' modify to your sheet's name
    LastCol = .Cells(2, .Columns.Count).End(xlToLeft).Column ' get last column with data in row 2

    ' put the SUM result in Cell A3
    .Cells(3, 1) = WorksheetFunction.Sum(.Cells(2, 1), .Cells(2, LastCol))
End With

End Sub

答案 1 :(得分:0)

此循环遍历任何预先选择的列范围,并将一行中的每个值加在一起。

    Dim columnCount AS integer
    Dim total AS long

    columnCount = 12345 'the amount of column you want to play with
    total = 0 'the total you are looking for

    For i= 1 to columnCount
      total = total + cells(2,i).value
    Next i  '

答案 2 :(得分:0)

如果行中没有错误值,则只需对行中的所有值求和 - 无需查找最后一列。

Debug.Print WorksheetFunction.Sum(Worksheets("Sheet2").Rows(2))

相关问题