views:

185

answers:

4

Suppose I have a function attached to one of my Excel sheets:

Public Function foo(bar As Integer) as integer
    foo = 42
End Function

How can I get the results of foo returned to a cell on my sheet? I've tried "=foo(10)", but all it gives me is "#NAME?"

I've also tried =[filename]!foo(10) and [sheetname]!foo(10) with no change.

A: 

include the file name like this

=PERSONAL.XLS!foo(10)
chilltemp
Same result both with my actual file name or with personal.xls
CodeSlave
+2  A: 

Put the function in a new, separate module (Insert->Module), then use =foo(10) within a cell formula to invoke it.

Dr. Sbaitso
I got the same result for both options
CodeSlave
+2  A: 

Try following the directions here to make sure you're doing everything correctly, specifically about where to put it. ( Insert->Module )

I can confirm that opening up the VBA editor, using Insert->Module, and the following code:

Function TimesTwo(Value As Integer)
    TimesTwo = Value * 2
End Function

and on a sheet putting "=TimesTwo(100)" into a cell gives me 200.

Stephen Pape
Moving it to a separate module did indeed solve the problem.
CodeSlave
+1  A: 

Where did you put the "foo" function? I don't know why, but whenever I've seen this, the solution is to record a dimple macro, and let Excel create a new module for that macro's code. Then, put your "foo" function in that module. Your code works when I follow this procedure, but if I put it in the code module attached to "ThisWorkbook," I get the #NAME result you report.

JeffK