Nice programing

For 루프 계속

nicepro 2020. 12. 26. 16:36
반응형

For 루프 계속


다음 코드가 있습니다.

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

    sname = arr(x)  
    If instr(sname, "Configuration item") Then  
        '**(here i want to go to next x in loop and not complete the code below)**  

    '// other code to copy past and do various stuff

Next x  

그래서 나는 단순히 서술문을 가질 수 있다고 생각 Then Next x했지만 이것은 "no for 서술문 선언"오류를 준다.

그렇다면 If instr(sname, "Configuration item") Thenx의 다음 값으로 진행하기 위해 뒤에 무엇을 넣을 수 있습니까?


Java 또는 Pythoncontinue 과 같은 명령문을 생각하고 있지만 VBA에는 그러한 기본 명령문이 없으며 VBA와 같은 명령문을 사용할 수 없습니다 .Next

GoTo대신 명령문을 사용하여 수행하려는 작업과 같은 것을 얻을 수 있지만 실제로 GoTo는 대안이 고 안되고 비실용적 인 경우에 대비해야합니다.

단일 "계속"조건이있는 경우에는 정말 간단하고 깨끗하며 읽기 쉬운 대안이 있습니다.

    If Not InStr(sname, "Configuration item") Then
        '// other code to copy paste and do various stuff
    End If

다음을 사용할 수 있습니다 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

몇 년 후 ... 나는 이것을 좋아합니다.

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

    sname = arr(x)  
    If instr(sname, "Configuration item") Then Exit Do 

    '// other code to copy past and do various stuff

Loop While False: Next x

For i=1 To 10
    Do 
        'Do everything in here and

        If I_Dont_Want_Finish_This_Loop Then
            Exit Do
        End If 

        'Of course, if I do want to finish it,
        'I put more stuff here, and then...

    Loop While False 'quit after one loop
Next i

몇 년 늦었지만 여기에 또 다른 대안이 있습니다.

For x = LBound(arr) To UBound(arr)
    sname = arr(x)  
    If InStr(sname, "Configuration item") Then  
        'Do nothing here, which automatically go to the next iteration
    Else
        'Code to perform the required action
    End If
Next x

부울을 사용하여 해결할 수도 있습니다.

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

예를 들어, 다음은 전체 예입니다.
(1) 워크 시트에서 사용 된 셀 범위를 식별합니다.
(2) 각 열을 반복합니다.
(3) 열 제목이 허용되는 제목 인 경우, 열의 모든 셀을 반복합니다.

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

참고 : 즉시 잡지 않았다면 선 If docol Then이 반전 된 CONTINUE입니다. 즉, doColFalse로 유지되면 스크립트가 다음 셀로 계속 진행되고 아무 작업도 수행하지 않습니다.

당연한 말 continue이나 next for진술 만큼 빠르거나 효율적이지는 않지만 최종 결과는 내가 얻을 수있는 것만 큼 가깝습니다.


때때로 이중 do 루프를 수행합니다.

Do

    Do

        If I_Don't_Want_to_Finish_This_Loop Then Exit Do

        Exit Do

    Loop

Loop Until Done

이렇게하면 "고토 스파게티"를 피할 수 있습니다.

ReferenceURL : https://stackoverflow.com/questions/5895908/continue-for-loop

반응형