Macros
Make Excel Great Again!
Important Notes
The are a few things to note about macros before we jump into the really useful ones:
- Upon running a single line of code that affects the content of the workbook you're in, Excel will (by default) perform calculations and run events or functions in the background.
- Macros will not run as fast as they should unless you disable these background calculations.
- You can call other macros (also called 'Sub Procedures') to run inside any macro. This can be very useful for breaking more complex code into smaller chunks and running a set of standard operations each time.
I therefore like to begin my macros by optimising them for speed and calling the procedure, 'TurnStuffOff', which disables all of these computationally demanding items:
VBA: Turn Stuff Off
Sub TurnStuffOff() 'Obtained from bgrconsulting.co.uk/macros where help and support can be found.
Application.EnableEvents = False
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
End Sub Of course, in doing this, your sheet will not perform properly when using it in the standard manner. We therefore have to end each macro by turning this stuff back on.
VBA: Turn Stuff On
Sub TurnStuffOn() 'Obtained from bgrconsulting.co.uk/macros where help and support can be found.
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
End Sub With that out of the way, we can move onto some of the more genuinely useful stuff...
Effective Error Handling
If you have seen an entire sheet present #REF! then you know how scary error messages in Excel can be. Even if they are valid, useful error messages like #DIV/0! can throw a lot of people off from the actual content of the workbook because it looks as though things aren't working properly. At BGR Consulting, we therefore recommend that you use error handling when building functions that are likely to go wrong (e.g. those including division of numbers that could go to zero or those containing references to other workbooks).
However, with that said, if you are building a more complex formula with nested functions (aka, functions within functions, such as =ROUND(SUM( or =INDEX(MATCH( etc.) then it can quickly become overwhelming to have to worry about adding in your IFERROR function as well.
This is where the ADD_IFERROR macro comes in. This beast will quickly cycle through a cell selection and add the IFERROR function to the beginning of each formula and close it out at the end. Not only that, but it is completely dynamic, meaning that it will actually ask you what you would like to present in the instance that an error does occur.
'But what if I accidentally select cells without a formula in them?'
No problem, this macro will ignore them entirely, meaning you won't end up with a mess of text within your non-formulaic cells.
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 Leave
If Selection.Count = 1 Then
If Left(Cell.Formula, 1) <> "=" Then GoTo Leave 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
Call TurnStuffOff
For Each Cell In Rng
On Error GoTo -1
On Error GoTo NextCell
If Cell.Formula = "" Then GoTo NextCell
If Left(Cell.Formula, 1) <> "=" Then GoTo NextCell
If Left(Cell.Formula, 9) = "=IFERROR(" And Mid(Cell.Formula, Len(Cell.Formula) - Len(ErrVal) - 1, Len(ErrVal)) = ErrVal Then GoTo NextCell
If Left(Cell.Formula, 9) = "=IFERROR(" Then _
IfErr = MsgBox("Cell " & Replace(Cell.Address, "$", "") & " 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, ",") - 1) & "," & ErrVal & ")", _
vbExclamation + vbYesNo, "Replace IFERROR?")
If IfErr = vbNo Then GoTo NextCell
If IfErr = vbYes Then Cell.Formula = Mid(Cell.Formula, 1, InStrRev(Cell.Formula, ",") - 1) & "," & ErrVal & ")": i = i + 1: GoTo NextCell
If Left(Cell.Formula, 9) = "=IFERROR(" And Mid(Cell.Formula, Len(Cell.Formula) - Len(ErrVal), Len(ErrVal)) = ErrVal Then i = i + 1: GoTo NextCell
Cell.Formula = "=IFERROR(" & Mid(Cell.Formula, 2, 9999) & "," & ErrVal & ")"
i = i + 1
NextCell:
IfErr = Empty
Next Cell
If Selection.Count = 1 And i = 0 Then MsgBox "The cell has not been reformulated per your instruction.", vbOKOnly, "Failure..."
If Selection.Count <> 1 And i = 0 Then MsgBox "No cells have been reformulated per your instruction.", vbOKOnly, "Failure..."
If Selection.Count = 1 And i = 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!"
Call TurnStuffOn
Exit Sub
Leave:
MsgBox "No cells in your selection contain formulas; nothing happened.", vbOKOnly, "Try again:"
End Sub Round Numbers Effortlessly
Precision is key in financial analysis, but manually rounding numbers across a large spreadsheet can be tedious. Similar to the Add_IFERROR macro, the Add_ROUND macro simplifies this by applying the ROUND function to your selected cells.
VBA: Add ROUND
Sub Add_ROUND() 'This macro is used to round formulas to a user provided number of decimal places; obtained from bgrconsulting.co.uk/macros where help and support can be found.
On Error GoTo NoF
If Selection.Count = 1 Then
If Left(Cell.Formula, 1) <> "=" Then GoTo NoF Else Set Rng = Selection
Else: Set Rng = Selection.SpecialCells(xlCellTypeFormulas)
End If
Begin:
dps = InputBox("To how many decimal places would you like to round the selected cells?", "Decimal Places?")
If dps = "" Then Exit Sub
On Error GoTo -1: On Error GoTo Leave
dps = Int(dps)
On Error GoTo 0
Call TurnStuffOff
If Selection.Cells.Count = 1 Then Set Rng = ActiveCell Else Set Rng = Selection.SpecialCells(xlCellTypeVisible)
For Each Cell In Rng
On Error GoTo -1
On Error GoTo NextCell
If Cell.Value = "" Then GoTo NextCell
If Cell.Style = "Percent" Then
AnsP = MsgBox("Cell " & Replace(Cell.Address, "$", "") & " is formatted as a percentage, would you like to round this number to " & dps + 2 & " decimal places instead?", vbExclamation + vbYesNo, "Warning: Percentage Detected!")
If AnsP = vbYes Then dps = dps + 2
If AnsP = vbNo Then Skip = MsgBox("Would you like to skip the rounding of cell " & Replace(Cell.Address, "$", "") & "?", vbExclamation + vbYesNo, "Warning: Percentage Detected!")
If Skip = vbYes Then GoTo NextCell
End If
If Left(Cell.Formula, 1) <> "=" Then Cell.Value = Round(Cell.Value, dps): GoTo NextCell
If InStr(Cell.Formula, "=ROUND(ROUND(") Then Cell.Formula = "=ROUND(" & Mid(Cell.Formula, 14, Len(Cell.Formula) - 19) & "," & dps & ")": GoTo NextCell
If InStr(Cell.Formula, "=ROUND(") And Mid(Cell.Formula, Len(Cell.Formula) - 1, 1) = "" & dps & "" Then GoTo NextCell
If Left(Cell.Formula, 7) = "=ROUND(" Then _
Rounded = MsgBox("Cell " & Replace(Cell.Address, "$", "") & " is already rounded as follows:" _
& vbNewLine & Cell.Formula & vbNewLine _
& vbNewLine & "Would you like to replace this formula with the following:" _
& vbNewLine & "=ROUND(" & Mid(Cell.Formula, 8, Len(Cell.Formula) - 10) & "," & dps & ")", _
vbExclamation + vbYesNo, "Round a Rounded Formula?")
If Rounded = vbNo Then GoTo NextCell
If Rounded = vbYes Then Cell.Formula = "=ROUND(" & Mid(Cell.Formula, 8, Len(Cell.Formula) - 10) & "," & dps & ")": GoTo NextCell
Cell.Formula = "=ROUND(" & Mid(Cell.Formula, 2, 9999) & "," & dps & ")"
NextCell:
If AnsP = vbYes Then dps = dps - 2
AnsP = Empty
Rounded = Empty
Next Cell
MsgBox "All visible cells within the selection have been rounded.", vbOKOnly, "Success!"
Call TurnStuffOn
Exit Sub
Leave:
Retry = MsgBox("The value entered must be an integer (between 0 and 22). Would you like to try again?", vbCritical + vbYesNo, "Retry?")
If Retry = vbYes Then GoTo Begin
Call TurnStuffOn
Exit Sub
NoF:
MsgBox "No cells in your selection contain formulas; nothing happened.", vbOKOnly, "Try again:"
End Sub How It Works:
- You select the cells that you want to round.
- The macro asks you for the desired number of decimal places.
- It then rounds each number or formula result accordingly.
- For percentages, the macro can adjust the rounding to suit your needs, asking if you'd like to round to a higher precision.