【问题标题】:VBA code doesn't replace a string inside FormulaArrayVBA 代码不会替换 FormulaArray 中的字符串
【发布时间】:2016-05-30 23:00:35
【问题描述】:

我的 Excel 中的一列在 VBA 代码中具有 FormulaArray 格式的长函数。我的 VBA 代码将此长数组函数复制到此列中的单元格。

由于数组函数中的字符超过255个,我将公式字符串分解为两部分:

StrForm是整个公式的字符串,StrInner1是这个StrForm的第一个内部部分,StrInner2StrForm的第二个内部部分。

tmp1tmp2是两个临时参数,我在下一步用StrInner1StrInner2替换它们。

我没有收到任何错误,此代码成功地将StrForm 复制到单元格D2。但它不会将"tmp1";"tmp2" 替换为StrInner1StrInner2。任何人都可以看到这是什么问题,因为我无法...

Sub test()
    Dim StrForm, StrInner1, StrInner2 As String

    StrInner1 = "$A$2=Sheet2!B2;$A$3=Sheet2!B2;$A$4=Sheet2!B2;$A$5=Sheet2!B2;$A$6=Sheet2!B2;$A$7=Sheet2!B2;$A$8=Sheet2!B2"        

    StrInner2 = ";$A$9=Sheet2!B2;$A$10=Sheet2!B2;$A$11=Sheet2!B2;$A$12=Sheet2!B2;$A$13=Sheet2!B2;$A$14=Sheet2!B2;$A$15=Sheet2!B2" 

    StrForm = "=IF(IF(OR(""tmp1"";""tmp2"");Sheet2!A2;"""")=0;"""";IF(OR(""tmp1"";""tmp2"");Sheet2!A2;""""))"

    Sheets("Sheet1").Range("D2").FormulaLocal = StrForm   

    Sheets("Sheet1").Range("D2").FormulaArray = Sheets("Sheet1").Range("D2").Formula
    Sheets("Sheet1").Range("D2").Replace What:="""tmp1""", Replacement:=StrInner1, lookat:=xlPart
    Sheets("Sheet1").Range("D2").Replace What:=";""tmp2""", Replacement:=StrInner2, lookat:=xlPart

    ' StrInner1 and StrInner2 will be next to each other, so I also remove the semicolon between tmp1 and tmp2
End Sub

【问题讨论】:

  • 我们早已远离 16 位计算。 VBA 中的字符串应该接受超过 256 个字符 :)
  • @krishKM 当您使用常规 Formula 发送公式时,超过 255 个字符没有问题。但FormulaArray 有一些特别之处,它会出错。可能是因为数组函数是多维计算,只是为了限制这种多维计算。

标签: vba excel


【解决方案1】:

改变这两行:

StrInner1 = "$A$2=Sheet2!B2,$A$3=Sheet2!B2,$A$4=Sheet2!B2,$A$5=Sheet2!B2,$A$6=Sheet2!B2,$A$7=Sheet2!B2,$A$8=Sheet2!B2"

StrInner2 = "$A$9=Sheet2!B2,$A$10=Sheet2!B2,$A$11=Sheet2!B2,$A$12=Sheet2!B2,$A$13=Sheet2!B2,$A$14=Sheet2!B2,$A$15=Sheet2!B2"

您正在替换 FormulaArray 中的文本,它不是本地版本,因此逗号始终是字段分隔符。

也改变:

Sheets("Sheet1").Range("D2").Replace What:="""tmp2""", Replacement:=StrInner2, lookat:=xlPart

同样的问题 - 您正在尝试替换 ;,但它不存在。避免它的最佳方法是将其从搜索模式和StrInner2 中删除,只需替换占位符即可。

有趣的是,当您替换FormulaArray 中的文本并且结果不是有效公式时,没有错误消息,但FormulaArray 保持不变

【讨论】:

  • 非常感谢 :) 我很惊讶为什么微软为不同的语言开发了不同的 Excel。它应该是通用逗号或分号。
猜你喜欢
  • 2018-03-21
  • 1970-01-01
  • 2023-03-11
  • 2011-08-27
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-26
相关资源
最近更新 更多