vba 使用 GoTo 后返回循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9555522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 15:26:35  来源:igfitidea点击:

returning back to loop after using GoTo

vba

提问by jiri jansa

I have tried several methods but didn′t manage to succeed. My problem is - running loop1, if some condition is fulfilled, run loop2 until some condition is fulfilled, return back to loop1.

我尝试了几种方法,但都没有成功。我的问题是 - 运行 loop1,如果满足某个条件,则运行 loop2,直到满足某个条件,然后返回到 loop1。

sub program()
Dim i As Integer
Dim q As Integer

For i=1 to 350
If Range("A"&i).value=1 And Range("D"&i).Value<15 Then Goto 1
Next i

1:q=0
  Do While List1.Range("A"&i+q).Value<>""
  Range("E"&i+q)="K"
  q=q+1
  Loop

End Sub

I haven't found the way how to return after executing "1 loop" back to "For Next Loop" and continue for next i. Maybe it is not possible and I have to include somehow code inside the first loop ?! thank you

我还没有找到在执行“1 个循环”后如何返回到“For Next Loop”并继续下一个 i 的方法。也许这是不可能的,我必须在第一个循环中以某种方式包含代码?!谢谢你

回答by

Make the code at 1into a function and call that instead of using goto. When the function exits, your first loop will continue executing from where it left off.

将代码 at1变成一个函数并调用它而不是使用 goto。当函数退出时,您的第一个循环将从它停止的地方继续执行。

回答by James Youngman

I don't actually know VBA (I last used VB in about 1996) but this should be more or less right:

我实际上并不了解 VBA(我上次使用 VB 是在 1996 年左右),但这应该或多或少是正确的:

sub program()
Dim i As Integer
Dim q As Integer

i = 1
Do while i <= 350
  If Range("A"&i).value=1 And Range("D"&i).Value<15 Then
    Do While i <= 350 And List1.Range("A"&i).Value<>""
      Range("E"&i)="K"
      i=i+1
    Loop
  Else
      i=i+1
  End If
Loop
end do
End Sub

回答by FCastro

Usage of GoTo is discouraged even by MSDN (you should use it only for error treatment paired with Resume), but since you asked, this is the approach:

即使 MSDN 也不鼓励使用 GoTo(您应该仅将它用于与 Resume 配对的错误处理),但既然您问了,这就是方法:

Sub program()
    Dim i As Integer
    Dim q As Integer

    For i=1 to 350
        If ((Range("A"&i).value=1) And (Range("D"&i).Value<15)) Then Goto OtherLoop
FirstLoop:
    Next i

Exit Sub

OtherLoop:
   q=0
   Do While List1.Range("A"&i+q).Value<>""
       Range("E"&i+q)="K"
       q=q+1
   Loop
   Goto FirstLoop

End Sub

You need the Exit statement to keep your code from entering "OtherLoop" when it finishes "FirstLoop", and also need to tell it to go back to where you previously were. Again, avoid using this stuff. Loops within loops (indentto organize, please) and secondary procedure calls (calling another sub or function) are far more recommended.

您需要 Exit 语句来防止您的代码在完成“FirstLoop”时进入“OtherLoop”,并且还需要告诉它返回到您之前所在的位置。再次,避免使用这些东西。更推荐循环内的循环(请缩进组织)和辅助过程调用(调用另一个子或函数)。