Search code examples
excelvbaevaluatenamed-ranges

Excel VBA Evaluate Function Wrong When Reference is Not Active Sheet for Named Range


EDITED WITH BETTER EXAMPLE

I'm trying to use the Evaluate function to evaluate a formula reference for a named range. However, when using the Evaluate function, if you do not explicitly state the sheet reference along with the cell reference, it will assume the active sheet as the cell reference. This causes the wrong result

In my real project I'm trying to only evaluate a part of the named range's formula, so it makes it even trickier.

Using a basic example of what I'm trying to do, let's say you have the following formula in Sheet 1 cell A1 whose name is MyCell:

="Don't evaluate this part"&"My Result Is " & A2

If the Active Sheet is Sheet 2 and you run the following code it will give you the wrong results (this is a quick and dirty example to illustrate the problem)

Dim s As String
s = Replace(Range("MyCell").Formula, """Don't evaluate this part""&", "")
Debug.Print Evaluate(s)

Instead of giving me the value that is in cell A2 of Sheet 1, it gives me the value that is in cell A2 of Sheet2.

Any ideas around this?

This is closest I found, but it is not my exact problem (despite similar titles) and it doesn't provide a solution: Excel VBA evaluate formula from another sheet


Solution

  • Its nearly always better to use Worksheet.Evaluate rather than the default Application.Evaluate: as Mark Balhoff points out that allows you to control unqualified references. But Worksheet.Evaluate is also usually twice as fast as Application.Evaluate. See my blog post here for details https://fastexcel.wordpress.com/2011/11/02/evaluate-functions-and-formulas-fun-how-to-make-excels-evaluate-method-twice-as-fast/