Wrapping Formulas In An Error Test
Pages in this article
Enable For Array formulas
Of course the first attempt was far from complete. If any cell in the range contains an array formula, the subroutine errors out.
Accounting for array formulas is a bit more complicated.
First of all, we need to ensure a range containing a single array formula is treated as a single entity. Secondly, we need to keep track of the ranges with a single array formula so we don't try to convert their formula more than once. The code below does all that:
Sub ChangeFormulas()
Dim oCell As Range
Dim sFormula As String
Dim sInput As String
Dim oDone As Range
Dim bFirst As Boolean
Static sFormulaTemplate As String
If sFormulaTemplate = "" Then
sFormulaTemplate =
"=IF(ISERROR(_form_),"""",_form_)"
End If
sInput = InputBox("Enter base formula", , sFormulaTemplate)
If sInput = "" Then Exit Sub
sFormulaTemplate = sInput
For Each oCell In Selection
sFormula = Replace(sFormulaTemplate,
"_form_", Right(oCell.Formula, _
Len(oCell.Formula) - IIf(Left(oCell.Formula, 1) = "=", 1, 0)))
If bFirst = False Then
bFirst = True
Set oDone =
oCell
If
oCell.HasArray Then
oCell.CurrentArray.FormulaArray = sFormula
Set oDone = Union(oDone, oCell.CurrentArray)
Else
oCell.Formula = sFormula
Set oDone = Union(oDone, oCell)
End If
ElseIf Intersect(oDone, oCell) Is
Nothing Then
If
oCell.HasArray Then
oCell.CurrentArray.FormulaArray = sFormula
Set oDone = Union(oDone, oCell.CurrentArray)
Else
oCell.Formula = sFormula
Set oDone = Union(oDone, oCell)
End If
End If
Next
End Sub
Frequently asked Questions
What is the purpose of wrapping formulas in an error test?
How does the provided VBA subroutine handle array formulas differently from regular formulas?
Why is it important to treat a range containing a single array formula as a single entity?
What does the VBA code do to avoid converting the same array formula more than once?
How does the subroutine prompt the user to enter a base formula template?
What is the role of the variable sFormulaTemplate in the VBA code?
How does the code replace the placeholder _form_ in the formula template?
What happens when the subroutine encounters a cell with an array formula?
How does the subroutine keep track of cells or ranges that have already been processed?
What is the significance of the InputBox in the ChangeFormulas subroutine?


Comments