Excel VBA代码,当单元格不为空时设置checkbox

我是新来的(在VBA初学者)。 我试图修改这个代码来设置checkbox只在Range(“B21:B40”)中的单元格不为空。

代码没有准备好。 我不知道如何build立两个工作循环每个工作将检查内容范围(“B21:B25”)和下一个范围(“A21:A25”)将设置checkbox

Sub ActiveCheckBox() Dim setRange As Range, cel As Range Dim checkRange As Range, cel1 As Range Dim wks As Worksheet Dim cb As Checkbox Set wks = Sheets("InterFace") Set setRange = wks.Range("A21:A25") Set checkRange = wks.Range("B21:B25") For Each cel1 In checkRange If cel1 <> "" Then For Each setRange In checkRange Set cb = cel.Worksheet.CheckBoxes.Add(cel.Left + cel.Width / 2 - 8.25, _ cel.Top + cel.Height / 2 - 8.25, 0, 0) ' 8.25 is cb.Height / 2 With cb .Text = vbNullString ' to clear Caption .LinkedCell = cel.Address(0, 0) ' Example A1 instead of $A$1 .Name = "cb" & cb.LinkedCell ' optional End With Next End If Next setRange.NumberFormat = ";;;" ' optional to hide the cell values End Sub 

build立,我用这个主题的脚本脚本插入一个checkbox到每个单元格,并将其分配给Excel中的单元格请让我知道我做错了什么。

@戈登感谢您的帮助!

下面我张贴工作代码。 另外我补充说:macros运行时,工作表变化,并删除checkbox之前把新的。

 Private Sub Worksheet_Change(ByVal Target As Range) Dim setRange As Range, cel As Range Dim checkRange As Range, cel1 As Range Dim wks As Worksheet Dim cb As Checkbox Set wks = Sheets("InterFace") Set setRange = wks.Range("A18:A30") Set checkRange = wks.Range("A18:A30") For Each cb In ActiveSheet.CheckBoxes cb.Delete Next For Each cel In setRange If cel.Offset(0, 1) <> "" Then Set cb = cel.Worksheet.CheckBoxes.Add(cel.Left + cel.Width / 2 - 8.25, _ cel.Top + cel.Height / 2 - 8.25, 0, 0) ' 8.25 is cb.Height / 2 With cb .Text = vbNullString ' to clear Caption .LinkedCell = cel.Address(0, 0) ' Example A1 instead of $A$1 .Name = "cb" & cb.LinkedCell ' optional End With End If Next End Sub