Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop VBA Evaluate from calling target function twice

Tags:

excel

vba

I am having trouble getting VBA's Evaluate() function to only execute once; it seems to always run twice. For instance, consider the trivial example below. If we run the RunEval() subroutine, it will call the EvalTest() function twice. This can be seen by the two different random numbers that get printed in the immediate window. The behavior would be the same if we were calling another subroutine with Evaluate instead of a function. Can someone explain how I can get Evaluate to execute the target function once instead of twice? Thank you.

Sub RunEval()
    Evaluate "EvalTest()"
End Sub

Public Function EvalTest()
    Debug.Print Rnd()
End Function
like image 435
Abiel Avatar asked Apr 10 '10 01:04

Abiel


1 Answers

This bug only seems to happen with UDFs, not with built-in functions. You can bypass it by adding an expression:

Sub RunEval()
    ActiveSheet.Evaluate "0+EvalTest()"
End Sub

But there are also a number of other limitations with Evaluate, documented here http://www.decisionmodels.com/calcsecretsh.htm

like image 198
Charles Williams Avatar answered Oct 09 '22 12:10

Charles Williams