VBA 中的 SUM 函数 - 一行中不同列的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15182561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:04:16  来源:igfitidea点击:

SUM Function in VBA - sum of different columns in one row

excelvba

提问by Jeannette Liu

Can I use the SUM function to sum two or more columns in the same row?

我可以使用 SUM 函数对同一行中的两列或更多列求和吗?

Example:  
Column  : A B C D E  
Total   : 1 2 3 4 5
TotColAC: 4 6 (TotColBD)

Is it possible to use the SUM function or is there another way?

是否可以使用 SUM 函数或有其他方法?

Thank you!

谢谢!

回答by

Using VBA. It will add cells from A1 to E1. You can modify as per your requirement.

使用 VBA。它将添加从 A1 到 E1 的单元格。您可以根据您的要求进行修改。

Sub Add()
    Dim totalAtoE As Double
    totalAtoC = WorksheetFunction.Sum(Range("A1:E1"))
End Sub

only A1 and C1

只有 A1 和 C1

Sub AddAandC()
    Dim totalAandC As Double
    totalAandC = WorksheetFunction.Sum(Range("A1"), Range("C1"))
End Sub

as per your comment

根据你的评论

Sub Add()

Dim lastRow As Long, i As Integer, totalAtoC As Double, FinalSum As Double
lastRow = Range("A5000").End(xlUp).Row

For i = 1 To lastRow
    totalAtoC = totalAtoC + WorksheetFunction.Sum(Range("A" & i & ":C" & i))
Next
FinalSum = totalAtoC

End Sub