excel - VBA - 更改范围内的公式
问题描述
所以我想知道如何更新一个范围内的公式(E7:BE7),在我的工作表中我有多个表,所以我不能用 lastRow 更新它。
对于 E7:BE7 范围内的每个单元格,我有以下公式:
- =总和(E8:E15)
- =总和(F8:F15)
- ...
- =总和(BE8:BE15)
在使用脚本向表中添加新条目后,我想更新公式,以便最后一行增加一。所以我会让该范围内的所有公式在新条目后变成这样:
- =总和(E8:E16)
- =总和(F8:F16)
- ...
- =总和(BE8:BE16)
这是我的脚本的一个片段,它添加了一个新条目,我想自动更新这些公式,但我还是 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
解决方案
您不需要循环来更新公式。假设你Target
是最后一行,你可以这样做:calendar_header.Formula = "-SUM(E$8:E$" & Target.Row & ")"
. 这将更新您范围内的公式
注意:还要考虑如果Target
有超过 1 个单元格会发生什么
推荐阅读
- php - 通过 Google API 发送电子邮件
- postgresql - Spring JPA/Hibernate Repository findAll 在 Kotlin 中默认执行 N+1 个请求而不是 JOIN
- css - 如何在 React 中更改 svg 图标的大小?
- javascript - 加载脚本时未定义解析
- xml - 解组嵌套在 XML 中的 HTML
- r - 如何使正态分布的变量取决于R中的条目和时间?
- html - 自定义 antd 树组件样式
- python - 如何加快从大文件中创建熊猫数据框的速度?
- json - 无法使用 PHP 和 JSON 从网站向 Arduino 请求数据
- r - RStudio Connect 中的包管理