我正在禁用按钮onclick,但它仍然允许点击。
代码如下:
UsrForm.Field1.Value = ""
UsrForm.Field2.Value = ""
UsrForm.btn.Enabled = False
UsrForm.Repaint
/*Processing Occurs*/
UsrForm.Field1.Value = val1
UsrForm.Field2.Value = val2
UsrForm.btn.Enabled = True
但是,如果我双击或单击禁用按钮的几次,它仍会多次运行该方法,尽管被禁用。
答案 0 :(得分:1)
这很有意思。我同意你的代码应该有效,我很困惑。但是,我是那种会编码的人,所以这里有一些使用模块级变量来记录程序是否已经运行。
Option Explicit
Private mbAlreadyProcessing As Boolean
Private Sub btn_Click()
On Error GoTo ErrHandler
If Not mbAlreadyProcessing Then
mbAlreadyProcessing = True
'do some work
mbAlreadyProcessing = False
End If
Exit Sub
ErrHandler:
'here we remember to "re-enable"
mbAlreadyProcessing = False
'do some error handling
End Sub
答案 1 :(得分:1)
我认为我们这里有一个错误的错误。 S Meaden发布的解决方案不起作用(至少不在我的测试中)。以下是我一起测试的内容:
Private Sub CommandButton1_Click()
Dim w As Date
Me.CommandButton1.Enabled = False
w = Now + TimeSerial(0, 0, 2)
Debug.Print "point 1: " & Now
Application.Wait w
Debug.Print "point 2: " & Now
Me.CommandButton1.Enabled = True
End Sub
单击它会使其变灰(如禁用时那样)并运行例程。然后单击两次运行例程两次。因为它打印时间,很明显,例程按顺序运行,所以excel(在我的情况下为excel,未经过其他应用程序测试)的接缝会记住点击,并在例程结束时(并且按钮已启用)再次)调用例程。它也会连续运行3到4次。
因此,实施S Meaden的答案,如下:
Dim clicked as Boolean
Private Sub CommandButton1_Click()
Dim w As Date
If Not clicked Then
clicked = True
Me.CommandButton1.Enabled = False
w = Now + TimeSerial(0, 0, 2)
Debug.Print Now
Application.Wait w
Debug.Print "punt 2 (" & Now & ")"
Me.CommandButton1.Enabled = True
clicked = False
End If
End Sub
也不起作用。
似乎如果在例程完成后启用了按钮,则会丢弃在例程执行期间放置的单击。因此,作为一种解决方法,您可以使用:
Private Sub CommandButton1_Click()
Dim w As Date
Me.CommandButton1.Enabled = False
w = Now + TimeSerial(0, 0, 2)
Debug.Print "point 1: " & Now
Application.Wait w
Debug.Print "point 2: " & Now
Me.Button1_clicked = False
Application.OnTime (Now + 0.000001), "enable_commandbutton"
End Sub
“enable_commandbutton”为:
Public Sub enable_commandbutton()
Dim uf As Object
Debug.Print "check"
For Each uf In VBA.UserForms
If uf.Name = "UserForm1" Then
uf.CommandButton1.Enabled = True
End If
Next uf
End Sub
在正常的代码模块中。
它不漂亮,但它有效。