Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 300
Rick Avatar asked Mar 27 '13 15:03

Rick


2 Answers

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
like image 165
David Zemens Avatar answered Oct 29 '22 13:10

David Zemens


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.

like image 45
Octopus Avatar answered Oct 29 '22 12:10

Octopus