The AddIn
object stores The C function name (Procedure
), the C signature (TypeText
- a character string specifying the return type and C function argument types), the name Excel uses for your function (FunctionText
), and the argument prompt (ArgumentText
) that shows up after you type the function name and hit Ctrl-Shift-A. You can also specify the category (Category
) and help text (FunctionHelp
) used in the Function Wizard. This information is supplied to xlfRegister
when xlAutoOpen
is called by Excel.
There is more than one way to create AddIn
objects. The simplest way is to specify the information Excel needs directly:
static AddIn xai_function( "?xll_function", XLL_LPOPER XLL_DOUBLE, "XLL.FUNCTION", "Number", "My Category", "Description of what the function does." );
The constructor for AddIn
gets called by the linker when the add-in is opened and simply stores the information that will be needed by Register
when Excel calls xlAutoOpen
. The symbols XLL_LPOPER
and XLL_DOUBLE
are #define'd to be the character strings "P" and "B", respectively. The C preprocessor concatenates these for you which results in the TypeText argument being "PB". See defines.h
for a complete list.
Another way to do this is:
static AddIn xai_function( Function(XLL_LPOPER, "?xll_function", "XLL.FUNCTION") .Arg(XLL_DOUBLE, "Number", "is a number ") .Category("My Category") .FunctionHelp("Description of what the function does") );
One slight difference is that the Function Wizard will now tell you that Number
"is a number".
You still need to implement the actual function to be called. Here is how to do that:
LPOPER WINAPI xll_function(double x) { #pragma XLLEXPORT static OPER oResult; oResult = x; return &oResult; }
Some things to note: When specifying the procedure in the AddIn
object you must prepend a question mark. LPOPER
is the same as OPER*
. An OPER
is a C++ datatype that corresponds to a cell or a two dimensional range of cells. Every function that you register with Excel must be declared WINAPI
. The first line of the body of the function has to be #pragma XLLEXPORT
. We are returning the address of the OPER
so it must be declared static so what is being pointed at will be around when Excel takes a look. Note we are assigning a double to an OPER
. I went to a lot of trouble to make OPER
s behave just as you would expect.