Search code examples
vbams-worddo-loops

Using Word VBA, How to change the condition of a loop without having to replicate the whole loop?


I want to call a routine with arguments to be used as the condition of a loop. The code that follows doesn't works, it gives the ERROR 13 (incompatible types). How do I fix this? Many thanks!

Sub foo()
   Call bar("a>10")
End Sub

Sub bar(myCondition as String)
   Dim a as Integer
   Do
      Debug.Print a
      a=a+1
   Loop Until myCondition
End Sub

Solution

  • Word has no equivalent to Excel's Evaluate so this is only possible the "long way around". You need to figure out every variation you want to pass for evaluation, test for which it is, and then run the correct type of loop. Seems to me you'd need to do something like this, anyway, since using the test you have in your example wouldn't loop for "<" (assuming you use positive integers).

    In order to avoid repeating the code you want to execute in the loop, put that in a separate function.

    Sub foo()
       Call bar(">", 10)
    End Sub
    
    Sub bar(ByVal conditionOperator As String, ByVal conditionValue As Long)
       Dim a As Long
       Select Case conditionOperator
        Case Is = "<"
            Do
             a = PerformLoop(a)
            Loop While a < conditionValue
        Case Is = ">"
            Do
             a = PerformLoop(a)
            Loop Until a > conditionValue
        Case Is = "="
            Do
             a = PerformLoop(a)
            Loop Until a = conditionValue
        Case Is = ">="
            Do
             a = PerformLoop(a)
            Loop Until a >= conditionValue
        Case Is = "<="
            Do
             a = PerformLoop(a)
            Loop While a < conditionValue
       End Select
    End Sub
    
    Function PerformLoop(a As Long) As Long
          Debug.Print a
          a = a + 1
          PerformLoop = a
    End Function