每第n行应用不同的公式

时间:2016-09-12 19:05:06

标签: excel vba row formula

所以我有这张表,我想每隔7行应用一个公式。但它不能是相同的公式,它也需要“抵消”公式。

例如,对于第一个范围,公式为“=(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

2 个答案:

答案 0 :(得分:0)

对于您的 TABLE Structure2016: STOCK_RIC YEAR WEEK_NUMBER JPM.N 2016 1 JPM.N 2016 2 JPM.N 2016 3 TABLE pre: STOCK_RIC WEEK_NUMBER SENT_POS_WEIGHTED JPM.N 5 0.1 JPM.N 3 0.9 JPM.N 1 0.1 JPM.N 10 0.1 Result should then look like STOCK_RIC WEEK_NUMBER SENT_POS_WEIGHTED JPM.N 1 0.1 JPM.N 2 NULL JPM.N 3 0.9 sub,您可以这样做:

ApplyCF

绝对可以调整,例如,你需要来查看公式栏中的公式吗?我们可以在VBA中评估该数学,然后将答案放入。

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

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

答案 1 :(得分:0)

如果需要显示公式。编辑。下面的代码将起作用!你需要使用parmateter“地址”来引用一个单元格。参数false或true在这里说如果需要亲戚(设置为假)或绝对(设置为真)参考

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