3

我想通过宏在特定单元格中插入复选框。例如:单击命令按钮时,我应该能够将复选框添加到A1单元格。

Sheets("Pipeline Products").Range("O" & i & ":AG" & i).Select 
ActiveSheet.CheckBoxes.Add(4, 14.5, 72, 17.25).Select 

With Selection 
    .Caption = "" 
    .Value = xlOff '
    .LinkedCell = "C" & ToRow     
    .Display3DShading = False 
End With 
4

3 回答 3

9

这条简单的线允许您将 CheckBox 添加到单元格 A1 并相应地设置宽度和高度:

ActiveSheet.OLEObjects.Add "Forms.CheckBox.1", Left:=Range("A1").Left, Top:=Range("A1").Top, Width:=Range("A1").Width, Height:=Range("A1").Height

您可以通过这种方式轻松地将其添加到 CommandButton:

Private Sub CommandButton1_Click()

    ActiveSheet.OLEObjects.Add "Forms.CheckBox.1", Left:=Range("A1").Left, Top:=Range("A1").Top, Width:=Range("A1").Width, Height:=Range("A1").Height

End Sub

编辑您的代码改进...

您只需添加循环即可将复选框插入多个单元格:

Sub YourCode_Improvment()

    Dim i
    '
    For i = 1 To 10 'cells from 1st to 10th

    ActiveSheet.CheckBoxes.Add(Cells(i, "A").Left, _
                                Cells(i, "A").Top, _
                                72, 17.25).Select
    With Selection
        .Caption = ""
        .Value = xlOff '
        .LinkedCell = "C" & i
        .Display3DShading = False
    End With
    Next
End Sub

如果需要,相应地更改此代码。

于 2013-06-07T20:25:45.683 回答
0

您可以使用 For Each 循环来添加复选框。

Dim i as Integer
Dim cel As Range
i = 10
For Each cel In Sheets("Pipeline Products").Range("O" & i & ":AG" & i)
    ActiveSheet.OLEObjects.Add "Forms.CheckBox.1", Left:=cel.Left, Top:=cel.Top, Width:=cel.Width, Height:=cel.Height
Next

希望这可以帮助。

于 2013-06-07T21:20:09.987 回答
0

顶部评论中的代码略有升级。只需选择一个范围并运行它,它将用复选框填充所有选定的单元格:

Sub InsertCheckboxes()
    Dim c As Range

    For Each c In Selection
        Dim cb As CheckBox
        Set cb = ActiveSheet.CheckBoxes.Add(c.Left, _
                                    c.Top, _
                                    c.Width, _
                                    c.Height)
        With cb
            .Caption = ""
            .Value = xlOff
            .LinkedCell = c.Address
            .Display3DShading = False
        End With
    Next
End Sub
于 2020-03-06T13:54:02.497 回答