Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 88854

Prevent a command button from being clicked multiple times while a sub is iterating

$
0
0

I'm creating an Excel macro that will run when a command button is pressed (VBA 7.1), and will not allow the user to click multiple times during execution, however every trick I've found online to this end has not worked: even while locked, disabled, and with focus on a different object, the user can still cause the sub to run multiple times before the first one finishes.

My current code looks like this (run_slow_macro opens a Word document to make changes, then saves it, and can take about 30 seconds to complete.)

Private Sub CommandButton1_Click()

    If CommandButton1.Enabled = False Then
        MsgBox ("STOP CLICKING")
    End If

    Me.Frame1.SetFocus
    CommandButton1.Enabled = False
    CommandButton1.Locked = True
    CommandButton1.Caption = "WAIT"

    Call run_slow_macro

    CommandButton1.Caption = "CommandButton1"
    CommandButton1.Enabled = True
    CommandButton1.Locked = False


End Sub

When I click the button, it locks and becomes disabled, and the caption changes as expected. However, subsequent clicks do not cause the "STOP CLICKING" messagebox to appear, yet still cause the Word document to be opened multiple times, edited, and then closed.

The command button does not become unlocked/enabled until after all executions are completed, and the "STOP CLICKING" messagebox never appears.

I'm very confused as to how it's executing "Call run_slow_macro" each time, but seems to be skipping everything before and after that line once the first execution is in progress.

I have very little experience with VBA, and have been unable to find any solutions online (the above code is the culmination of the most common recommendation's I've seen), so I appreciate any advice that can be offered.


Viewing all articles
Browse latest Browse all 88854


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>