【问题标题】:Use checkbox dynamically added to userform使用复选框动态添加到用户窗体
【发布时间】:2018-03-28 08:11:35
【问题描述】:

我使用此代码将CheckBox1 添加到我的UserForm

Private Sub UserForm_Initialize()
    Dim opt As Variant
    Set opt = UserForm1.Controls.Add("Forms.checkbox.1", "CheckBox1", True)
End Sub

现在当我点击CommandButton 时,我想检查CheckBox1 是否被选中:

Private Sub CommandButton1_Click()
    If CheckBox1.Value = False Then
        MsgBox "F"
    End If
End Sub

但是这段代码不起作用;我认为是因为复选框是动态添加的。
这只是解决问题的代码的简化。

【问题讨论】:

  • 您也可以将 opt 创建为 Module 变量而不是 Sub 变量?把Private opt As Control放在你的Option Explicit之后,去掉Dim opt As Variant,然后你可以使用If Not opt.Value Then MsgBox "F"

标签: excel vba outlook


【解决方案1】:

这就是你的想法:

Option Explicit

Private Sub UserForm_Initialize()
    Dim opt As Variant
    Set opt = Me.Controls.Add("Forms.checkbox.1", "CheckBox1", True)
End Sub

Private Sub CommandButton1_Click()
    If Not Me.Controls("CheckBox1") Then
        MsgBox "F"
    End If
End Sub

但是,根据您的经验和编写更好代码的愿望,您可能决定在使用表单时遵循一些 MVC 模式。阅读这些以获得更多关于它的想法:

【讨论】:

    【解决方案2】:

    需要如下

    Private Sub CommandButton1_Click()
    If Me.Controls("Checkbox1").Value = False Then
    MsgBox "F"
    End If
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      • 2019-12-04
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      相关资源
      最近更新 更多