[英]Excel VBA: How to create loop and save output for each value in range?
[英]How to increment the Range of a For Each loop - Excel VBA
我有一個循環,我試圖在其中遞增公式發布在哪些單元格中。我確認我的循環已經工作,我只是不太知道如何限制它以在每個增量而不是每個單元格中發布公式。
也許我不應該在這里使用 For Each 循環?
Option Explicit
Sub Insert_Formula_Sum()
Dim LastRow As Long, i As Long, c As Long
Dim rng As Range, rcell As Range
Dim LI As Worksheet
Set LI = Sheets("Lumber Inventory")
'Set lower range of dataset
LastRow = LI.Range("A" & Rows.Count).End(xlUp).Row
'Set range of For Each loop
Set rng = Range("D8:D" And LastRow)
i = 3
c = 3
For Each rcell In rng
rcell.Formula = "=SUM(D" & i & ":D" & c & ")"
i = i + 7
c = c + 7
rcell = rcell + 7
Next rcell
End Sub
我只是不太清楚 go 如何增加范圍。 你可以看到我的少年嘗試:
rcell = rcell + 7
但這當然會導致數據類型不匹配,因為它變暗為范圍而不是 integer。
您的公式似乎對 1 個單元格求和,如果不正確,您需要調整I
Start、Step、I-3、I-3 上的 +-。
Option Explicit
Sub Insert_Formula_Sum()
Dim LastRow As Long
Dim I As Long
Dim LI As Worksheet
Set LI = Sheets("Lumber Inventory")
With LI
' Find Last Row#
LastRow = .Range("A" & Rows.Count).End(xlUp).Row
For I = 8 To LastRow Step 7
.Range("D" & I).Formula = _
"=SUM(D" & I - 3 & ":D" & I - 3 & ")"
Next I
End With
End Sub
但是,如果您將公式行更改為:
... = "=SUM(D" & I - 6 & ":D" & I - 1 & ")"
那么output就是:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.