【问题标题】:How to add a select all check boxes option to a UserForm in Excel VBA如何在 Excel VBA 中向用户窗体添加全选复选框选项
【发布时间】:2020-11-12 09:32:39
【问题描述】:

所以我有这个代码

Dim LastRow     As Long

Private Sub Remove_Files_Button_Click()


On Error GoTo Error:
Dim i As Long
For i = 1 To LastRow
    If Me.Controls("CheckBox_" & i) Then
        Range("G" & i).Value = Range("A" & i).Value
    End If
    If Me.Controls("CheckBox_" & i) Then
        Range("H" & i).Value = Range("B" & i).Value
    End If
    If Me.Controls("CheckBox_" & i) Then
        Range("I" & i).Value = Range("C" & i).Value
    End If
Next i
    Range("A:F").Select
    Selection.Delete Shift:=xlToLeft
    Range("A:B").Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlNo
Error:
    Unload Me
End Sub


Sub UserForm_Initialize()

Dim i           As Long
Dim chkBox      As MSForms.CheckBox

On Error GoTo Error:
LastRow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

For i = 1 To LastRow
    Set chkBox = Me.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i)
    chkBox.Height = 30
    chkBox.Caption = Worksheets("Sheet1").Cells(i, 1).Value
    chkBox.Left = ((i - 1) Mod 4) * 100 + 5
    chkBox.Top = 5 + Fix((i - 1) / 4) * 30
Next i
Error:
End Sub

采用 VBA 形式。当我运行它时,我会生成这个弹出窗口 enter image description here

我想要做的,甚至无法弄清楚如何去做是有第二个按钮,如果点击它会自动选中所有复选框。任何帮助,将不胜感激。 谢谢

【问题讨论】:

    标签: excel vba checkbox


    【解决方案1】:

    遍历控件并检查控件的名称。如果like "checkbox*" then Value = True

    Private Sub CommandButton1_Click()
        Dim ctl As Control
        For Each ctl In Me.Controls
            If ctl.Name Like "CheckBox*" Then
                ctl.Value = True
            End If
        Next ctl
    End Sub
    

    如果您需要改回该值,您可以制作另一个按钮并将 ctl.Value = True 更改为 ctl.Value = False

    Private Sub CommandButton2_Click()
        Dim ctl As Control
        For Each ctl In Me.Controls
            If ctl.Name Like "CheckBox*" Then
                ctl.Value = False
            End If
        Next ctl
    End Sub
    

    或者添加另一个 if 语句来反转值,但如果他们检查某些内容,它将取消选中并且它们不会全部相等。

    Private Sub CommandButton1_Click()
        Dim ctl As Control
        For Each ctl In Me.Controls
            If ctl.Name Like "CheckBox*" Then
                If ctl.Value = False Then
                    ctl.Value = True
                Else
                    ctl.Value = False
                End If
            End If
        Next ctl
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2020-10-09
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      相关资源
      最近更新 更多