What is the respect between the "end" and the "exit" in VBA?

In VBA, sometimes we want to exit the program after some condition is true. But am I using end or exit sub ?

+8
vba excel-vba excel
source share
1 answer

This is a little beyond your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub do not match. They do not perform the same task.

End stops the execution of ALL code, and you should almost always use Exit Sub (or Exit Function , respectively).

The end stops ALL exectution. Although this sounds enticing, it also clears all global and static variables. ( source )

See Also DOX MSDN for Final Report

When executed, the End statement resets allmodule level variables and all static local variables in all modules. To save the value of these variables, use the Stop statement instead. You can then resume execution by storing the value of these variables.

Note. The End statement interrupts code execution without triggering Unload, QueryUnload, or Terminate events, or any other Visual Basic code. The code that you posted in the Unload, QueryUnload, and Terminate events for formclass modules and classes does not execute. Objects created from class modules are destroyed, files opened with the Open operator are closed, and the memory used by your program is freed. Links to objects belonging to other programs are invalid.

Not End Sub and Exit Sub the same. End Sub cannot be called in the same way Exit Sub may be because the compiler does not allow it.

enter image description here

This again means that you must Exit Sub , which is a completely legal operation :

Sub output
Exits the Sub procedure in which it appears immediately. Execution continues with an expression following the statement of what is called a Sub procedure. Sub output can only be used inside the Sub procedure.

In addition, and as soon as you feel how the procedures work, it is obvious that End Sub does not clear global variables. But clear the local (Dim'd) variables :

End sub
Completes the definition of this procedure.

+19
source share

All Articles