每第 n 行应用不同的公式

Applying a different formula every nth row

所以我有这个 sheet 我想每隔 7 行应用一个公式。但不能是同一个公式,还需要"offset"公式。

例如,对于第一个范围,公式为“=(C4+C5)-C3”;对于第二个范围,“=(C11+C12) - C10”;等等。

这是我目前拥有的:

    Sub ApplyFormula()

    ApplyCF Range("C6")
    ApplyCF Range("C13")
'and so on, every 7 rows
'is there any other way i can apply these ranges instead of typing them?
'with an offset formula or something like that.

End Sub

    Sub ApplyCF(rng As Range)


    rng.Formula = "=(C4+C5)-C3"
    'i'd like the macro to "offset" the formula,
    'so for the C13 Range it would be "=(C11+C12) - C10"

    End Sub

对于您的 ApplyCF 潜艇,您可以这样做:

Sub ApplyCF(rng As Range)
If rng.Count <> 1 Then Exit Sub ' in case your range is more than one cell

Dim prevCell As Range, twoPrevCell As Range, threePreCell As Range
Set prevCell = rng.Offset(-1, 0)
Set twoPrevCell = rng.Offset(-2, 0)
Set threeprevcell = rng.Offset(-3, 0)

rng.Formula = "=(" & twoPrevCell & "+" & prevCell & ")-" & threeprevcell
End Sub

它肯定可以进行调整,例如,您需要在公式栏中查看公式吗?我们可以在 VBA 中评估该数学,然后将答案放入。

根据您的评论,对每第 6 个单元格尝试此操作(这是整个宏,无需拆分它们):

Sub test()
' I assume you want to run this for every 6th cell in column C, starting with C1

Dim lastRow As Long
lastRow = Cells(Rows.Count, 3).End(xlUp).Row ' gets us our last row in column C with data

Dim cel As Range, rng As Range

For i = 6 To lastRow Step 6 'have to start at row 4, since any other row less than that messes up the formula
    Cells(i, 3).Select      ' because you can't have row 3-3
    Cells(i, 3).Formula = "=(" & Cells(i - 2, 3).Address & "+" & Cells(i - 1, 3).Address & ")-" & Cells(i - 3, 3).Address
Next i

End Sub

如果需要显示公式。编辑。下面的代码将起作用!您需要使用参数 "address" 来引用单元格。参数 false 或 true 在这里表示是否需要相对(设置为 false)或绝对(设置为 true)referernce

Sub ApplyCF(rng As Range)

         rng.Formula = "=(" & rng.Offset(-2, 0).Address(False, False) & _
         "+" & rng.Offset(-1, 0).Address(False, False) & ")-" & rng.Offset(-3, 0).Address(False, False)

    End Sub