通过vba宏将复选框插入特定单元格

时间:2013-06-07 20:10:10

标签: excel-vba vba excel

我想通过宏在特定单元格中插入复选框。请告知如何去做。

例如:点击命令按钮我应该可以将复选框添加到“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 

谢谢你, 普拉香特

3 个答案:

答案 0 :(得分:5)

这个简单的行允许您将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

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

答案 1 :(得分: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

希望这有帮助。

答案 2 :(得分: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