【问题标题】:Why my checkboxes doesn't work when I try to launch my userform with a button on the sheet and work when I launch the userform from the main menu?为什么当我尝试使用工作表上的按钮启动我的用户表单时我的复选框不起作用,而当我从主菜单启动用户表单时我的复选框不起作用?
【发布时间】:2020-07-01 22:03:25
【问题描述】:

我目前正在使用 VBA 开发一个小项目,因此我创建了一个带有两个复选框的用户窗体,并为这些复选框编写了 2 个子组件,以确保只能选中一个复选框。这是 2 个复选框的代码:

Private Sub CheckBox2_Click()
    If CheckBox2.Value = True And CheckBox3.Value = True Then
        CheckBox3.Value = False
        TextBox8.Enabled = True
        TextBox8.BackColor = RGB(255, 255, 255)
    Else
        CheckBox3.Value = False
        CheckBox2.Value = True    
    End If
End Sub

Private Sub CheckBox3_Click()
    If CheckBox3.Value = True And CheckBox2.Value = True Then
        CheckBox2.Value = False
        TextBox8.Enabled = False
        TextBox8.BackColor = RGB(205, 205, 205)
    Else
        CheckBox2.Value = False
        CheckBox3.Value = True
        TextBox8.Enabled = False
    End If
End Sub

如您所见,考虑到复选框已选中,subs 还启用/禁用 TextBox 字段。

当我尝试使用运行按钮从主菜单启动用户窗体时,此代码完美运行:如果您选中一个复选框,则另一个复选框将被取消选中。

我还在我的 Excel 文件的第一张表上创建了一个启动用户窗体的按钮,因此用户不必激活开发人员的菜单来启动它。这是附加到此按钮的子:

Private Sub lance_interface()
    UF.Show
End Sub

当我单击此按钮时,会出现用户表单,但是一旦选中了一个复选框,就无法选中另一个复选框以取消选中第一个复选框:第一个复选框一直处于选中状态。

我希望能清楚地解释我的问题,提前感谢您的帮助,并对我的英语错误感到抱歉。

【问题讨论】:

  • 用户表单后面还有其他代码吗?加载也许...

标签: excel vba checkbox userform


【解决方案1】:

您需要在用户表单中禁用事件。在您的情况下,可能看起来像这样

Option Explicit
Dim eventOn As Boolean
Private Sub CheckBox2_Click()
    If eventOn Then
        eventOn = False
        If CheckBox2.Value = True And CheckBox3.Value = True Then
            CheckBox3.Value = False
            TextBox8.Enabled = True
            TextBox8.BackColor = RGB(255, 255, 255)
        Else
            CheckBox3.Value = False
            CheckBox2.Value = True
        End If
        eventOn = True
    End If
End Sub

Private Sub CheckBox3_Click()
    If eventOn Then
        eventOn = False
        If CheckBox3.Value = True And CheckBox2.Value = True Then
            CheckBox2.Value = False
            TextBox8.Enabled = False
            TextBox8.BackColor = RGB(205, 205, 205)
        Else
            CheckBox2.Value = False
            CheckBox3.Value = True
            TextBox8.Enabled = False
        End If
        eventOn = True
    End If

End Sub

Private Sub UserForm_Initialize()
    eventOn = True
End Sub

如需进一步阅读,请查看ChipPearson article on Surpress Change in Formsdisabling-events-in-userforms

【讨论】:

    猜你喜欢
    • 2011-02-10
    • 2010-10-30
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多