首页 > 解决方案 > VBA - 更改范围内的公式

问题描述

所以我想知道如何更新一个范围内的公式(E7:BE7),在我的工作表中我有多个表,所以我不能用 lastRow 更新它。

对于 E7:BE7 范围内的每个单元格,我有以下公式:

在使用脚本向表中添加新条目后,我想更新公式,以便最后一行增加一。所以我会让该范围内的所有公式在新条目后变成这样:

这是我的脚本的一个片段,它添加了一个新条目,我想自动更新这些公式,但我还是 vba 的新手并且有点挣扎,任何帮助将不胜感激。

        With Target
            Dim cell As Range
            Dim calendar_header As Range
            
            Set calendar_header = Range("E7:BE7")
            
            ' this is the part that will insert a new row on my target and copy the information i need in the row
            .Offset(0).EntireRow.Insert Shift:=xlDown
            .Offset(-2).EntireRow.Copy
            .Offset(-1).EntireRow.PasteSpecial xlPasteFormats
            Application.CutCopyMode = False
            Cells(.Row - 1, "A").Value = Cells(.Row - 2, "A").Value
            Cells(.Row - 1, "B").Value = Cells(.Row - 2, "B").Value
            Cells(.Row - 2, "E").Copy
            Cells(.Row - 1, "E").PasteSpecial
            Application.CutCopyMode = False

            ' This is the loop that's supposed to make my updates on the formulas
            For Each cell In calendar_header
                
                 ' Im struggling with this part.
                
            Next cell
            
            
        End With

标签: excelvba

解决方案


您不需要循环来更新公式。假设你Target是最后一行,你可以这样做:calendar_header.Formula = "-SUM(E$8:E$" & Target.Row & ")". 这将更新您范围内的公式

注意:还要考虑如果Target有超过 1 个单元格会发生什么


推荐阅读