Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Well you could declare the variable at module level in the forms as private. That is not a global but a module level variable. Then you could pass it to the function you create and check it in the function.</p> <p>But be careful with the DoEvents. It basically means allow the windows message loop to process messages. This means that not only can the user click your button again, they can close the form and do other things. So when you are in this loop you'll need to set a module level variable anyway as you'll need to check for it in a QueryUnload of the form and in any event handlers.</p> <p>You can also use the Tag property of the control itself to store a flag of sorts. But I don't consider that more elegant.</p> <p>I also prefer to use two different buttons. Just hide one and show the other. That way your cancel code and run code are separated in different event handlers.</p> <p>To expand on my answer here is some sample code that handles the unloading aspect. Here if you stop via the x it prompts you. If you kill via task manager, it dies gracefully.</p> <pre><code>Option Explicit Private Enum StopFlag NotSet = 0 StopNow = 1 StopExit = 2 End Enum Private m_lngStopFlag As StopFlag Private m_blnProcessing As Boolean Private Sub cmdGo_Click() Dim lngIndex As Long Dim strTemp As String m_lngStopFlag = StopFlag.NotSet m_blnProcessing = True cmdStop.Visible = True cmdGo.Visible = False For lngIndex = 1 To 99999999 ' check stop flag Select Case m_lngStopFlag Case StopFlag.StopNow MsgBox "Stopping - Last Number Was " &amp; strTemp Exit For Case StopFlag.StopExit m_blnProcessing = False End End Select ' do your processing strTemp = CStr(lngIndex) ' let message loop process messages DoEvents Next lngIndex m_lngStopFlag = StopFlag.NotSet m_blnProcessing = False cmdGo.Visible = True cmdStop.Visible = False End Sub Private Sub cmdStop_Click() m_lngStopFlag = StopFlag.StopNow End Sub Private Sub Form_Load() m_blnProcessing = False End Sub Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer) Select Case UnloadMode Case vbFormControlMenu, vbFormCode If m_blnProcessing Then Cancel = True If MsgBox("Unload Attempted - Cancel Running Process?", vbOKCancel + vbDefaultButton1 + vbQuestion, "Test") = vbOK Then m_lngStopFlag = StopFlag.StopExit End If End If Case Else m_lngStopFlag = StopFlag.StopExit Cancel = True End Select End Sub </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload