How to use End statement in VBA?

The End statement in VBA (Visual Basic for Applications) is a powerful command used to immediately terminate the execution of a program or procedure. When the End statement is executed, it stops code execution abruptly, closes all files opened with Open statements, clears all variables, and releases all system resources.

How to Use the End Statement

The End statement is very straightforward to use; you simply include it in your code where you want the execution to stop:

VBA
Sub ExampleProcedure()
    ' Some code here
    If SomeCondition Then
        End
    End If
    ' More code that will not be executed if the condition is True
End Sub

In this example, if SomeCondition is True, the End statement will be executed, and the entire program will stop immediately.

Points to Consider

Abrupt Termination: The End statement terminates the program immediately without any cleanup. This means that it does not execute any remaining code, including Finally blocks or any error handling routines you might have in place.

Use Sparingly: Due to its abrupt nature, it’s generally recommended to use the End statement sparingly. It can be useful in situations where an unrecoverable error occurs and there is no point in continuing the execution of the program. However, in most cases, it’s better to use structured error handling or other forms of program control to gracefully exit a procedure or function.

No Release of Object References: The End statement does not trigger the release of object references, so if you are using COM objects or other resources that require manual release or disposal, the End statement may leave these resources open until the entire application is closed.

Impact on Global Variables and States: Global variables and program states are cleared when End is executed. If your application relies on these for subsequent operations or if you need to maintain state information, the End statement may not be appropriate.

Alternative Methods: Consider using Exit Sub, Exit Function, or Exit Property to exit from a procedure gracefully without terminating the entire program. These commands will allow you to exit a subroutine, function, or property method cleanly while continuing with the rest of your program.

In summary, while the End statement is a quick and easy way to terminate a program, its use should be limited to scenarios where an immediate and complete stop of all program execution is required and where the abrupt termination will not lead to unintended consequences.

Switch the language

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project

Leave a Reply

Your email address will not be published. Required fields are marked *