循环中的CountA函数

我有以下代码,将checkbox添加到表单名称中带有文字“好处”的工作表中。

我需要在第3行中的checkbox为在第5行中具有文本的每个列。每个工作表将具有不同数量的列。

下面的代码工作,但设置,然后使用columnCount为所有工作表的第一个工作表。

我想我有正确的代码,但它有错误的顺序?

'Checks for the text "Benefits" in the sheetname. 'If true then runs AddCheckBoxesRange Macro to add selection checkboxes for each plan. Sub CheckSheets() Dim sh As Worksheet Application.ScreenUpdating = False For Each sh In ActiveWorkbook.Sheets If LCase$(sh.Name) Like "*benefits*" Then Call AddCheckBoxesRange(sh) Next sh Application.ScreenUpdating = True End Sub 'Macro CheckSheets looks for the text benefits in sheetname, if it exists it calls this macro Sub AddCheckBoxesRange(ws As Worksheet) 'add Form checkboxes Dim c As Range Dim myCBX As CheckBox Dim rngCB As Range Dim strCap As String Dim columnCount As Integer columnCount = WorksheetFunction.CountA(Range("5:5")) + 1 Set rngCB = ws.Range("B3", ws.Cells(3, columnCount)) strCap = "Select Plan" For Each c In rngCB With c Set myCBX = ws.CheckBoxes.Add _ (Top:=.Top, Width:=.Width, _ Height:=.Height, Left:=.Left) End With With myCBX .Name = "cbx_" & c.Address(0, 0) .LinkedCell = c.Offset(37, 0) _ .Address(external:=True) .Caption = strCap End With Next c End Sub 

您只需要限定columnCount,否则它将始终查看ActiveSheet。

更改

columnCount = WorksheetFunction.CountA(Range("5:5")) + 1

columnCount = WorksheetFunction.CountA(ws.Range("5:5")) + 1