我在这里(https://ccm.net/faq/37428-excel-vba-how-to-create-multiple-checkboxes)找到了一个宏,该宏将在选定范围内创建复选框-很好-但现在我想做相反的事情,即删除指定范围内的复选框。
这是创建复选框的代码:
Sub Insert_chkbx_Link_Cell()
Dim rngCel As Range
Dim ChkBx As CheckBox
For Each rngCel In Selection
With rngCel.MergeArea.Cells
If .Resize(1, 1).Address = rngCel.Address Then
Set ChkBx = ActiveSheet.CheckBoxes.Add(.Left, .Top, .Width, .Height)
With ChkBx
.Value = xlOff
.LinkedCell = rngCel.MergeArea.Cells.Address
With .Border
End With
End With
End If
End With
Next rngCel
End Sub
这里是一个子项,它将“取消链接/取消分配”单元格中的复选框:
Sub Un_Assign()
For Each sht In ActiveWorkbook.Sheets
For Each CheckBox In sht.CheckBoxes
CheckBox.OnAction = ""
Next CheckBox
Next sht
End Sub
此问题是它不会在指定范围内执行此操作,而是会在每个工作表上执行该操作。
因此,我将创建复选框的宏更改为删除它们的宏:
Sub Remove_chkbx_Unlink_Cell()
Dim rngCel As Range
Dim ChkBx As CheckBox
For Each rngCel In Selection
With rngCel.MergeArea.Cells
If .Resize(1, 1).Address = rngCel.Address Then
ActiveSheet.CheckBoxes.Delete
End If
End With
Next rngCel
End Sub
同样,这很好用,但是会删除工作表上的每个复选框。
因此,我在for each
语句中添加了一个if
循环,并尝试指定一个范围:
Sub Remove_chkbx_Unlink_Cell()
Dim rngCel As Range
Dim ChkBx As CheckBox
For Each rngCel In Selection
With rngCel.MergeArea.Cells
If .Resize(1, 1).Address = rngCel.Address Then
For Each ChkBx In rngCel
CheckBox.OnAction = ""
Next ChkBx
rngCel.CheckBoxes.Delete
End If
End With
Next rngCel
End Sub
问题是我在For Each ChkBx In rngCel
行上出错:
类型不匹配
编辑
下图中有6个复选框,前三个被选中,后三个未被选中。是否可以通过选择链接到的单元格来删除未选中的框?
下面,我选择了空复选框的单元格,并且与“创建”复选框的方式大致相同,我想删除它们:即,选择一个单元格区域并删除该范围内的复选框
答案 0 :(得分:2)
要删除特定范围内的复选框,您可以循环浏览工作表中的所有复选框,并在它们的.TopLeftCell
与目标范围相交(Application.Intersect Method)时将其删除。
Option Explicit
Public Sub TestDeleteCheckBoxes()
'delete all CheckBoxes in A1:A10 in Sheet1
DeleteCheckBoxes ThisWorkbook.Worksheets("Sheet1").Range("A1:A10")
End Sub
Public Sub DeleteCheckBoxes(Target As Range)
Dim Cbx As CheckBox
For Each Cbx In Target.Parent.CheckBoxes 'loop through all CheckBoxes on the worksheet
If Not Intersect(Cbx.TopLeftCell, Target) Is Nothing Then
Cbx.Delete 'delete it if it intersects with the target range
End If
Next Cbx
End Sub
请注意,我将其包装到一个过程中,以便您可以在任何目标范围内重复使用该代码。