Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a custom worksheet function in Excel VBA

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.

like image 652
Tomalak Avatar asked Apr 16 '09 11:04

Tomalak


People also ask

How do I create a custom function in Excel?

Press Alt + F11 when VBE is open to go back to the Excel window. After opening VBE, you need to add a new module where you will write your functions. Right-click on the VBA project pane and select Insert -> Module. An empty module window will appear where you are to specify your custom function.

How do I use a worksheet function in Excel VBA?

To use an Excel function, type “Application. WorksheetFunction.” and start typing the name of the function. You'll see it come up in the resulting list (you can also just type the name of the function you're looking for). Then you'll need to include the standard arguments for the function.


2 Answers

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)
like image 53
codeape Avatar answered Sep 18 '22 15:09

codeape


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
like image 25
TMD Avatar answered Sep 21 '22 15:09

TMD