vba · DOCS

Improving execution speed

Maintained on

If you are not familiar with VBA, it is not uncommon to gather the necessary processes from websites and implement them as a temporary solution.

However, when you run the finished product, do you experience a shaky screen or frequent switching between processing mode and normal mode?

For those facing such issues, we would like to introduce some code that can easily solve the above problems and potentially improve the speed by simply loading it before executing the created process.

VBA Code

Public Sub sample()
    Dim previousDisplayAlerts As Boolean
    Dim previousScreenUpdating As Boolean
    Dim previousEnableEvents As Boolean
    Dim previousCalculation As XlCalculation

    previousDisplayAlerts = Application.DisplayAlerts
    previousScreenUpdating = Application.ScreenUpdating
    previousEnableEvents = Application.EnableEvents
    previousCalculation = Application.Calculation

    On Error GoTo CATCH

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    Call macro1

FINALLY:
    Application.DisplayAlerts = previousDisplayAlerts
    Application.ScreenUpdating = previousScreenUpdating
    Application.EnableEvents = previousEnableEvents
    Application.Calculation = previousCalculation

    Exit Sub

CATCH:
    Debug.Print (Err.Description)
    Resume FINALLY
End Sub

These settings affect the whole of Excel, so the code saves each previous value before changing it and restores it on both normal exit and error. Note that DisplayAlerts = False lets operations such as overwriting files or deleting sheets proceed without confirmation, which can cause unintended data loss. If the slowness comes from reading and writing cells one at a time in a loop, loading the values into an array and writing them back in one go often helps far more.

By simply writing the name of the created Sub XXXXX() procedure in the part where the actual macro is executed, you can achieve the same operation as before without the screen shaking or changes in the mouse cursor.

If you want to make it understandable to the person operating it when an error occurs, you can modify the part

Debug.Print (Err.Description)

to something like

MsgBox "An error has occurred. Error description: " & Err.Description
  • #VBA