[英]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.