VBA - 具有多个条件级别的循环

时间:2014-01-30 20:19:53

标签: vba loops

我正在尝试创建一个测试多个条件级别的循环,以及未能进入下一个项目的测试,以及那些通过的循环进入下一级别测试。怎么会这样?特别是它:

ITEM: test condition 1

Is condition 1 met?
    no: next ITEM
    yes: test condition 2

Is condition 2 met?
    no: next ITEM
    yes: test condition 3

Is condition 3 met?
    no: next ITEM
    yes: run block of code, next item

以下是它的说明

enter image description here

提前感谢您的帮助

2 个答案:

答案 0 :(得分:3)

有多种方法可以解决这个问题 - 我建议使用下面列出的最后一个选项:

经典的方式就是这样:

Sub ClassicalVersion()

    For Each x In YourCollectionY  'or use For i = LBound(array) to Ubound(array)
        If Condition1 Then
            If Condition2 Then
                If Condition3 Then
                    'Your code here
                End If
            End If
        End If
    Next

End Sub

这有时被称为箭头反模式,应该避免imo,因为它使代码难以阅读。

相反,您可以使用GoTo声明:

Sub GoToVersion()

    For Each x In YourCollectionY  'or use For i = LBound(array) to Ubound(array)
        If Not Condition1 Then GoTo NextElement
        If Not Condition2 Then GoTo NextElement
        If Not Condition3 Then GoTo NextElement

        'Your code here
NextElement:
    Next

End Sub

很多人都鄙视使用GoTo,但是这对你的问题来说是一个可行的解决方案,并且对于经典版本已经更好了。

然而,最好的方法是使用子例程和Exit Sub语句将循环与您的条件分开(并根据单一责任原则,甚至可能是条件检查中的代码):

Sub SRPVersion()
    For Each x In YourCollectionY  'or use For i = LBound(array) to Ubound(array)
        If RunChecks Then
            CallToSubWithYourCode
        End If
    Next

End Sub

Function RunChecks(x as ...) as Boolean
    If Not Condition1 Then Exit Function
    If Not Condition2 Then Exit Function
    If Not Condition3 Then Exit Function
    RunChecks = True
End Function

答案 1 :(得分:1)

您可以使用Do循环执行此操作:

Do While True
  If Not condition1 Then Exit Do
  If Not condition2 Then Exit Do
  If Not condition3 Then Exit Do
  Call code
  Exit Do
Loop

或者,如果你这样做,同时循环一堆项目:

For Each Thing in bunchOfItems

  If Not condition1 Then GoTo nextItem
  If Not condition2 Then GoTo nextItem
  If Not condition3 Then GoTo nextItem

  Call code

nextItem:

Next Thing

大多数语言都有一个continue语句来短接For循环的其余部分。不幸的是,VBA没有。