I am having trouble returning a value from a Named Formula in Excel VBA (a simple Named Range works as expected).
Create the Named Range/Formula rowOffset
equal to:
=ROW(Sheet1!$A$2)-ROW(Sheet1!$A$1)
rowOffset
evaluates as expected (equal to 1)
However, I have been unable to figure out how to return the value of rowOffset
inside of VBA.
'##Sheet1 module##
Sub test()
'ERROR 1004: application-defined or object-defined error
Debug.Print Me.Range("rowOffset").Value
'Returns formula
Debug.Print Me.Names("rowOffset").Value
'ERROR 2015 in Immediate window
Debug.Print Application.Evaluate(Me.Names("rowOffset"))
'ERROR 13: type mismatch
Debug.Print Application.Evaluate(Me.Names("rowOffset").Value)
End Sub
Why doesn't the above code work in this specific situation, but does work for a Named Range with the definition =$A$1
(the value of A1 is returned, as expected)?
EDIT: Thanks to Simoco for the (very simple!) answer. One trip through the locals window and I should have been able to figure this out on my own! haha.
First of all, interesting question!
Woking code:
Debug.Print Evaluate("rowOffset")(1)
or
Debug.Print Join(Evaluate("rowOffset"))
or
Debug.Print Evaluate("INDEX(rowOffset,1)")
or
Debug.Print [INDEX(rowOffset,1)]
Why Debug.Print Evaluate("rowOffset")
is not working?
The reason is because ROW()
actually returns array with one element rather than single value,
i.e. {1}
, and all you need is to take it's first element or concatenate array using Join
.