Thursday, July 23, 2020

How to set FormulaArray property to a formula with more than 255 characters

'https://docs.microsoft.com/en-us/office/vba/api/excel.range.formulaarray
'says "The FormulaArray property also has a character limit of 255."
'This is the workaround.
Sub SetTooLongArrayFormula(ByVal rn As Range, ByVal sFormula As String)
    Dim sFormat As String
    sFormat = rn.Cells(1, 1).NumberFormat
    rn.FormulaArray = ""
    rn.Cells(1, 1).NumberFormat = "@"
    rn.Value = sFormula
    rn.Cells(1, 1).NumberFormat = sFormat
    rn.Select
    DoEvents
    SendKeys "{F2}", True
    DoEvents
    SendKeys "+^{ENTER}", True
    
End Sub

Sub Test()
    'Do not run this macro from VBE Editor
    'Run this macro from the Macros ribbon on the Developer tab with the Excel worksheet in front.
    Dim sFormula As String
    sFormula = "=""1"""
    For i = 1 To 250
        sFormula = sFormula & "&""1"""
    Next
    SetTooLongArrayFormula Range("A1:A2"), sFormula
End Sub

No comments: