Evaluate Excel VBA boolean condition (not a formula)

前端 未结 3 534
孤城傲影
孤城傲影 2021-01-13 17:02

I have text in a cell A1 as below

((True And False Or True) And (True And (Not True))) And (False Or True)

I need to evalu

3条回答
  •  甜味超标
    2021-01-13 17:34

    This is what you can do with VBA .Evaluate:

    Option Explicit
    
    Public Sub TestMe()
    
        Dim cell01  As Range
        Dim cell02  As Range
    
        Set cell01 = Range("A1")
        Set cell02 = Range("A2")
    
        Range("A1") = "1+2+3+4+5"
        Range("A2") = "TRUE and FALSE"
    
        Debug.Print Evaluate(CStr(cell01))
        'Debug.Print CBool(cell02) - this will be an error!
        Debug.Print Evaluate(CBool("True") And CBool("False"))
    
        Debug.Print Evaluate("=AND(TRUE,FALSE)")
        Debug.Print Evaluate("=AND(TRUE,TRUE)")
        Debug.Print Evaluate("=OR(TRUE,TRUE)")
    
    End Sub
    

    If you want to parse the TRUE and FALSE thing (commented in my answer), try to build a formula out of it and to evaluate it.

    E.g., TRUE AND FALSE, should be translated to =AND(TRUE,FALSE). This gets evaluated easily by VBA as it is an Excel Formula. The translation is not a trivial task, but an interesting one.

提交回复
热议问题