Overcoming the 255 char. limit for formulaArray in Excel VBA

我的梦境 提交于 2019-12-12 19:16:16

问题


I need an array to be inserted into a specific cell and I keep running into the 1004 error. Here is the code:

Range("o37").FormulaArray = "=CONCATENATE(SUM(IF(('2016 Summary'!$T$4:$T$39<=" & mon & ")*" & _
    "('2016 Summary'!$D$4:$D$39>0)*('2016 Summary'!$T$4:$T$39+'2016 Summary'!$D$4:$D$39>" & mon & ")*" & _
    "('2016 Summary'!$S$4:$S$39=TRUE),(1),IF(('2016 Summary'!$T$4:$T$39<=" & mon & ")*('2016 Summary'!$S$4:$S$39=TRUE)*" & _
    "('2016 Summary'!$D$4:$D$39=0),(1),0)))&"" - Employees"")"

That array is supposed to be inserted into O37 with the "mon" variable based on the activecell column. The formula works when I manually put it in the sheet. I have tried splitting it with .replace and I get the same error. What can I do to make this work with formulaArray?


回答1:


Depending upon how long the value in the mon variable is, it seems that your array formula is only marginally over the limit at ~290-310 characters and a large portion of that is comprised of the external worksheet name (e.g. '2016 Summary'). Changing the worksheet name temporarily to a single character is sufficient to bring the formula down to the ~190-210 character range; more than adequate to stuff the formula into the cell's Range.FormulaArray property.

    Dim strWS As String, chrWS As String

    strWS = "2016 Summary"
    chrWS = Chr(167)    '<~~ any unque, legal, single character that can be temporarily used as a worksheet name

    With Worksheets(strWS)
        .Name = Chr(167)
    End With

    With Worksheets("worksheet_with_array_formula")
        .Range("o37").FormulaArray = "=CONCATENATE(SUM(IF((" & chrWS & "!$T$4:$T$39<=" & mon & ")*" & _
            "(" & chrWS & "!$D$4:$D$39>0)*(" & chrWS & "!$T$4:$T$39+" & chrWS & "!$D$4:$D$39>" & mon & ")*" & _
            "(" & chrWS & "!$S$4:$S$39=TRUE),(1),IF((" & chrWS & "!$T$4:$T$39<=" & mon & ")*(" & chrWS & "!$S$4:$S$39=TRUE)*" & _
            "(" & chrWS & "!$D$4:$D$39=0),(1),0)))&"" - Employees"")"
    End With

    With Worksheets(chrWS)
        .Name = strWS
    End With

Excel will change the worksheet name within the formula, adding wrapping ticks (e.g. '2016 Summary'!$T$4:$T$39) to compensate for the space in the new (old) worksheet name.

If you provided more detail on the value of mon and some sample data from the '2016 Summary' worksheet, it also possible that the formula could be improved. At first glance, it looks like an array formula may not be absolutely necessary at all.



来源:https://stackoverflow.com/questions/35025697/overcoming-the-255-char-limit-for-formulaarray-in-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!