excel - 在公式 VBA 中更改字符串
问题描述
我有一个工作簿,我不时向其中添加行。当我添加行时,我复制了一行完整的公式,这些公式引用了工作簿中的其他工作表(即 =Datasheet!A12)。粘贴公式时,不引用另一个工作表的公式会更新到新行,但引用其他工作表的公式不会(即 =Datasheet!A12 应该变为 =Datasheet!A13)。所以我的解决方案是遍历新行并找到带有“!”的公式 并更改行号。顺便说一句,我愿意接受更好的解决方案。目前,我的代码没有更新任何内容。由于某种原因,“如果”语句总是错误的。这是我的代码:
Dim i As Integer
Dim r As Range
Dim cell As Range
Set r = Rows(row_to_insert).Cells
'loop through position sheets and insert blank rows
For i = 1 To 4
Sheets(i).Select
Rows(row_to_insert).EntireRow.Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Next i
'loop through position sheets and copy/paste formulas into new rows
For i = 1 To 4
Sheets(i).Select
Rows(blank_row_to_use + 1).EntireRow.Select
Selection.Copy
Rows(row_to_insert).EntireRow.Select
ActiveSheet.Paste
r = Rows(row_to_insert)
For Each cell In r ' loop thorugh passed range relevant cells (i.e. those containing formulas)
If InStr(cell.Formula, "!") > 0 Then cell = Replace(cell, (row_to_insert - 1), (row_to_insert)) ' if current cell has an explicit sheet reference, then convert its formula to the passed reference type
Next
Next i
row_to_insert 是一个提示,让我选择要添加的行,而 blank_row_to_use 是包含我复制的公式的行。
更新 我发现我的范围是为循环设置的,以查看单元格值而不是单元格公式。因此,对于任何正在寻找类似问题的解决方案的人来说,这就是更新后的代码的样子。虽然它很慢,所以如果有人对我的公式没有更新有更优雅的解决方案,请告诉我。
Dim i As Integer
'loop through position sheets and insert blank rows
For i = 1 To 4
Sheets(i).Select
Rows(row_to_insert).EntireRow.Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Next i
'loop through position sheets and copy/paste formulas into new rows
For i = 1 To 4
Sheets(i).Select
Rows(blank_row_to_use + 1).EntireRow.Select
Selection.Copy
Rows(row_to_insert).EntireRow.Select
ActiveSheet.Paste
Dim r As Range
Dim cell As Range
Set r = Rows(row_to_insert).Cells.SpecialCells(xlCellTypeFormulas)
For Each cell In r ' loop thorugh passed range relevant cells (i.e. those containing formulas)
If InStr(cell.Formula, "!") > 0 Then cell = Replace(cell.Formula, (row_to_insert - 1), (row_to_insert)) ' if current cell has an explicit sheet reference, then convert its formula to the passed reference type
Next
Next i
解决方案
推荐阅读
- regex - 如何在 Linux 中仅用字母之间的下划线替换空格,忽略数字
- r - 选择具有每年数据的变量的所有值
- javascript - How to get the array value from axios response
- python - SQLAlchemy - 在整个数据库模型列中搜索模式
- asp.net-web-api - CORS 在 IIS Express 中运行良好,但在 IIS 中失败
- postman - 我如何在邮递员中获取 Amazon Cognito 令牌而无需手动步骤
- java - 如何通过 REST API 关联两个实体
- c++ - 为什么在接受输入后循环退出时不会这样做
- reactjs - React-Redux 更新和重定向逻辑
- c++ - 在 GCC 上无法编译 std::tuple 与多个空成员的比较