Macros

Add IFERROR

VBA: Add IFERROR Function

Sub Add_IFERROR() 'This macro is used to add the IFERROR function to a formula; obtained from bgrconsulting.co.uk/macros where help and support can be found.
On Error GoTo NoF
If Selection.Count = 1 Then
    If Left(Selection.Formula, 1) <> "=" Then GoTo NoF Else Set Rng = Selection
Else: Set Rng = Selection.SpecialCells(xlCellTypeFormulas)
End If

Begin:
ErrVal = InputBox("What value would you like the cell to show in the instance an error occurs?", "Value If Error?")
If ErrVal = "" Then Exit Sub
If MidSub <> vbYes Then Call z_TurnStuffOff

    For Each Cell In Rng
        On Error GoTo -1: On Error GoTo NextCell
        If Left(Cell.Formula, 9) = "=IFERROR(" Then
            If Mid(Cell.Formula, Len(Cell.Formula) - Len(ErrVal), Len(ErrVal)) = ErrVal Then
                x = x + 1
            Else
                IfErr = MsgBox("Cell " & Cell.Address(0, 0) & " already contains IFERROR as follows:" _
                & vbNewLine & Cell.Formula & vbNewLine _
                & vbNewLine & "Would you like to replace this formula with the following:" _
                & vbNewLine & Mid(Cell.Formula, 1, InStrRev(Cell.Formula, ",")) & ErrVal & ")", _
                vbExclamation + vbYesNo, "Replace IFERROR?")
                If IfErr = vbYes Then Cell.Formula = Mid(Cell.Formula, 1, InStrRev(Cell.Formula, ",")) & ErrVal & ")": i = i + 1
            End If
        Else
            Cell.Formula = "=IFERROR(" & Mid(Cell.Formula, 2) & "," & ErrVal & ")"
            i = i + 1
        End If
NextCell:
    Next Cell
If Selection.Count = 1 And i = 0 And x = 0 Then MsgBox "The cell has not been reformulated per your instruction.", vbOKOnly, "Warning:"
If Selection.Count <> 1 And i = 0 And x = 0 Then MsgBox "No cells have been reformulated per your instruction.", vbOKOnly, "Warning:"
If Selection.Count = 1 And i = 1 Or x = 1 Then MsgBox "The selected cell has been reformulated.", vbOKOnly, "Success!"
If Selection.Count <> 1 And i = 1 Then MsgBox "One of the selected cells has been reformulated.", vbOKOnly, "Success!"
If i > 1 Then MsgBox Format(i, "#,##0") & " cells containing formulas within the selection have been reformulated.", vbOKOnly, "Success!"
If x > 1 Then MsgBox Format(x, "#,##0") & " cells within the selection were already formulated correctly; these cells are unchanged.", vbOKOnly, "Success!"
If MidSub <> vbYes Then Call z_TurnStuffOn
Exit Sub

NoF:
MsgBox "No cells in your selection contain formulas; nothing happened.", vbOKOnly, "Try again:"
End Sub