Rick
Rick

Reputation: 63

Reference a named Excel variable using VBA

Situation: I'm using Excel 10. I have a named variable that uses a formula to compute it's value. This is a named variable, not a named range (in the 'Name Manager' the name "MaxDate" refers to "=MAX(Sheet1!B:B)" where column B is a list of dates). The computed value does not appear in any cells by itself, but rather is used in various formulas within the spreadsheet.

My problem: How can I reference this named variable in VBA code? Using range("MaxDate").value does not work. I know I can simply put the value into a cell and reference the cell, but I'd like to find a way to reference the variable directly. Any ideas?Thanks.

Upvotes: 6

Views: 33662

Answers (2)

Octopus
Octopus

Reputation: 154

For a given workbook with a Named variable "MyVar", valued "=MAX(Sheet1!B:B)".
Try the following code:

Evaluate(ActiveWorkbook.Names("MyVar").RefersTo)

Replace the ActiveWorkbook with the object you're referring if you need to.

Upvotes: 2

David Zemens
David Zemens

Reputation: 53623

Here's some examples of working with your named variable:

Sub TestNamedVariable()

Dim varFormula As String
Dim varValue As Variant

'This will print the formula if you need it:
varFormula = ActiveWorkbook.Names("MaxDate")

'This will evaluate the named variable/formula
varValue = Application.Evaluate("MaxDate")

End Sub

Upvotes: 15

Related Questions