Continue For loop

前端 未结 8 1581
面向向阳花
面向向阳花 2020-11-27 05:29

I have the following code

For x = LBound(arr) To UBound(arr)

    sname = arr(x)  
    If instr(sname, \"Configuration item\") Then  
        \'**(here i wa         


        
相关标签:
8条回答
  • 2020-11-27 06:29

    This can also be solved using a boolean.

    For Each rngCol In rngAll.Columns
        doCol = False '<==== Resets to False at top of each column
        For Each cell In Selection
            If cell.row = 1 Then
                If thisColumnShouldBeProcessed Then doCol = True
            End If
            If doCol Then
                'Do what you want to do to each cell in this column
            End If
        Next cell
    Next rngCol
    

    For example, here is the full example that:
    (1) Identifies range of used cells on worksheet
    (2) Loops through each column
    (3) IF column title is an accepted title, Loops through all cells in the column

    Sub HowToSkipForLoopIfConditionNotMet()
        Dim rngCol, rngAll, cell As Range, cnt As Long, doCol, cellValType As Boolean
        Set rngAll = Range("A1").CurrentRegion
        'MsgBox R.Address(0, 0), , "All data"
        cnt = 0
        For Each rngCol In rngAll.Columns
            rngCol.Select
            doCol = False
            For Each cell In Selection
                If cell.row = 1 Then
                    If cell.Value = "AnAllowedColumnTitle" Then doCol = True
                End If
                If doCol Then '<============== THIS LINE ==========
                    cnt = cnt + 1
                    Debug.Print ("[" & cell.Value & "]" & " / " & cell.Address & " / " & cell.Column & " / " & cell.row)
                    If cnt > 5 Then End '<=== NOT NEEDED. Just prevents too much demo output.
                End If
            Next cell
        Next rngCol
    End Sub
    

    Note: If you didn't immediately catch it, the line If docol Then is your inverted CONTINUE. That is, if doCol remains False, the script CONTINUES to the next cell and doesn't do anything.

    Certainly not as fast/efficient as a proper continue or next for statement, but the end result is as close as I've been able to get.

    0 讨论(0)
  • 2020-11-27 06:32

    You can use a GoTo:

    Do
    
        '... do stuff your loop will be doing
    
        ' skip to the end of the loop if necessary:
        If <condition-to-go-to-next-iteration> Then GoTo ContinueLoop 
    
        '... do other stuff if the condition is not met
    
    ContinueLoop:
    Loop
    
    0 讨论(0)
提交回复
热议问题