简体   繁体   中英

How to total values in a row in Excel-VBA

I have a spreadsheet with some values and I want to total these values; however, the values are in different columns (2A, 2B, 2C, etc.)

Using VBA in Excel, how do I calculate the sum of the cells in the row? All solutions I have searched for show me how to calculate values in a column.

Try the code below (explanations inside the code as comments):

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

This loop goes through any pre-selected column range and adds every value within a row together.

    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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM