为在VBA中创建的复选框设置“移动并使用单元格大小”

时间:2017-02-03 02:16:35

标签: excel vba excel-vba checkbox

我创建了一个电子表格,其中列中有很多复选框。偶尔我会完成一个列,并希望将其隐藏起来。

但是,如果我隐藏列,则不会隐藏该列中的复选框。

如果我手动将复选框属性更改为“移动并使用单元格调整大小”,则可以解决此问题。但正如我所说,有很多复选框,我用宏创建它们。

所以我尝试将以下内容添加到创建宏的vba中: CBX.Placement = xlMoveAndSize

但它没有改变。

有什么想法吗?

这是完整的VBA:

Sub CellCheckboxReview()
Dim myCell As Range
Dim myRng As Range
Dim CBX As CheckBox

With ActiveSheet
    'remove comment if you want to delete all .CheckBoxes.Delete
    Set myRng = .Range(ActiveCell.Offset(19, 0), ActiveCell.Offset(23, 0))
End With

For Each myCell In myRng.Cells
    With myCell
        Set CBX = .Parent.CheckBoxes.Add _
                    (Top:=.Top, _
                     Left:=.Left, _
                     Width:=.Width, _
                     Height:=.Height)
        CBX.Name = "Checkbox_" & .Address(0, 0)
        CBX.Caption = "" 'or what you want
        CBX.Value = xlOff
        CBX.LinkedCell = .Address(external:=True)
        CBX.Placement = xlMoveAndSize
        .NumberFormat = ";;;"
    End With
Next myCell

End Sub

1 个答案:

答案 0 :(得分:1)

选项xlMoveAndSize不适用于单个复选框,甚至不在Excel的GUI中。但是,如果您Group选中了复选框,则可以应用它。

Sub CellCheckboxReview()
    Dim myCell As Range, myRng As Range, CBX As CheckBox
    Set myRng = ActiveSheet.Range(ActiveCell.Offset(19, 0), ActiveCell.Offset(23, 0))

    Dim ar(1 To 5) As String ' <-- an array to be used to group the checkboxes
    Dim i As Long: i = 1
    For Each myCell In myRng.Cells
        With myCell
            Set CBX = .Parent.CheckBoxes.Add _
                        (Top:=.Top, _
                         Left:=.Left, _
                         Width:=.Width, _
                         Height:=.Height)
            CBX.Name = "Checkbox_" & .Address(0, 0)
            CBX.Caption = "" 'or what you want
            CBX.value = xlOff
            CBX.LinkedCell = .Address(external:=True)
            'CBX.Placement = xlMoveAndSize  ' <-- this has no effect for an individual checkbox
            .NumberFormat = ";;;"
            ar(i) = CBX.Name ' <-- add the shape's name to the array, for grouping later 
            i = i + 1
        End With
    Next myCell

    ' now group the checkboxes then set the desired placement
    With ActiveSheet.Shapes.Range(ar)
        .Group
        .Item(1).Placement = xlMoveAndSize
    End With
 End Sub