1

Found some tips here and in google, but can't implement properly.

Say I have a loop that runs, and I need to show a box with a button "Cancel". The code must run till I press the button. In the following example I used For Loop and show iteration number in the Label1.Caption

' action of UserForm1 on Button Click
Private Sub CommandButton1_Click()
    cancel = True
End Sub

Public cancel as boolean

Sub example ()
    cancel = False
    Dim i As Integer

    For i = 1 To 1000
        Application.Wait (Now + #12:00:01 AM#)
        UserForm1.Label1.Caption = CStr(i)
        UserForm1.Show vbModeless
        If cancel = True Then
            Exit For
        End If
    Next i         
End Sub

This code runs, but it doesn't react on Button click. If I do UserForm1.Show vbModal, then the code stops and waits till I click the button. What am I doin wrong?

DDR
  • 459
  • 5
  • 15

1 Answers1

0

This is my code and it works perfectly when the userform is opened with frmTest.Show false

Dim cancelbool As Boolean

Function loopfunction()

Dim i As Integer

i = 0

Do Until cancelbool
    DoEvents
    Me.lblIteration.Caption = i
    i = i + 1
Loop
End Function

Private Sub cmdCancel_Click()

cancelbool = True
End Sub

Private Sub UserForm_Activate()

loopfunction
End Sub

And by the way, the Application.Wait makes your app unresponsive

gizlmo
  • 1,882
  • 1
  • 14
  • 14
  • Thanks. Is there any other way to pause a sub? I check free license on a server once in 10 seconds and I need to wait a little bit between server queries. – DDR May 31 '16 at 10:43
  • I'm not sure, I would probably use a loop that counts to a very high value (a few million maybe) and use `DoEvents` inside it so the app is still responsive – gizlmo May 31 '16 at 10:51
  • If this solved your problem, please mark it as answer :) – gizlmo May 31 '16 at 11:23
  • You can also use a sub with `Application.OnTime` to do the job. – Vincent G May 31 '16 at 13:50