You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA中含双引号的公式字符串循环写入问题求助

解决VBA中写入含双引号的公式字符串问题

你遇到的核心问题是VBA字符串的双引号转义规则——在VBA里,如果你想在一个字符串常量中包含双引号,必须用两个连续的双引号来表示单个双引号,不然VBA会把单个双引号当成字符串的结束标记,直接抛出语法错误。

修正后的代码

直接修改你原来的代码,把公式里的双引号替换成双份即可:

Dim LastRow As Long
Dim r As Long, i As Long, StartRow As Long ' 建议显式声明所有变量
r = 14
StartRow = 10
LastRow = Range("B" & StartRow).End(xlDown).Row
For i = StartRow To LastRow
    Range("B" & r).Value = "=BCurveFwd(B" & i & ";""startdate,maturity,par.mid"";B22;C22;B23;C23;""cols=3;rows=1"")"
    r = r + 1
Next i

关键修改点

我只改动了两处:

  • 把原公式里的 "startdate,maturity,par.mid" 改成了 ""startdate,maturity,par.mid""
  • 把原公式里的 "cols=3;rows=1" 改成了 ""cols=3;rows=1""

这样循环执行后,B14单元格会生成你预期的公式:=BCurveFwd(B10,"startdate,maturity,par.mid",B22,C22,B23,C23,"cols=3;rows=1"),后续单元格也会自动对应索引值。

可选优化方案(适合双引号较多的场景)

如果你的公式里有大量双引号,写一堆连续的""容易看花眼,也可以用Chr(34)来代替双引号(Chr(34)是ASCII码对应的双引号字符),代码可读性会更好:

Dim LastRow As Long
Dim r As Long, i As Long, StartRow As Long
Dim quote As String
quote = Chr(34) ' 定义双引号变量

r = 14
StartRow = 10
LastRow = Range("B" & StartRow).End(xlDown).Row
For i = StartRow To LastRow
    Range("B" & r).Value = "=BCurveFwd(B" & i & ";" & quote & "startdate,maturity,par.mid" & quote & ";B22;C22;B23;C23;" & quote & "cols=3;rows=1" & quote & ")"
    r = r + 1
Next i

内容的提问来源于stack exchange,提问作者Andreas Hild

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:43:18