Stop VBA Evaluate from calling target function twice

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


I don't know of a way to stop it, but you can at least recognize when it is happening most of the time. That could be useful if your computation is time consuming or has side effects that you don't want to have happen twice and you want to short circuit it.

(EDIT: Charles Williams actually has an answer to your specific quesion. My answer could still be useful when you don't know what data type you might be getting back, or when you expect to get something like an array or a range.)

If you use the Application.Caller property within a routine called as a result of a call to Application.Evaluate, you'll see that one of the calls appears to come from the upper left cell of of the actual range the Evaluate call is made from, and one from cell $A$1 of the sheet that range is on. If you call Application.Evaluate from the immediate window, like you would call your example Sub, one call appears to come from the upper left cell of the currently selected range and one from cell $A$1 of the current worksheet. I'm pretty sure it's the first call that's the $A$1 in both cases. (I'd test that if it matters.)

However, only one value will ever be returned from Application.Evaluate. I'm pretty sure it's the one from the second eval. (I'd test that too.)

Obviously, this won't work with calls made from the actual cell $A$1.

(As for me, I would love to know why the double evaluation happens. I would also love to know why the evaluator is exposed at all. Anyone?)

EDIT: I asked on StackOverflow here: Why is Excel's 'Evaluate' method a general expression evaluator?

I hope this helps, although it doesn't directly answer your question.

Tags:

Excel

Vba