Link to home
Start Free TrialLog in
Avatar of BBlu
BBluFlag for United States of America

asked on

User Defined Functions in Excel VBA

Can someone explain to me why User Defined Functions must be in a new module and not in the VBA window for a worksheet or "This Workbook"
ASKER CERTIFIED SOLUTION
Avatar of zorvek (Kevin Jones)
zorvek (Kevin Jones)
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of BBlu

ASKER

Got it.  Thanks, Kevin.
Avatar of BBlu

ASKER

Thanks, again, Kevin.
I realize that the question has been answered, but thought it worthwhile to elaborate.

You can indeed put user-defined functions in a worksheet code pane or ThisWorkbook. You just cannot use them in worksheet formulas.

If you use them elsewhere on the same module sheet, you call them the same as if they were on a regular module sheet. But if you use them on a different module sheet (either code pane or regular module sheet), then you need to prefix them with the object:
MsgBox Sheet1.Test(12)               'Refers to the Test function on the Sheet1 code pane. Note that Sheet1 is the code name of that worksheet.
MsgBox Worksheets("Tango").Test(12)         'Refers to the exact same function. The worksheet has a tab name of Tango.
MsgBox ThisWorkbook.TestW(12)    'Refers to the TestW function in the ThisWorkbook code pane

Because explicitly mentioning the parent object is somewhat tedious, it is simpler to install your user-defined functions in a regular module sheet.

Brad
BBlu,

To clarify what Brad has posted, you can place code in any code module: worksheet, workbook, class, and general. And you can call that code from anywhere.

However, you asked about a User Defined Function or UDF which, sorry brad, can ONLY be placed in a general code module.

Placing that code in any other code module renders it just plain old code and it is no longer a User Defined Function.

A User Defined Function is, by definition, a function with zero or more parameters that can be referenced in a cell formula.

Kevin
Avatar of BBlu

ASKER

Thanks to you both.  I appreciate the extra effort all of you put into helping newbies like me.