End and Exit Sub

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all,

what is the difference between End and Exit Sub if they are used in a Sub?
What state will be in after using them each?

Clara
 
Exit sub does exactly what it says... it exits the current sub. If the sub
was called by another sub then that sub will continue on as normal. Exit sub
does NOT halt all execution. It just exit the current sub.

End halts ALL exectution. While this sounds tempting to do it also clears
all global and static variables. It is the equivalent of stopping your car by
steering it into a tree. Your car will stop but the consequences are
significant. VERY RARELY do you want to use End... 99% of the time you see
someone using End I would contend that it is probably an inappropriate use.

If you need to halt all execution then you probably want to convert your sub
into a function of some sort that returns a value which indicates to a
calling procedure whether the calling procedure should continue.

Purely as an aside it is a good coding practice to minimize your usage of
Exit Sub. The difficulty is that if it is used heavily it can be difficult to
debug your procedures. If you can exit your sub at a number of different
points then it can be difficult to determine how much of your sub executed
before it exited. I normally will only use Exit Sub instructions at the
beginning of my procedures to determine if I want to execute the procedure at
all. Once I get into the body of the procedure I tend to use If-Then-Else
instructions to control the execution...

As always these are rules and rules are made to be broken. But before you
break any rules you need to understand why the rule exists...
 
Thank you so much Jim,

Why did you say "End halts all execution ".Because after that, Excel still
response to user's event. I mean application's execution does not stop yet.

Clara
thank you so much for your help
 
End stops the currently exectuing code dead in it's tracks inclucing
unloading all of the memory (from the heap and the stack). Code exectution
can be reinitiated but all of the global and static variabe values will be
gone...
 
Back
Top