Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stopping a loop when a command button click

Status
Not open for further replies.

radha83

Programmer
Feb 19, 2002
15
0
0
IN
I have a loop that has a lot of iterations and i want that to be stopped when a command button is clicked. how do i do that? thanks for any help
Radha
 
Hi,
Use the DoEvents statement in the loop and tie the condition of the loop to the button e.g.

Option Explicit
Dim arr(12) As Integer
Dim blnStop As Boolean

Private Sub Command1_Click()
blnStop = False
End Sub

Private Sub Form_Load()
Label1.Caption = "start"
frmThings.Show
blnStop = True
While (blnStop = True)
arr(0) = 1
DoEvents
Wend
Label1.Caption = "over"
End Sub

Jon
 
Hi,

Here's a way:

Dim UserBreak as boolean

private sub CmdUserBreak_Click()
UserBreak=true
end sub

private sub Form_load()
UserBreak=false
end sub

Private sub DoMyLoop()
do
do events
if UserBreak then msgbox("User breaks!"):exit sub
loop
end sub
Sunaj
'The gap between theory and practice is not as wide in theory as it is in practice'
 
Sorry Jon
I didn't see your post before I wrote mine... Sunaj
'The gap between theory and practice is not as wide in theory as it is in practice'
 
I'd use a boolean in a while loop

while <your condition> AND not bClicked

wend


But like the other guys don't forget Do Events
Give a man a program and tomorrow he will be hungry.
Teach a man to program and he will never hunger again.
--Sunr¿se

 
Sorry that sounded bad,

I meant &quot;in agreement with the other guys use Do Events&quot;

;¿) Give a man a program and tomorrow he will be hungry.
Teach a man to program and he will never hunger again.
--Sunr¿se

 
Here is a little bit of an optimization...

private userCanceled as boolean

for i = 0 to upper 'upper can be some really big number
if userCanceled then exit for
'do the loop code

if i mod 100 = 0 then 'only run the doevents after every 100th iteration, this save some processor overhead..
doevents
endif
next i


'================
If it is really critical that the code stop execution immediately after the button has been pressed, then by all means forget the iteration test. If you are searching for files and you just want to stop the search, then the iteration test will help emmensly(sp?)....

Troy Williams B.Eng.
fenris@hotmail.com

 
hi,
Thanks all. it is actually a nested loop and i have put the
'do events' statement in the outer loop, as i don't need that much time accuracy and it worked.
Radha
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top