Results 1 to 4 of 4

Thread: VBA cancel button

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    May 2002
    Posts
    158

    Question VBA cancel button

    I have an Excel macro that works just fine. However, in certain cases, the macros can run for a VERY long time, producing many sheets with 500k rows per sheet.

    If I sense that the data is such that the macro will keep running for a very long time, I open the Task Manager and kill the Excel process. This works, but isn't exactly pretty. Question: I know that I could put a Cancel button on the userform, but my fear is that given the processing that is going on, if the button were clicked, this click would not be handled until the processing is done.

    Any suggestions?

  2. #2
    PowerPoster
    Join Date
    Jul 2010
    Location
    NYC
    Posts
    7,653

    Re: Cancel button?

    If you put a DoEvents statement somewhere in the loop, the button can be used to set a flag you check for then exit the processing loop.

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    May 2002
    Posts
    158

    Re: Cancel button?

    Thank you. The code seems to be working, but for some reason the mouse changes from an hourglass to a small plus sign when the DoEvents line is executed...

  4. #4
    Lively Member anycoder's Avatar
    Join Date
    Jan 2025
    Posts
    67

    Re: VBA cancel button

    You can also block all user interactions in the userform by setting its Enabled to False and using GetAsyncKeyState to check if the Esc key is pressed to cancel the operation.

    Code:
    Private Declare PtrSafe Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
     
      
    Private Sub CommandButton2_Click()
    Dim i As Long, t As Single
    t = Timer
    Application.ScreenUpdating = False
    Enabled = False
    For i = 1 To 500000
     ' random task
     Cells(i, "A").Value = Cells(i, "A").Value + Cells(i, "B").Value
     
     'update status
     If (Timer - t) > 0.1 Then
       Caption = (i * 100 \ 500000) + 1 'displays progress
       DoEvents
      If GetAsyncKeyState(27) < 0 Then
          If MsgBox("Do you want cancel the operation ?", vbYesNo Or vbExclamation) = vbYes Then
             Exit For
          End If
       End If
       t = Timer
     End If
    Next
    Application.ScreenUpdating = True
    Unload Me
    End Sub

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width