vba在电子表格中选择/取消选中名称为x的所有复选框?

时间:2016-12-17 22:16:04

标签: excel vba checkbox

我正在尝试选择/取消选中名称为' print'的所有复选框。在电子表格中,如果另一个复选框' print1'检查。

我正在创建我的复选框,使用以下代码作为每个循环的一部分。

For Each objFile In objFolder.Files


If DatePart("ww", objFile.DateCreated, vbMonday, vbFirstFourDays) = Range("H7").Value Then


'print file PG
    Cells(i + 13, 1) = Range("T7").Value
    'print file Month
    Cells(i + 13, 5) = Range("H7").Value

    'print file Year
    Cells(i + 13, 9) = Range("B7").Value

    'print file name
    Cells(i + 13, 13) = objFile.Name

    'print file path
    Cells(i + 13, 18) = "=hyperlink(""" & objFile.Path & """)"

     'add action box 1
    ActiveSheet.CheckBoxes.Add(Cells(i + 13, 27).Left, Cells(i + 13, 27).Top, Cells(i + 13, 27).Width, Cells(i + 13, 27).Height).Select

    With Selection
    .Name = "print"
        .Caption = ""
        .Value = xlOff '
        .LinkedCell = Cells(i + 13, 27)
        .Display3DShading = False
            End With

这会创建一个名称为' print'的复选框。按要求。

我还有一个名为' print1'的独特复选框。此复选框有一个分配给它的宏,名为set_print。当用户选中/取消选中此复选框时,宏应该触发,并且应该选中/取消选中名为' print'的所有其他复选框。为此,我使用以下代码:

Sub set_print()
If ActiveSheet.CheckBoxes("print").Value <> xlOn Then
ActiveSheet.CheckBoxes.Value = xlOn
ActiveSheet.Shapes("Search1").TextFrame.Characters.Text = "Print"
Else
ActiveSheet.CheckBoxes("print").Value = xlOff
ActiveSheet.Shapes("Search1").TextFrame.Characters.Text = "Search"
End If
End Sub

出于某种原因,只选中了一个复选框。我不确定我做错了什么,请有人给我看看吗?

1 个答案:

答案 0 :(得分:0)

for each循环更改:

With Selection
    .Name = "print"

为:

With Selection
    .Name = "print" & i

然后按如下方式更改Sub set_print()

Sub set_print()
    With ActiveSheet
        If .CheckBoxes("print1").Value <> xlOn Then
            CheckThem xlOn
            .Shapes("Search1").TextFrame.Characters.Text = "Print"
        Else
            CheckThem xlOff
            .Shapes("Search1").TextFrame.Characters.Text = "Search"
        End If
    End With
End Sub

Sub CheckThem(xlOnOff As Long)
    Dim chkBx As CheckBox

    With ActiveSheet
        For Each chkBx In .CheckBoxes
            If Left(chkBx.Name, 5) = "print" Then chkBx.Value = xlOnOff
        Next
    End With
End Sub