Be sure to run code before exit

Stevenn

Active Member
Joined
Feb 8, 2012
Messages
259
I've got following code in the beginning of my procedure:

Code:
With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
    .Cursor = xlWait
    .DisplayStatusBar = True
End With

but sometimes my function will result in an error. Is it possible to 'restore' the settings by following code

Code:
With Application
    .Cursor = xlDefault
    .StatusBar = False
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
End With

even if the function ends before the end of the code in the procedure?
 

Excel Facts

Create a Pivot Table on a Map
If your data has zip codes, postal codes, or city names, select the data and use Insert, 3D Map. (Found to right of chart icons).
What you're looking for is VBA's error handling, which is done with "On Error Goto" or "On Error Resume", depending on exactly what needs to be done. There's a fair bit out on the internet on error handling, and ways to use it. For example, be very conservative with the use of On Error Resume and/or On error Resume Next.

Code:
Sub ErrorExitSample()
    Dim strTest                    As String
    Dim i                          As Double

    On Error GoTo RestoreAppStates
    
    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .Cursor = xlWait
        .DisplayStatusBar = True
    End With


'this is just a sample chunk of code... your real code
'would go into this area
    Do
        strTest = InputBox("Enter a number")
        If IsNumeric(strTest) Then Exit Do
        MsgBox ("That isn't a number")
    Loop
    i = CDbl(strTest)

    'next line will throw an error if '0' is entered in the input box
    MsgBox (1 / i)
    'this line (and any other code before the 'RestoreAppStates:' label) will
    'be skipped if 1/i gives an error.
    MsgBox ("Succesful division!!!")
'end of sample code


RestoreAppStates:
    With Application
        .Cursor = xlDefault
        .StatusBar = False
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
    End With

End Sub

Of course, the very best way to handle code errors is to make sure that they can't occur. In the sample above, I corrected for non-numeric input, but 'neglected' to correct for a input of 0.
 
Upvote 0
What you're looking for is VBA's error handling, which is done with "On Error Goto" or "On Error Resume", depending on exactly what needs to be done. There's a fair bit out on the internet on error handling, and ways to use it. For example, be very conservative with the use of On Error Resume and/or On error Resume Next.

Code:
Sub ErrorExitSample()
    Dim strTest                    As String
    Dim i                          As Double

    On Error GoTo RestoreAppStates
    
    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .Cursor = xlWait
        .DisplayStatusBar = True
    End With


'this is just a sample chunk of code... your real code
'would go into this area
    Do
        strTest = InputBox("Enter a number")
        If IsNumeric(strTest) Then Exit Do
        MsgBox ("That isn't a number")
    Loop
    i = CDbl(strTest)

    'next line will throw an error if '0' is entered in the input box
    MsgBox (1 / i)
    'this line (and any other code before the 'RestoreAppStates:' label) will
    'be skipped if 1/i gives an error.
    MsgBox ("Succesful division!!!")
'end of sample code


RestoreAppStates:
    With Application
        .Cursor = xlDefault
        .StatusBar = False
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
    End With

End Sub
Of course, the very best way to handle code errors is to make sure that they can't occur. In the sample above, I corrected for non-numeric input, but 'neglected' to correct for a input of 0.

I am trying to avoid any errors to occur, but I have to make use of "Exit Sub" in For Each-loop, and it wont go to my error handler. But your great example works just fine when my database call fails :-) Is there any way to make sure to restore the app states when I manually exit the procedure with "Exit Sub"?
 
Upvote 0
Without seeing the code, I can't give an exact answer, however, here's some suggestions.

If the sub is being called from another sub, you could put the application.* lines in the calling sub, like this:
Code:
Sub ParentSub()

    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .Cursor = xlWait
        .DisplayStatusBar = True
    End With

    'Called sub has an on error goto line, but 
    'does NOT make changes to the application object
    'properties.
    Call CalledSub

    With Application
        .Cursor = xlDefault
        .StatusBar = False
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
    End With

End Sub

Sub CalledSub()
    On Error GoTo ExitMySub

    'the sub that does stuff


ExitMySub:

End Sub

If you want this in a single procedure, you can just make sure to restore back to the default before each exit sub, something like this:

Code:
Sub SingletonSub()
    Dim strTest                    As String
    Dim i                          As Long

    On Error GoTo ExitMySub
    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .Cursor = xlWait
        .DisplayStatusBar = True
    End With

    'your first loop with an exit sub condition
    For i = 1 To 10
        'some if then that causes an exit from sub
        If i = 7 Then
            With Application
                .Cursor = xlDefault
                .StatusBar = False
                .Calculation = xlCalculationAutomatic
                .ScreenUpdating = True
            End With
            Exit Sub
        End If
    Next i
    'second loop with an exit sub condition
    For i = 4 To 25
        If i / 3 = 7 Then
            With Application
                .Cursor = xlDefault
                .StatusBar = False
                .Calculation = xlCalculationAutomatic
                .ScreenUpdating = True
            End With
            Exit Sub
        End If
    Next i

    'if sub doesn't exit early, or if there is an error, this will run
ExitMySub:
    With Application
        .Cursor = xlDefault
        .StatusBar = False
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
    End With

End Sub
 
Upvote 0

Forum statistics

Threads
1,223,246
Messages
6,170,996
Members
452,373
Latest member
TimReeks

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top