我正在创建一个Excel宏,该宏将在按下命令按钮时运行(VBA 7.1),并且不允许用户在执行过程中多次单击,但是我为此找到的每项技巧都还没有可行:即使在锁定,禁用并专注于其他对象的情况下,用户仍可以使子程序在第一个完成之前运行多次。
我当前的代码如下(run_slow_macro
打开Word文档进行更改,然后保存它,大约需要30秒才能完成。)
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
当我单击按钮时,它会锁定并被禁用,并且标题会按预期更改。但是,随后的单击不会导致出现“ STOP CLICKING”消息框,但仍会导致Word文档被多次打开,编辑然后关闭。
在所有执行完成后 ,命令按钮不会解锁/启用,并且永远不会出现“ STOP CLICKING”消息。
我对每次如何执行“调用run_slow_macro”感到非常困惑,但是似乎在第一次执行正在进行时会跳过该行之前和之后的所有内容。
我对VBA的经验很少,也无法在线找到任何解决方案(上面的代码是我所见过的最常见建议的最终结果),因此,我感谢可以提供的任何建议。
答案 0 :(得分:1)
这将禁用宏执行,直到完成为止。阅读代码注释。
看到我正在使用HasStarted
中定义为run_slow_macro
的变量来告诉命令按钮应该在宏未完成时退出。
Option Explicit
' This variable should be declared at the top of the module
Private HasStarted As Boolean
Private Sub CommandButton1_Click()
If HasStarted = True Then Exit Sub
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
Public Sub run_slow_macro()
HasStarted = True
' Do something
HasStarted = False
End Sub
让我知道它是否有效
答案 1 :(得分:0)
看看以下内容。我相信它有您的答案。