如何使用VBA将某些文本插入到现有公式中?

时间:2019-03-28 09:34:07

标签: excel vba

我正在尝试将现有公式的文本替换为其他文本,但是该代码仅适用于从x到y的更改,而不是从x到z的更改,因为它显示了运行时错误1004。

有人知道为什么吗?

Sub MySub()
Dim x As String
Dim y As String
Dim z As String
Dim i As Integer

x = "$S:$S"
y = "$R:$R"
z = "$R:$R;"" <= ""&J$2;[activated201902.xlsx]riskmodel_new!$R:$R;"" > ""&I$2)"

For i = 1 To 10
Cells(i, "E").FormulaLocal = Replace(Cells(i, "E").FormulaLocal, x, y)
Cells(i, "J").FormulaLocal = Replace(Cells(i, "J").FormulaLocal, x, z)
Next i

End Sub

1 个答案:

答案 0 :(得分:0)

在VBA中的公式字符串中,您必须将双引号加倍,因此您在正确的路径上:

Dim x As String
Dim y As String
Dim z As String
Dim i As Integer

x = "$S:$S"
y = "$R:$R"
z = "$R:$R;"""" <= """"&J$2;[activated201902.xlsx]riskmodel_new!$R:$R;"""" > """"&I$2)"

For i = 1 To 10
Cells(i, "E").FormulaLocal = Replace(Cells(i, "E").FormulaLocal, x, y)
Cells(i, "J").FormulaLocal = Replace(Cells(i, "J").FormulaLocal, x, z)
Next i

End Sub