为什么“替换”在此FormulaArray中不起作用?

时间:2019-02-08 13:02:59

标签: excel vba replace

我写了一个很长的公式,所以我不得不将它切成一部分并用.Replace再次使其成为一个公式。

公式的目的是对一个范围内具有多个条件的唯一值进行计数。公式的SUM部分是求和不同的条件。

恐怕我还是一个初学者,对Array的使用还没有很多经验。

但是,这不起作用,因为我的回答是“ #NAME?”在excel中,公式为:"=IF(SUM((WWW))=0,""-"",SUM((WWW)))",因此无法识别被替换的部分。

我在做什么错?

如果删除公式中的“ =”,并在excel中将其手动放置,该公式将起作用。所以这个公式是正确的。

Dim theFormulaPart1 As String
Dim theFormulaPart2 As String
Dim theFormulaPart3 As String
Dim theFormulaPart4 As String
Dim theFormulaPart5 As String

theFormulaPart1 = "=IF(SUM((WWW))=0,""-"",SUM((WWW)))"
theFormulaPart2 = "IF(FREQUENCY(IF((Scientific_Name=RC[-8])*(Total>0)*(Membership=""EAZA""),MATCH(Mnemonic,Mnemonic,0)),MATCH(Mnemonic,Mnemonic,0))>0,1))+XXX"
theFormulaPart3 = "(IF(FREQUENCY(IF((Scientific_Name=RC[-8])*(Total>0)*(Membership=""Temporary""),MATCH(Mnemonic,Mnemonic,0)),MATCH(Mnemonic,Mnemonic,0))>0,1))+YYY"
theFormulaPart4 = "(IF(FREQUENCY(IF((Scientific_Name=RC[-8])*(Total>0)*(Membership=""Associate""),MATCH(Mnemonic,Mnemonic,0)),MATCH(Mnemonic,Mnemonic,0))>0,1))+ZZZ"
theFormulaPart5 = "(IF(FREQUENCY(IF((Scientific_Name=RC[-8])*(Total>0)*(Membership=""N-EEP""),MATCH(Mnemonic,Mnemonic,0)),MATCH(Mnemonic,Mnemonic,0))>0,1)"    

 With ActiveSheet.Range("I42")
    .FormulaArray = theFormulaPart1
    .Replace "WWW", theFormulaPart2, xlPart
    .Replace "XXX", theFormulaPart3, xlPart
    .Replace "YYY", theFormulaPart4, xlPart
    .Replace "ZZZ", theFormulaPart5, xlPart
End With

设置似乎可以正常工作,因为它会显示“ 20”:

Dim theFormulaPart1 As String
Dim theFormulaPart2 As String
Dim theFormulaPart3 As String
Dim theFormulaPart4 As String
Dim theFormulaPart5 As String   

theFormulaPart1 = "=IF(SUM(WWW)=0,""-"",SUM((WWW)))"
theFormulaPart2 = "3+XXX"
theFormulaPart3 = "4+YYY"
theFormulaPart4 = "6+ZZZ"
theFormulaPart5 = "7"

With ActiveSheet.Range("I36")
    .FormulaArray = theFormulaPart1
    .Replace "WWW", theFormulaPart2, xlPart
    .Replace "XXX", theFormulaPart3, xlPart
    .Replace "YYY", theFormulaPart4, xlPart
    .Replace "ZZZ", theFormulaPart5, xlPart
End With

1 个答案:

答案 0 :(得分:0)

由于具有数组公式,因此需要将其视为此类,否则将删除功能。

例如:

如果我在{=SUM(B1:F1*B2:F2)}中有arrayformula Cells(1,1)并且想要扩展范围,我将不得不替换它,例如:

  • Cells(1, 1).FormulaArray = Replace(Cells(1, 1).Formula, "F", "G")

  • Cells(1, 1).FormulaArray = Replace(Cells(1, 1).FormulaArray, "F", "G")

但是如果我愿意这样做的话:

  • Cells(1, 1) = Replace(Cells(1, 1).FormulaArray, "F", "G")

它将使用单元格的值而不是公式,从而创建一个导致错误的正则公式,这与您在此行之后所做的完全一样:With ActiveSheet.Range("I36")