簡體   English   中英

如何在Excel-VBA中連續求和

[英]How to total values in a row in Excel-VBA

我有一個包含一些值的電子表格,我希望將這些值總計。 但是,值在不同的列(2A,2B,2C等)中

在Excel中使用VBA,如何計算行中單元格的總和? 我搜索過的所有解決方案都向我展示了如何計算列中的值。

嘗試下面的代碼(代碼內的注釋說明):

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

該循環遍歷任何預選的列范圍,並將行中的每個值加在一起。

    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  '

如果行中沒有錯誤值,則只需將行中的所有值相加即可-無需查找最后一列。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM