Avoid Exits in the Body of a Procedure in VB6/VBA

Provided by: Luke Chung, President of FMS, Inc.

For Best Practices, each procedure should end at its bottom. This ensures all cleanup code (normally at the bottom) is executed and makes it easier for future developers (which may be you) to maintain.

VB6/VBA offers the ability to use the Exit command to leave a procedure at any point:

  • Exit Function
  • Exit Sub
  • Exit Property

While this is appropriate at the bottom of the procedure where you may have error handling code, it’s problematic if used in the middle of this procedure.

When a procedures exit in its body, all the code after it is not executed, and control jumps immediately back to the calling procedure.

For complex, long procedures with lots of loops and If statements, it's very easy to miss a hidden Exit command and not realize the flow could quit right in the middle. By avoiding the use of Exit commands in the middle of a procedure, you eliminate the need to remember or look for such instances which often cause bugs.

In the simple example below, an Exit Sub jumps out of the code while it’s moving through a recordset. While the example is trivial, one may have code searching for a particular record and exiting when it’s found. If it’s embedded within multiple IF statements, FOR loops, etc. it may be easy to miss and be the cause of bugs:

Sub SampleExit()
  On Error GoTo PROC  On Error GoTo PROC_ERR
  Dim rst As ADODB.Recordset  

  Set rst = New ADODB.Recordset
  rst.Open "Msysobjects", CurrentProject.Connection
  Do While Not rst.EOF
    Debug.Print rst![Name]
    If rst![Name] = "Modules" Then
      Exit Sub       ' <------ Avoid this
    End If
    rst.MoveNext
  Loop

PROC_EXIT:
  Set rst = Nothing
  Exit Sub           ' <------ This is okay 
  
PROC_ERR:
  MsgBox Err.Description, vbCritical, "Error occurred"
  Resume PROC_EXIT
End Sub

At the bottom of the procedure in the PROC_EXIT section, it is appropriate to leave the procedure with an EXIT command to prevent the error handling section (PROC_ERR) from executing.

The use of these exit commands in the body of the procedure is considered lazy programming and should be replaced with the use of flags (variables) that tell the subsequent code to not execute and get to the bottom of the procedure.

In the example, we can do this by creating a boolean variable and setting it to True when the record is found. The Do Loop checks this variable, and ends when it becomes True. Control then goes to the end of the Do..Loop.

Sub SampleExit()
  On Error GoTo PROC_ERR
  Dim rst As ADODB.Recordset  
  Dim fFound As Boolean
  
  fFound = False

  Set rst = New ADODB.Recordset
  rst.Open "Msysobjects", CurrentProject.Connection
  Do While Not rst.EOF And Not fFound
    Debug.Print rst![Name]
    If rst![Name] = "Modules" Then
      fFound = True
    End If
    rst.MoveNext
  Loop
...

If there were other commands after the Loop line, you could use fFound variable to either run or not run the appropriate code.

By avoiding the use of EXIT commands in the body of your procedures, you’ll make your life, or the life of the next person assigned to maintain your application, much nicer. This is especially important for long, complex procedures, where subsequent developers will have to know, or discover the hard way, that they need to examine every line of code to see if an unexpected exit occurs.

Microsoft Access DocumentationOne feature of our Total Access Analyzer program is its formatted module printout reports which bracket and indent your code so you can easily see loop and procedure exits. This lets you better understand existing code so you can decide if you need to fix it.

A feature of Total Access Analyzer is its detection of these Exit commands in the body of your procedures. It’s one of the 350+ types of Best Practices detected in your MS Access applications and VBA code.

Table Design

Query Design

Form Design

Form Tips and Mistakes

Copy Command Button and Keep Picture

Module VBA to Forms and Controls

Form Navigation Caption

Resync Record in a Subform

Synchronize Two Subforms

Multiple OpenArgs Values

Late Bind Tab Subforms

Subform Reference to Control Rather than Field

Tab Page Reference

Shortcut Keys


Combo Box Top 6 Tips

Properties and Validation

Select First Item

Cascading Combo Boxes

Zip, City, State AutoFill

Report Design

Suppress Page Headers and Footers on the First Page of Your Report

Add the NoData Event

Annual Monthly Crosstab Columns

Design Environment

Add Buttons to the Quick Access Toolbar

Collapse the Office Ribbon for more space

VBA Programming

Basics: Forms and Controls

Run VBA Code from a Macro

Use Nz() to Handle Nulls

Avoid Exits in the Body of a Procedure

Shortcut Debugging Keys

Set Module Options

Math Rounding Issues

Rename a File or Folder

Avoid DoEvents in Loops

Age Calculations

Weekday Math

Send Emails with DoCmd.SendObject

Source Code Library

Microsoft Access Modules Library

Microsoft Access Modules

VBA Error Handling

Error Handling and Debugging Techniques

Error Number and Description Reference

Basic Error Handling

Pinpointing the Error Line

Performance Tips

Linked Database

Subdatasheet Name

Visual SourceSafe

Deployment

Runtime Downloads

Simulate Runtime

Prevent Close Box

Disable Design Changes

Broken References

Remote Desktop Connection Setup

Terminal Services and RemoteApp Deployment

Reboot Remote Desktop

Missing Package & Deployment Wizard

Avoid Program Files Folder

Unavailable Mapped Drives

Microsoft Access Front-End Deployment

System Admin

Disaster Recovery Plan

Compact Database

Compact on Close

Database Corruption

Remove 'Save to SharePoint Site' Prompt from an Access Database

Class Not Registered Run-time Error -2147221164

Inconsistent Compile Error

Decompile Database

Bad DLL Calling Convention

Error 3045: Could Not Use

Converting ACCDB to MDB

SQL Server Upsizing

Microsoft Access to SQL Server Upsizing Center

Microsoft Access to SQL Server Upsizing Center

When and How to Upsize Access to SQL Server

SQL Server Express Versions and Downloads

Cloud and Azure

Cloud Implications

MS Access and SQL Azure

Deploying MS Access Linked to SQL Azure

SQL Server Azure Usage and DTU Limits

Visual Studio LightSwitch

LightSwitch Introduction

Comparison Matrix

Additional Resources

Connect with Us

 

Free Product Catalog from FMS