Continuar Para bucle


Tengo el siguiente código

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  

Así que pensé que podría simplemente tener la declaración Then Next x, pero esto da un error de "no para declaración declarada".

Entonces, ¿qué puedo poner después de If instr(sname, "Configuration item") Then para que proceda al siguiente valor de x?

Author: Jean-François Corbett, 2011-05-05

7 answers

Estás pensando en una instrucción continue como de Java o de Python, pero VBA no tiene tal instrucción nativa, y no puedes usar la Next de VBA así.

Podría lograr algo como lo que está tratando de hacer usando una declaración GoTo en su lugar, pero en realidad, GoTo debería reservarse para casos donde las alternativas son artificiales e imprácticas.

En su caso con una sola condición de "continuar", hay una muy simple, limpio y legible alternativa:

    If Not InStr(sname, "Configuration item") Then
        '// other code to copy paste and do various stuff
    End If
 36
Author: Jean-François Corbett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-18 08:24:06

Puedes usar un 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
 73
Author: VBA hack,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-14 09:26:39

Muchos años después... Me gusta este:

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
 16
Author: Alfredo Yong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-22 16:40:43
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
 11
Author: Arlen Beiler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-19 20:39:24

Algunos años tarde, pero aquí hay otra alternativa.

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
 5
Author: moongster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-09 07:10:41

A veces hago un bucle do doble:

Do

    Do

        If I_Don't_Want_to_Finish_This_Loop Then Exit Do

        Exit Do

    Loop

Loop Until Done

Esto evita tener "goto spaghetti"

 0
Author: Rand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-29 18:08:57

Esto también se puede resolver usando un booleano.

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

Por ejemplo, aquí está el ejemplo completo que:
(1) Identifica el rango de celdas usadas en la hoja de trabajo
(2) Bucles a través de cada columna
(3) SI el título de la columna es un título aceptado, recorre todas las celdas de la columna

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

Nota: Si no lo cogiste inmediatamente, la línea If docol Then es tu CONTINUACIÓN invertida. Es decir, si doCol sigue siendo False, el script CONTINÚA a la siguiente celda y no lo hace nada.

Ciertamente no tan rápido/eficiente como una instrucción continue o next for adecuada, pero el resultado final es lo más cercano que he podido obtener.

 0
Author: gibberish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-20 02:43:09