反向循环但跳过第一个条件?

时间:2017-09-14 15:17:22

标签: vba excel-vba excel

我发现每个分页符,当我找到一个我在列上反向循环但我想跳过我找到的第一个条件。这就是我的意思:

Dim i As Long
Dim pb As Variant
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")

For Each pb In ws.HPageBreaks
    For i = pb.Location.Row To 1 Step -1
        If Cells(i, 1).Value = 1 Then '<<--- HOW TO SKIP THE FIRST "1" I FIND BUT KEEP THE LOOP GOING BACKWARD?
            Dim counter As Long
            counter = counter + 1
            If counter = 1 Then '<<-- certainly not working...
                Exit For
            Else
                'Do Something
            End If
        End If
     Next
Next

enter image description here

编辑:我需要做的就是删除代码退出并运行!

3 个答案:

答案 0 :(得分:0)

如果你想继续循环摆脱Exit For并将你的if语句改为

If counter <> 1 Then
    'Do something
End If

然后你保持完整循环。

答案 1 :(得分:0)

为找到的1s添加一个计数器,并在找到它时递增它。如果计数器> 1,则读取它,否则忽略它。

在我的手机上,稍后会添加一个特定的代码示例。

答案 2 :(得分:0)

如果我理解正确,你只需要更改计数器初始化的位置,然后检查计数器是否大于1.我假设每个分页符都跳过第一个。

Dim i As Long
Dim pb As Variant
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")

For Each pb In ws.HPageBreaks
    Dim counter As Long = 0 ' Move this count outside the internal loop
    For i = pb.Location.Row To 1 Step -1
        If foundFirst AndAlso Cells(i, 1).Value = 1 Then '<<--- HOW TO SKIP THE FIRST "1" I FIND BUT KEEP THE LOOP GOING BACKWARD?
            counter = counter + 1
            'Only do it once your counter is above 1
            If counter <> 1 Then            
                'Do Something
            End If

        End If
     Next
Next