VBA - 将条件评估为字符串

时间:2013-03-13 21:42:04

标签: vba excel-vba excel

我遇到了一个非常奇怪的场景。在函数中,我将收到一串要评估的条件。

E.g。

(a>b and (b=2 or c!=3))
  

其中a,b和c是我的变量名。

我经常尝试和搜索,但没有任何意义。

所以我的问题是:是否可以评估这样的字符串?如果是的话,请给我一些暗示。

2 个答案:

答案 0 :(得分:2)

替代方法,添加对 Microsoft脚本控件

的引用
Dim vx As MSScriptControl.ScriptControl
Set vx = New MSScriptControl.ScriptControl

a = 100
b = 200
c = 300
Cond = "(a>b and (b=2 or c<>3))"

With vx
    .Language = "VBScript"
    .AddCode "function stub(a,b,c): stub=" & Cond & ": end function"

    result = .Run("stub", a, b, c)
End With

MsgBox result

请注意,您需要使用&lt;&gt;替换!=因为前者在VB *中无效(和/或在jScript中无效)

答案 1 :(得分:1)

这是您问题的正确答案,而不仅仅是评论。

你需要:

  • 在VBIDE中设置对Microsoft Visual Basic for Applications Extensibility x.x(工具/参考)的引用。
  • 信任对VBA项目对象模型的访问(使用Google了解如何为您的Excel版本执行此操作)。
  • 运行initValues(),然后致电getConstantValue("(a>b and (b=2 or c<>3))")

代码:

Option Explicit

Dim a As Long
Dim b As Long
Dim c As Long

Sub initValues()
    a = 3
    b = 2
    c = 4
End Sub

Function getConstantValue(constStr As String) As Variant

    Dim oMod As VBIDE.CodeModule
    Dim i As Long, _
        num As Long

    Set oMod = ThisWorkbook.VBProject.VBComponents("Module1").CodeModule

    For i = 1 To oMod.CountOfLines
        If oMod.Lines(i, 1) = "Function tempGetConstValue() As Variant" Then
            num = i + 1
            Exit For
        End If
    Next i

    oMod.InsertLines num, "tempGetConstValue = " & constStr

    getConstantValue = Application.Run("tempGetConstValue")

    oMod.DeleteLines num

End Function

Function tempGetConstValue() As Variant
End Function