[英]Setting up loop in Excel VBA to repeatedly sum up specific range
我有一個電子表格,我試圖用E列中各個但相似的點(每次迭代向下80個單元格)的特定數據重復填充K列。
因此,K2例如應顯示E25 + E35 + E42 + E56 + E63的總數。
然后,K3應該顯示E105 + E185 + E122 + E136 + E143的總數。
我已經編寫了執行第一步(並且可以工作)的宏,如下所示:
Sub disctoptest()
Dim source As Range
Dim destination As Range
Dim total As Long
Set destination = Range("K2")
Set source = Range("E25")
total = WorksheetFunction.Sum( _
source.Value + _
source.Offset(10, 0).Value + _
source.Offset(17, 0).Value + _
source.Offset(31, 0).Value + _
source.Offset(38, 0).Value)
destination.Select
destination.Value = total
Set source = Nothing
Set destination = Nothing
End Sub
然后,我插入了一個循環以對整個數據庫重復該操作,但是每當我運行添加的宏時,excel要么凍結,要么干脆拒絕工作。 這是我用來循環的代碼:
Sub disctop()
Dim source As Range
Dim destination As Range
Dim total As Long
Set destination = Range("K2")
Set source = Range("E25")
Do until destination.offset(0, -1) = ""
destination.Select
total = WorksheetFunction.Sum( _
source.Value + _
source.Offset(10, 0).Value + _
source.Offset(17, 0).Value + _
source.Offset(31, 0).Value + _
source.Offset(38, 0).Value)
destination.Value = total
source = source.Offset(80, 0)
destination = destination.Offset(1, 0)
Loop
Range("A1").Activate
Set source = Nothing
Set destination = Nothing
End Sub
如果使用其他類型的循環可能更容易,我需要在K列中精確地重復該操作680次。
任何提示和建議,將不勝感激!
您需要在范圍變量上使用SET
,以使它們更改為它們引用的單元格:
Set source = source.Offset(80, 0)
Set destination = destination.Offset(1, 0)
也
destination.offset(0, -1) = ""
永遠不會返回true,因為即使所有五個引用均為空,SUM函數也將返回0。
因此,您需要測試其他類似項: Total = 0
或者,您可以使用以下公式執行此操作:
=INDEX(E:E,25+((ROW(1:1)-1)*80)) +INDEX(E:E,35+((ROW(1:1)-1)*80)) +INDEX(E:E,42+((ROW(1:1)-1)*80)) + INDEX(E:E,56+((ROW(1:1)-1)*80)) +INDEX(E:E,63+((ROW(1:1)-1)*80))
放入K2並復制下來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.