views:

968

answers:

3

I have a faint memory of being able to use VBA functions to calculate values in Excel, like this (as the cell formula):

=MyCustomFunction(A3)

Can this be done?

EDIT:

This is my VBA function signature:

Public Function MyCustomFunction(str As String) As String

The function sits in the ThisWorkbook module. If I try to use it in the worksheet as shown above, I get the #NAME? error.


Solution (Thanks, codeape): The function is not accessible when it is defined ThisWorkbook module. It must be in a "proper" module, one that has been added manually to the workbook.

+2  A: 

Yes it can. You simply define a VBA function in a module. See http://www.vertex42.com/ExcelArticles/user-defined-functions.html for a nice introduction with examples.

Here's a simple example:

  • Create a new workbook
  • Switch to VBA view (Alt-F11)
  • Insert a module: Insert | Module
  • Module contents:
Option Explicit

Function MyCustomFunction(input)
    MyCustomFunction = 42 + input
End Function
  • Switch back to worksheet (Alt-F11), and enter some values:
A1: 2
A2: =MyCustomFunction(A1)
codeape
Does not work, that's why I'm asking - I get #NAME?
Tomalak
Hm, seems my choice of module was wrong. It must not sit in the ThisWorkbook module, but in a separate one. Thanks. :)
Tomalak
Your function signature is wrong. Use "untyped" arguments and return values. I don't remember what VBA actually does when you leave out the type, it uses the Variant type, I guess.
codeape
Hm, both Range and String actually do work flawlessly.
Tomalak
I am actually not sure if the signature *is* wrong. I haven't tested. But anyway I guess it is best to use variants - since then you can use the function with both cell references (passed as Range objects) and constants (passed as Float, string, whatever).
codeape
Since this is going to be a quick-and-dirty throwaway solution, passing in a string will be sufficient. But I'll think of it the next time I need it. :)
Tomalak
Arguments may be typed or untyped (Variants), both ways ()and mixtures) work. If type is specified, Excel/VBA will work to try to coerce the input into that specified, which may be a good thing, may not.
Mike Woodhouse
A: 

Very easily - see Using Microsoft Excel Worksheet Functions in Visual Basic.

Galwegian
No, the other way around. I want to use Visual Basic functions on a Worksheet.
Tomalak
A: 

The word input needs to be replaced as it is a basic keyword. Try num instead. You can also go further by specifying a type, eg variant.

Function MyCustomFunction(num As Variant)
    MyCustomFunction = 42 + num
End Function
TMD