Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate Excel VBA boolean condition (not a formula)

Tags:

excel

vba

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 evaluate this text and put Boolean result (True / False) in another cell B1 using VBA code.

I tried to use Evaluate function, it is not working.

When I read this cell, it always return string type with double quote enclose in both side. Hence it is treated as string and not evaluating the Boolean expression.

"((True And True Or True) And (True And (True))) And (True Or True)"

I want to write this way, but it is not working

If Range("A1").Value = True Then
    Range("B1").Value = True
Else
    Range("B1").Value = False
End If

I tried to store in Boolean variable also

Dim Result as Boolean
Result = CBool(Range("A1").Value) 

as it is string, I am getting type mismatch when I tried to convert using CBool.

like image 267
Ravi Kannan Avatar asked Mar 07 '23 14:03

Ravi Kannan


1 Answers

You could try something like this, taking advantage of the Eval function in Access.

Public Function EvaluateExpression(Value As String) As Boolean
    With CreateObject("Access.Application")
        EvaluateExpression = .Eval(Value)
    End With
End Function

Public Sub T()
    Debug.Print EvaluateExpression("((True And True Or True) And (True And (True))) And (True Or True)")
End Sub

'True
like image 185
Kostas K. Avatar answered Mar 16 '23 12:03

Kostas K.