I’ve searched the web and I’ve searched the questions here on stackoverflow, but I haven’t been able to find a solution.
Here is what I’d like to do:
Suppose I have the following code in a class module named “MyClass”
Option Explicit
Dim var1 as integer
Sub Initialize(v as integer)
var1 = v
End Sub
Function GetVar1()
GetVar1 = var1
End Function
Then I have a UDF in a separate module with the code
Function InitializeMyClass(v as integer) as MyClass
Dim myvar as MyClass
Set myvar = new MyClass
Call myvar.Initialize(v)
Set InitializeMyClass = myvar
End Function
Function GetMyVar(m as MyClass)
GetMyVar = m.GetVar1()
End Function
Now in cell A1 I have "=InitializeMyClass(3)" and in Cell A2 I have "=GetMyVar(A1)". I get #VALUE errors in both cells. This of course is caused by the fact that I am trying to return a user defined data type into cell A1. I feel that this should be possible, but I am not sure how.
Edit: Oh yeah, the question is, "Is there a way for me to return a user-defined data type into a cell and then have it be callable from another UDF in the example I gave above? I don't know if this requires COM or not. If it does, anyone know how I can get started? Ideally, if someone had an example of how this worked, that would be fantastic!"
Another Edit: Here we go, now i know it can be done: read this description, it's not quantitative, but will give you a sense of what they do, http://www.quanttools.com/index.php?option=com_content&task=view&id=19
As the other answers suggest, the literal answer to your question is “no”. You can’t store anything other than a number, string, boolean, error, etc. in a cell. You can’t return anything other than a simple value such as those, or an array, or a range reference, from a UDF.
However, you can do essentially what you want by passing around (and storing in cells) some kind of handle to your objects that is a legal cell value (i.e. “myclass:instance:42”). This is probably what the example you linked to in your edit does. Your code has to be able to interpret the meaning of the handle values and maintain the objects in memory itself, though. This can get tricky if you care about not leaking objects, since there are lots of ways to erase or overwrite handles that you can’t detect if you’re using VBA to do all this.
I don’t have it in front of me right now, but you might want to look at the book Financial Applications using Excel Add-in Development in C/C++ by Steve Dalton:
http://www.amazon.com/Financial-Applications-using-Development-Finance/dp/0470027975/ref=ntt_at_ep_dpt_1
He discusses ways to work with handles like this more robustly with XLL add-ins.