【问题标题】:VBA disable Checkbox click event from firing inside Textbox change eventVBA禁止在文本框更改事件中触发复选框单击事件
【发布时间】:2017-05-07 16:26:40
【问题描述】:

我想做这样的事情。不知道在 Excel VBA 中是否可行。在用户表单上,我有一个复选框和一个文本框。

当我选中复选框时,复选框的标题将插入到文本框中,当我取消选中复选框时,复选框的标题将从同一个文本框中删除。

当我在文本框中写入复选框的标题时,在文本框更改事件内,复选框状态将被更新。同时,复选框单击事件被触发,标题文本将加倍。如何阻止复选框单击事件触发两次?

复选框的点击事件代码:

Private Sub cbSelect_Click()
    With TextBox1
        .Value = IIf(cbSelect.Value, _
        .Value & cbSelect.Caption, _
        Replace(.Value, cbSelect.Caption, vbNullString))
    End With
End Sub

文本框的变化事件代码:

Private Sub TextBox1_Change()
    If InStr(TextBox1.Value, cbSelect.Caption) Then
        cbSelect.Value = 1
    Else
        cbSelect.Value = 0
    End If
End Sub

有什么想法吗?

【问题讨论】:

  • 你测试过你得到的任何答案吗?有什么反馈吗?

标签: excel vba checkbox


【解决方案1】:

您的代码实际上对我有用,而没有您描述的问题只是替换:

InStr(Me.TextBox1.Value, Me.cbSelect.Caption)

与:

InStr(Me.TextBox1.Value, Me.cbSelect.Caption) > 0

顺便说一句,这里有一些可能有用的编码建议:

  • 我总是使用Me 关键字并引用Userform 控件。

    这还将有Intellisense 帮助您查找UserForm 控件名称

  • 你的cbSelect.Value设置代码可以缩短到一行

以上所有的结果:

Private Sub TextBox1_Change()
    Me.cbSelect= InStr(Me.TextBox1.Value, Me.cbSelect.Caption) > 0
End Sub

Private Sub cbSelect_Click()
    With Me.TextBox1
        .Value = IIf(Me.cbSelect, _
                    .Value & Me.cbSelect.Caption, _
                    Replace(.Value, Me.cbSelect.Caption, vbNullString))
    End With
End Sub

【讨论】:

  • @ĐứcThanhNguyễn,你通过了吗?
  • @ĐứcThanhNguyễn,如果你能向试图帮助你的人提供适当的反馈,那就太好了。谢谢
【解决方案2】:

我在User_Form 模块级别添加了Public TextBoxFlag As Boolean,并且在两个Control 的事件中都修改并检查了这个“标志”。

一旦代码进入TextBox1_Change事件标志获得True值,当代码到达cbSelect_Click事件时,如果TextBoxFlag = True的值它不会运行里面的代码,只有当是False(不是来自TextBox1_Change事件,而是直接来自CheckBox1事件)。

代码

Option Explicit

Public TextBoxFlag As Boolean

Private Sub cbSelect_Click()

    ' check if event came from the value being modified in the TextBox1_Change event
    If TextBoxFlag = False Then
        With TextBox1
            .Value = IIf(cbSelect.Value, _
            .Value & cbSelect.Caption, _
            Replace(.Value, cbSelect.Caption, vbNullString))
        End With
    End If

End Sub


Private Sub TextBox1_Change()

    ' raise the flag >> came from TextBox change event
    TextBoxFlag = True

    If InStr(TextBox1.Value, cbSelect.Caption) > 0 Then
        cbSelect.Value = True
    Else
        cbSelect.Value = False
    End If
    ' reset the flag
    TextBoxFlag = False

End Sub

【讨论】:

    【解决方案3】:

    当我测试您的代码时,复选框状态没有改变,我认为这是由于使用了二进制值 (1 / 0) 而不是布尔值 (True / False)

    我将您的 Textbox1_Changecode 更改为以下内容,并在删除复选框 c 的一部分后立即

    Private Sub TextBox1_Change()
        If InStr(TextBox1.Value, cbSelect.Caption) Then
            cbSelect.Value = True
        Else
            cbSelect.Value = False
        End If
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多