Name

Eval Function

Syntax

[result = ]Eval(expression)
result

Use: Optional

Data Type: Any

A variable to hold the result of the Eval function.

expression

Use: Required

Data Type: String

The expression to be evaluated.

Return Value

Any

Description

Evaluates an expression and returns the results.

Rules at a Glance

  • Eval follows the rules of precedence in evaluating expression.

  • If an equals sign (=) occurs in expression, it is interpreted as a comparison operator rather than as an assignment operator. In this case, Eval returns True if the parts of expression are equal and False if they are not.

Example

In this example, the first result will always evaluate to False, since the variables are not equal, and the second will always evaluate to True, since Test1 is in fact less than Test2:

Dim Test1, Test2, Result

Test1 = 4
Test2 = 5
Result = Eval("Test1 = Test2")
MsgBox Result
Result = Eval("Test1 < Test2")
MsgBox Result
Result = Eval("Test1 / Test2")
MsgBox Result
Result = Eval("Test1 - Test2")
MsgBox Result

Programming Tips and Gotchas

You may wonder why you’d want to bother with Eval when you can do the same thing without it. For example:

   lVar1 = 2
   lVar2 = 3
   lResult = lVar1 + lVar2

is the same as:

   lVar1 = 2
   lVar2 = 3
   lResult = Eval(lVar1 + lVar2)

But the significance of Eval is that it evaluates expressions stored to strings. For example, the code:

   Dim sExp, result, a, b, c
   
   a = 10
   b = 20
   c = 30
   
   sExp = "a + b + c"
 
   result = eval(sExp)

returns 60. This means that you can build expressions and assign them to strings ...

Get VBScript in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.