【问题标题】:VBA to pass a conditional operator as a variable to an if statementVBA将条件运算符作为变量传递给if语句
【发布时间】:2015-10-06 10:40:59
【问题描述】:

我想执行条件也是变量的 if 语句。类似:

If Var1 Var2 Var3 Then DoStuff

例如 Var1 = 5、Var2 = ">" 和 Var3 = "2" 如何让 VBA 将其理解为:

If 5 > 2 Then DoStuff

【问题讨论】:

  • 你不能直接用 VBA 来做,你必须以某种方式抽象它。您能否列出条件变量 (Var2) 的所有可能选择?

标签: vba variables if-statement conditional


【解决方案1】:

这是一种间接的方法,使用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,请编辑标签。

【讨论】:

  • 如果在 Microsoft Access 中使用 VBA,Evaluate() 不可用。看起来充满希望的函数Eval() 不一样(但也许值得一试)。
猜你喜欢
  • 2018-04-27
  • 2015-08-08
  • 2011-08-31
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
  • 2011-02-18
  • 2013-10-17
  • 1970-01-01
相关资源
最近更新 更多