Excel VBA For Loop Error

时间:2012-07-04 08:30:26

标签: vba excel-vba excel

我正在尝试运行一个简单的For循环,它将被扩展为包含更多功能,但是因为它不断抛出错误“无效的下一个控制变量引用”而遇到麻烦。我试图使用的代码如下所示。

Sub Tickbox()

Set Location = Sheets("TickBoxSheet").Range("B:B")

i = WorksheetFunction.CountA(Location)

Sheets("TickBoxSheet").Range("B2").Select


For a = 1 To i
    If Selection.Value = "True" Then
        Row = Selection.Row
        'Hide some rows in another sheet via if statements

        ActiveCell.Offset(1, 0).Select
    End If
Next i

End Sub

我不知道今天早上是否需要更多咖啡,但我似乎无法弄清楚到底是怎么回事。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:8)

递增变量(在Next中)应该是索引变量,即:

For a = 1 To i
  '...
Next a

i在索引中如此受欢迎,在其他情境中使用它之前应该三思而后行。

答案 1 :(得分:5)

你已经从llmo得到了答案。然而,我想强调的其他一些事情......

尝试避免.Select。它会降低你的代码速度。

同样没有必要 WorksheetFunction.CountA(Location)会给你最后一行,因为你想循环遍历所有拥有数据的行。我建议这个

Sub Tickbox()
    Dim i As Long, a As Long, Rw As Long

    With Sheets("TickBoxSheet")
        i = .Range("B" & .Rows.Count).End(xlUp).row

        For a = 2 To i
            If .Range("B" & a).Value = "True" Then
                Rw = a
                'Hide some rows in another sheet via if statements
            End If
        Next a
    End With
End Sub

您也可以使用自动过滤器更快地进行操作,以便循环只有True的单元格。例如

Sub Tickbox()
    Dim i As Long, a As Long, Rw As Long
    Dim Location As Range, acell As Range

    With Sheets("TickBoxSheet")
        '~~> Remove any filters
        .AutoFilterMode = False

        i = .Range("B" & .Rows.Count).End(xlUp).row

        With .Range("B1:B" & i)
            .AutoFilter Field:=1, Criteria1:="True"
            Set Location = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
            Debug.Print Location.Address
        End With

        '~~> Remove any filters
        .AutoFilterMode = False

        For Each acell In Location
            If acell.Value = "TRUE" Then
                Rw = acell.row
                'Hide some rows in another sheet via if statements
            End If
        Next acell
    End With
End Sub