【问题标题】:Disable Text_Change event VBA禁用 Text_Change 事件 VBA
【发布时间】:2020-04-09 09:44:57
【问题描述】:

亲爱的,

有没有办法禁用 Textbox_change 事件?我试试

Application.EnableEvents = False 

但它不起作用。

    If .txtHomeNumber.Value <> "" Then
        If IsNumeric(txtHomeNumber.Value) Then
            .txtHomeNumber.BackColor = RGB(255, 255, 255)
            .txtMobileNumber.BackColor = RGB(255, 255, 255)
            .txtParentsNumber.BackColor = RGB(255, 255, 255)
        Else: MsgBox "Please enter a valid Home Number in Contact Details section.", vbExclamation, "Contact Details"
            Application.EnableEvents = False
                .txtHomeNumber.Value = Left(.txtHomeNumber.Value, Len(.txtHomeNumber.Value) - 1)
            Application.EnableEvents = True
            Exit Sub
        End If
    End If

【问题讨论】:

  • 添加一个模块级布尔变量并将其作为事件的第一行进行检查 - If bEnabled Then.... &lt;do stuff&gt; Else &lt;don't do stuff&gt; End If
  • 或者不要使用更改事件,因为每次更改都会触发它,使用更新后或退出事件
  • @Darren Bartrup-Cook 我是用户表单使用的新手。您能举个例子吗?非常感谢您的快速回复。
  • 什么情况下您不希望触发事件 - 我认为您希望有时触发事件?

标签: excel vba userform


【解决方案1】:

此代码在Userform 上使用TextBoxCommandButton
我刚刚添加了按钮,以便您可以在启用禁用之间进行切换。

Option Explicit

Private bEnabled As Boolean

Private Sub UserForm_Initialize()
    'Starts as FALSE so change to TRUE when form first opens.
    bEnabled = True
End Sub

Private Sub TextBox1_Change()

    If bEnabled Then
        MsgBox "Enabled"
'        If .txtHomeNumber.Value <> "" Then
'            If IsNumeric(txtHomeNumber.Value) Then
'                .txtHomeNumber.BackColor = RGB(255, 255, 255)
'                .txtMobileNumber.BackColor = RGB(255, 255, 255)
'                .txtParentsNumber.BackColor = RGB(255, 255, 255)
'            Else: MsgBox "Please enter a valid Home Number in Contact Details section.", vbExclamation, "Contact Details"
'                Application.EnableEvents = False
'                    .txtHomeNumber.Value = Left(.txtHomeNumber.Value, Len(.txtHomeNumber.Value) - 1)
'                Application.EnableEvents = True
'                Exit Sub
'            End If
'        End If
    End If

End Sub

Private Sub CommandButton1_Click()
    bEnabled = Not bEnabled
End Sub

查看您的代码 - 您确定不想在 AfterUpdate 事件中使用它吗?

【讨论】:

    【解决方案2】:

    我通常定义自己的布尔值,如下所示:

    Public DisableEvents As Boolean
    
    Private Sub SomeObject_Change()
        If Not DisableEvents Then
            DisableEvents = True
                ' do_stuff
            DisableEvents = False
        End If
    End Sub
    

    这可以防止您以其他方式创建的无限循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 2016-09-25
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多