Worksheet functions in VBA macros
2003-04-27 VBA programming 0 67
Almost all of the built-in worksheet functions can be used in macros. If you have a
non-English version of Excel you have to remember to use the English function names, and
that the separator sign between the function arguments always is a comma (,). If you don't
know the English function name, record a macro while you enter the function the usual way
in a cell, in the registered macro the function name will be translated to English. When
you are going to use a worksheetfunction in a macro you also have to include the
Application-object. In Excel97 you use the object Application.WorksheetFunction.
MyTotal = Application.Sum(Range("A1:A100")) ' returns the total of the values in A1:A100 in the active worksheet. MyTotal = Application.WorksheetFunction.Sum(Range("A1:A100")) ' the same formula for Excel 97.If you want to use functions from the Analysis Tool Pack addin in your own macros:
- Open the VBE (Alt+F11).
- Activate the project where you want to use the function(s).
- Select Tools, References... and check the option atpvbaen.xls.
- click the OK-button to close the References-dialog.
The macros in the workbook where you added the reference to the atpvbaen.xls library can now use the functions like this:
workdaycount = networkdays(Date, Date + 14) ' or like this to avoid conflict with other user defined functions with the same name: workdaycount = [atpvbaen.xls].networkdays(Date, Date + 14)It is not necessary to install the Analysis Tool Pack addin from the menu Tools, Add-Ins...