Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.
The following steps show you how to create a simple custom function, how to
call the function from the workbook that contains the code, and how to call
this custom function from another workbook.
To Create a Custom Function
- Open a new workbook.
- Start the Visual Basic Editor (press ALT+F11).
- On the Insert menu, click Module.
- On the module sheet, type the following code:
Function myfunction(x)
myfunction = x * 2
End Function
- Save this workbook as Test.xls.
To Call the Function from the Workbook That Contains the Function Code
To call this function from within Test.xls, type the following formula in
cell A1 on Sheet1:
=myfunction(3)
Cell A1 should display the value 6, because the custom function doubled the
value that was sent to it.
To Call the Function from Another Workbook
In order to call the function from a workbook, you must create a reference
to the workbook that contains the code. To create a reference, follow these
steps:
- Open a new workbook.
- Save this workbook as Test2.xls.
- Start the Visual Basic Editor (press ALT+F11).
- On the Insert menu, click Module.
In the next steps, you will create a reference to Test.xls. - Press CTRL+R to activate the Project Explorer window.
- Select VBAProject (Test.xls), and then click VBAProject Properties on the Tools menu.
- In the Project Name box, type MyProject and then click OK.
- Select VBAProject (Test2.xls) in the Project Explorer window.
- On the Tools menu, click References. Click MyProject, and then click OK.
You should now have a reference to the workbook that contains the custom
function. You can now call this custom function the same way you would call
it if the workbook contained the code. For example, in cell A1 of Test2.xls, type the formula:
=myfunction(5)
Cell A1 should display the value 10.
NOTE: If the reference is not made as outlined in steps 1-4, cell A1 displays the #NAME? error value because Microsoft Excel does not know where
to find the "myfunction" custom function. Naming the function and the
project with the same name also results in the #NAME? error.
Note also that you cannot create a reference to an unsaved workbook, so if
you encounter an error when you try to create the reference, make sure the
workbook that contains the custom function has been saved.