VBA 将条件运算符作为变量传递给 if 语句

VBA to pass a conditional operator as a variable to an if statement

我想执行一个 if 语句,其中条件也是一个变量。类似于:

If Var1 Var2 Var3 Then DoStuff

例如 Var1 = 5,Var2 = ">" 和 Var3 = "2" 你怎么能让 VBA 理解为:

If 5 > 2 Then DoStuff

这是一种间接的方法,使用 Evaluate

Sub test()
Dim x As String, y As String, z As String
x = "5"
y = ">"
z = "2"

If Application.Evaluate("IF(" & x & y & z & ", true, false)") Then
    MsgBox "yes"
Else
    MsgBox "no"
End If
End Sub

编辑:我已经在 Excel VBA 中对此进行了测试。如果您没有使用 Excel VBA,请编辑标签。