The problem that you face in an endless loop is that under various circumstances the computer gets so busy that it stops âlistening.â Then it will not respond to any changes, will not update the screen, etc.
The way to prevent this is to be sure to include the statement, âDoEventsâ inside your loop.
So, if your loop and the button are both in/on the same form, at the top of the form's code module, create a Private Boolean variable that can be tested in the loop, and set by the button. (Being near the top of the module, outside any routines it will be visible/accessible to all code of the form (which is stated as having âModule-scopeâ).
In the button click event set the boolean variable to True.
In the loop, on each iteration, test the value of the Boolean. If True, exit the loop. (I'll use elipses to indicate the routine that the loop is in, in the following):
Code:
Option Explicit
Private TimeToLeave As Boolean
Private Sub TheButton_Click()
TimeToLeave = True
End Sub
. . .
Do While True
DoEvents
' Do your loop stuff...
' ...
' ...
If TimeToLeave Then Exit Do
Loop
. . .