我已经使用更简单的公式尝试并测试了该方法,并且效果很好,但是当我使用新的更长的公式进行尝试时,它会将FormulaPart1
输入到range("J2")
中,但不能代替带有FormulaPart2
和FormulaPart3
的文本。该代码也没有给出任何错误。
基本上,该公式计算可用性百分比
((Available Hours - Engineering Downtime)/ Available Hours) * 100
请在下面查看我的代码。
Sub ArrayFormCalc()
Dim FormulaPart1 As String
Dim FormulaPart2 As String
Dim FormulaPart3 As String
Dim S1 As Worksheet
Set S1 = Sheets("Sheet1")
FormulaPart1 = "=IFERROR(((INDEX(INDIRECT(RC5&""_""&TEXT(R5C,""mmm"")),MATCH(RC6,INDIRECT(RC5&""_""&TEXT(R5C,""mmm"")&""_Shift""),0)" & _
",MATCH(R5C,INDIRECT(RC5&""_""&TEXT(R5C,""mmm"")&""_Date""),0))))-xxxxx,"""")"
FormulaPart2 = "SUMIFS(DT_Cur_Day_Hrs,DT_Equip,RC7,DT_Site,RC5,DT_Strt_Date,R5C,DT_Shift,RC6,DT_Cat,""Engineering Downtime"")" & _
"+SUMIFS(DT_Nxt_Day_Hrs,DT_Equip,RC7,DT_Site,RC5,DT_End_Date,R5C,DT_Shift,RC6,DT_Cat,""Engineering Downtime""))/yyyy"
FormulaPart3 = "(INDEX(INDIRECT(RC5&""_""&TEXT(R5C,""mmm"")),MATCH(RC6,INDIRECT(RC5&""_""&TEXT(R5C,""mmm"")&""_Shift""),0)," & _
"MATCH(R5C,INDIRECT(RC5&""_""&TEXT(R5C,""mmm"")&""_Date""),0))*100)"
Application.ReferenceStyle = xlR1C1
With S1.Range("J2")
.FormulaArray = FormulaPart1
.Replace "xxxxx", FormulaPart2, xlPart
.Replace "yyyy", FormulaPart3, xlPart
End With
Application.ReferenceStyle = xlA1
End Sub
答案 0 :(得分:1)
我无法确定确切的问题,但是可能是您在尝试替换事物之前将无效的公式写入数组。 我建议在字符串上预先使用替换公式,并且仅将最终结果粘贴到FormulaArray中。 https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/replace-function
答案 1 :(得分:1)
除非您的应用程序设置为使用R1C1引用,否则您将尝试将R1C1引用放入现有的A1样式公式中,该公式将不起作用。将应用程序更改为R1C1样式,添加公式然后放回去,或者更改两个替换部分以使用A1样式引用。
答案 2 :(得分:1)
似乎该问题确实存在于将其拆分以替换该公式时。
下面的代码包含公式的正确拆分。
Sub ArrayFormCalc()
Dim FormulaPart1 As String
Dim FormulaPart2 As String
Dim FormulaPart3 As String
Dim S1 As Worksheet
Application.ReferenceStyle = xlR1C1
Set S1 = Sheets("Sheet1")
FormulaPart1 = "=IFERROR(INDEX(INDIRECT(RC5&""_""&TEXT(R5C,""mmm"")),MATCH(RC6,INDIRECT(RC5&""_""&TEXT(R5C,""mmm"")&""_Shift""),0),MATCH(R5C,INDIRECT(RC5&""_""&TEXT(R5C,""mmm"")&""_Date""),0))-xxxxx*100,"""")"
FormulaPart2 = "(SUMIFS(DT_Cur_Day_Hrs,DT_Equip,RC7,DT_Site,RC5,DT_Strt_Date,R5C,DT_Shift,RC6,DT_Cat,""Engineering Downtime"")" & _
"+SUMIFS(DT_Nxt_Day_Hrs,DT_Equip,RC7,DT_Site,RC5,DT_End_Date,R5C,DT_Shift,RC6,DT_Cat,""Engineering Downtime""))/yyyy"
FormulaPart3 = "(INDEX(INDIRECT(RC5&""_""&TEXT(R5C,""mmm"")),MATCH(RC6,INDIRECT(RC5&""_""&TEXT(R5C,""mmm"")&""_Shift""),0),MATCH(R5C,INDIRECT(RC5&""_""&TEXT(R5C,""mmm"")&""_Date""),0)))"
With S1.Range("J2")
.FormulaArray = FormulaPart1
.Application.ReferenceStyle = xlR1C1
.Replace "xxxxx", FormulaPart2, xlPart
.Replace "yyyy", FormulaPart3, xlPart
.Application.ReferenceStyle = xlA1
End With
End Sub