动态地将复选框和事件处理程序添加到工作表

时间:2016-09-13 11:23:58

标签: vba dynamic event-handling worksheet

在B栏的表格中,我有组件名称 在A栏中,我希望有一个动态添加的复选框,因为B列中的名称列表会随着时间的推移而增加

我需要能够做到以下几点: - 处理事件(onclick)作为勾选/取消勾选复选框隐藏/取消隐藏另一个工作表中的行 - 当我循环浏览另一个模块中的复选框(从命令框中点击)并根据状态执行操作时,返回每个复选框的状态 - 修改每个复选框的状态,因为我有1个命令框可以勾选所有复选框,1个命令框可以解开所有复选框

到目前为止,我有一个工作原型,但我有两个问题: 1)复选框没有链接到A列中的单元格,它们只是在我创建它们时定位 2)复选框不是动态的,我手动创建它们并且必须为每个复选框写一个事件处理程序(onclick)(> 50个复选框)

我试图创建一个代码来动态添加复选框并创建一个类模块来处理事件,但我真的卡住了.. 我复制并修改了一些最初用于用户表单的代码,并设法使其在用户表单上工作,但我宁愿在工作表上包含所有内容,如上所述。

这是类模块代码(名为:clsBoxEvent)

Option Explicit
Public WithEvents cBox As MSForms.CheckBox

Private Sub cBox_Click()
MsgBox cBox.Name
End Sub

这是我作为模块编写的代码。我计划将它放在一个命令按钮的事件(onclick)中,我打算单击该按钮来更新复选框列表。除非这不是必要的,因为只要B列中的单元格不是空白,就会创建复选框吗?

感谢您的投入。

Dim chkBoxEvent As clsBoxEvent
Dim chkBox As MSForms.CheckBox
Dim chkBoxColl As Collection

Private Sub chkBox_update()
Dim i As Integer
Set chkBoxColl = New Collection

For i = 1 To 5
    ' I wrote the code just to add 5 checkboxes as a test. Later I will need to adapt this to the actual required number of checkboxes (the number of products in column B)  

    Set chkBox = Controls.Add("Forms.CheckBox.1", "ChkBox" & i)
    With chkBox
       ' I work with the position as I did not know how to link it to the cells in colums A
        .Left = 126
        .Height = 16
        .Top = 6 + ((i - 1) * 16)
    End With

Set chkBoxEvent = New clsBoxEvent
Set chkBoxEvent.cBox = Controls(chkBox.Name)
chkBoxColl.Add chkBoxEvent

Next i

End Sub

1 个答案:

答案 0 :(得分:3)

我的回答:Excel VBA script to insert multiple checkboxes linked to cell with yes and no instead of true and false似乎对你有用。

enter image description here

Sub AddCheckBoxes()

    Dim cb As CheckBox
    Dim myRange As Range, cel As Range
    Dim wks As Worksheet

    Set wks = Sheets("Sheet1")

    Set myRange = wks.Range("A1:A1000")

    For Each cel In myRange

        Set cb = wks.CheckBoxes.Add(cel.Left, cel.Top, 30, 6)

        With cb
            .Caption = ""
            .OnAction = "ProcessCheckBox"
        End With

    Next

End Sub

Sub ProcessCheckBox()
    Dim cb As CheckBox
    With Sheets("Sheet1")
        Set cb = .CheckBoxes(Application.Caller)
        If Not cb Is Nothing Then cb.TopLeftCell = IIf(cb.Value = 1, "Cleared", "")
    End With
End Sub