excel - 具有动态范围的自动填充公式
问题描述
我在 G 列上有我要分离的数据组合。mid/find 的公式工作正常,但是当我尝试添加我在底部在线找到的自动填充代码时,它会出错。
Range("H2").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-1],FIND(""ASL"",RC[-1])+4,3)"
Range("I2").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-2],FIND(""DEPT"",RC[-2])+5,2)"
Range("J2").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-3],FIND(""ST"",RC[-3])+3,2)"
Range("K2").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-4],FIND(""REIN"",RC[-4])+5,5)"
Range("H2:K2").Select
Selection.AutoFill Destination:=Range("H2:K" & Range("A" & Rows.Count).End(xlUp))
解决方案
您可以通过将公式放入数组并将每个公式写入列范围来将公式写入每一列。你不需要使用AutoFill
. 此代码会将公式插入到列 H - K 从第 2 行到 A 列的最后一行(值)。请根据需要更改工作表。代码中提供了注释。
Sub InsertFormulasInColumnsWithArray()
'Set your worksheet variable, change the worksheet as needed
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
'Put all your formulas into an array. the `_` connects each section into one line of code, easier to read.
Dim formulaArr As Variant: formulaArr = Array("=MID(RC[-1],FIND(""ASL"",RC[-1])+4,3)", _
"=MID(RC[-2],FIND(""DEPT"",RC[-2])+5,2)", "=MID(RC[-4],FIND(""REIN"",RC[-4])+5,5)", _
"=MID(RC[-4],FIND(""REIN"",RC[-4])+5,5)")
x = 8 'assign the variable `x` to the first column `H = 8`
With ws 'use the With statement to ensure you are adding the formulas to the correct worksheet
For i = LBound(formulaArr) To UBound(formulaArr) 'loop through the 4 formulas in your array
'Starting at `row 2`, `column 8` (x = 8)`,
'resize the the range to the value of the last row in `Column A`
'you subtract `-1` because you start the range on `Row 2`
'Write the first formula to the range in `Column H`,
'in the second loop you will write the second formula in Column I, etc.
.Cells(2, x).Resize(.Cells(.Rows.Count, 1).End(xlUp).Row - 1).FormulaR1C1 = formulaArr(i)
x = x + 1 'increase x by 1 to select the next column
Next i 'Loop to the next formula in the array, until the last formula is done
End With
End Sub
推荐阅读
- hibernate - 根据列值使用不同的序列生成主键
- mysql - mysql中的累积和列 - 设置功能不起作用
- reactjs - this.setState 第二个参数带有一个 setTimeout
- html - 我的 Internet 浏览器每次都会自动打开和关闭 HTML 侧边栏。我怎样才能阻止它,发生了什么?
- gitlab-ci - Gitlab-ci:将一个仓库从 Gitlab 推送到 Gitlab Runner 主机?
- python - 如何使用 shell 命令按应用程序名称查找 PID
- python - 剪刀石头布游戏玩家2输入错误
- windows - 使用批处理脚本在文本文件中使用文件夹列表将只需要的文件夹复制到目标文件夹
- r - 用第二个数据帧中的相同行名替换第一个数据帧中的行
- salesforce - 如何在 Salesforce 中自定义 RemoteAccessAuthorizationPage?