循环中的CountA函数

时间:2017-03-07 22:33:16

标签: excel vba excel-vba

我有以下代码,可以在工作表中添加复选框,并在工作表名称中添加文本“Benefits”。

对于每行中包含文本的第3行,我需要一个复选框。每个工作表都有不同的列数。

下面的代码有效,但设置然后将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

1 个答案:

答案 0 :(得分:1)

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

更改

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

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