使用 Word VBA,如何在不必复制整个循环的情况下更改循环的条件?
Using Word VBA, How to change the condition of a loop without having to replicate the whole loop?
我想调用一个带参数的例程,用作循环的条件。
下面的代码不起作用,它给出错误 13(不兼容的类型)。我该如何解决?非常感谢!
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
Word 没有 Excel 的 Evaluate
的等价物,因此只有 "long way around" 才有可能。您需要找出要通过评估的每个变体,对其进行测试,然后 运行 正确的循环类型。在我看来你需要做这样的事情,无论如何,因为使用你在你的例子中的测试不会循环“<”(假设你使用正整数)。
为了避免在循环中重复要执行的代码,请将其放在单独的函数中。
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
我想调用一个带参数的例程,用作循环的条件。 下面的代码不起作用,它给出错误 13(不兼容的类型)。我该如何解决?非常感谢!
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
Word 没有 Excel 的 Evaluate
的等价物,因此只有 "long way around" 才有可能。您需要找出要通过评估的每个变体,对其进行测试,然后 运行 正确的循环类型。在我看来你需要做这样的事情,无论如何,因为使用你在你的例子中的测试不会循环“<”(假设你使用正整数)。
为了避免在循环中重复要执行的代码,请将其放在单独的函数中。
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