BACKGROUND: I got a cool Array Formula and it works perfect in Excel. Now I\'m trying to do the same formula, but with VBA. So I typed the Array Formula in
This is a little time consuming due to forced recalculation of a moved object but it seems to work well.
Problem: external workbook references are pushing array formula over the character limit.
Solution: a) move the external worksheet to the local workbook b) complete the array formula insertion c) move the local worksheet back to the external workbook and let Excel figure it out.
Sub arrayFormulaTooBig()
Dim ha2ndx As Long, wbha As Workbook, wbf As Workbook
Dim sel As Range
Set sel = Selection
Set wbha = Workbooks("HOGARES ALBACETE.xlsx")
Set wbf = sel.parent.parent
'Application.Calculation = xlCalculationmanual
'Application.ScreenUpdating = False
'move the external worksheet to local and reduce worksheet name to minimum characters
With wbha
If .Worksheets.Count = 1 Then
.Worksheets.Add after:=.Worksheets(.Worksheets.Count)
.Worksheets(.Worksheets.Count).Name = "to be removed"
End If
With .Worksheets("21076")
ha2ndx = .Index
.Move after:=wbf.Worksheets(wbf.Worksheets.Count)
End With
End With
'minimize worksheet name
wbf.Worksheets("21076").Name = ChrW(215)
'from 282 characters
'Selection.FormulaArray = _
"=INDEX('[HOGARES ALBACETE.xlsx]21076'!C1,MATCH(MAX(IF(RIGHT('[HOGARES ALBACETE.xlsx]21076'!C1,LEN(R[-1]C)+2)=""["" &R[-1]C&""]"",'[HOGARES ALBACETE.xlsx]21076'!C2)),IF(RIGHT('[HOGARES ALBACETE.xlsx]21076'!C1,LEN(R[-1]C)+2)=""[""&R[-1]C&""]"",'[HOGARES ALBACETE.xlsx]21076'!C2),0),1)"
'to 137 characters
sel.FormulaArray = _
"=INDEX(×!C1,MATCH(MAX(IF(RIGHT(×!C1,LEN(R[-1]C)+2)=""["" &R[-1]C&""]"",×!C2)),IF(RIGHT(×!C1,LEN(R[-1]C)+2)=""[""&R[-1]C&""]"",×!C2),0),1)"
With wbf
With .Worksheets(ChrW(215))
.Move before:=wbha.Worksheets(ha2ndx)
End With
End With
'restore worksheet name
wbha.Worksheets(ChrW(215)).Name = "21076"
On Error Resume Next
Application.DisplayAlerts = False
wbha.Worksheets("to be removed").Delete
Application.DisplayAlerts = True
On Error GoTo 0
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
I'd bet your Excel is not set to use R1C1 referencing, so the replace won't work as you're trying to put an R1C1 referenced string into an A1 style formula. Try using:
Application.ReferenceStyle = xlR1C1
With ActiveSheet.Range("F2")
.FormulaArray = theFormulaPart1
.Replace MiReemplazo, theFormulaPart2
End With
Application.ReferenceStyle = xlA1