Excel Class VBA Macro Adds IfError Functions To Every Formula
Today a student asked Excel Class if there was a macro to automatically add an IfError function to every formula on every sheet in a selected workbook, assuming there was not already an IfError function used.
On short notice the Excel Class instructor provided the following code which we wanted to share with our readers.
Remember that macros have no Undo command. Once you run this VBA macro the only undo is to close the file without saving changes. The macro leaves a selected workbook open so you can review the changes before deciding to save or not.
To use this code, press the Alt+F11 key to open the VB Editor.
Select the Insert menu > Module command.
Then paste the following code into the empty window:
To run the program, press the F5 key, or from Excel select the Ribbon View Tab > Macros button and run the AddIfError macro.
Public Sub AddIffError()
‘purpose: IF there is a formula add iferror
‘if there’s an iferror already, ignore the formula
‘process all sheets in wb
On Error GoTo Errorhandler
‘Step 10: Ask user to open a wb
MsgBox “Please click OK to select a workbook to process”
‘Step20: Prompt user to open wb to process
‘Step30: On every sheet add iferror
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Sheets
If ws.Visible = True Then ws.Select
‘Select all cells
Dim r As Range
For Each r In Selection
If Left(r.Formula, 1) = “=” Then
If Left(r.Formula, 8) = “=IFERROR” Then
myformula = Right(r.Formula, Len(r.Formula) – 1)
r = “=IfError(” & myformula & “,0)”
If Err.Number <> 0 Then
MsgBox “Something went wrong”
If you want to learn more about Excel VBA programming check out our 2-day Excel VBA course in New York City.