[英]How to store the sum of a range of cells in a variable?
我試圖將一系列單元格的總和存儲在一個變量中。
Sub obtainhours()
Dim Total As Integer
Worksheets("22012017").Activate
Total = WorksheetFunction.Sum(Range("D2,D50"))
End Sub
首先,您應該聲明Total
As Long
,因為它能夠存儲大於Integer
( >32767
) 的數值。
您應該避免使用Activate
因為它會減慢代碼的運行時間,而是通過實現With
語句使用完全限定的對象。
Sub obtainhours()
Dim Total As Long
With Worksheets("22012017")
' Option 1: get the Sum of cells "D2" and "D50" only
Total = WorksheetFunction.Sum(.Range("D2,D50"))
' Option 2: get the Sum of cells "D2 through cell "D50"
Total = WorksheetFunction.Sum(.Range("D2:D50"))
End With
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.