Excel provides a means of executing macros when certain events occur over the lifetime of an add-in session. You already know
xlAutoOpen
is called when an add-in is opened in Excel and that it registers all the
AddIn
objects you created. If you want to run a macro when your add-in is opened, e.g., a splash screen or authentication prompt, here is how to do it:
int xll_macro(void) { // your code here return 1; // or 0 to indicate an error } static Auto<Open> xao_macro(xll_macro);
Note there is no need to declare the function as WINAPI
or use
#pragma XLLEXPORT
to export it.
This calls xll_macro
before add-ins are registered. If you want to call after they are registered use
Auto<OpenAfter>
. (Use Open12
for Excel 2007 and later, and
OpenX
for single source/dual mode add-ins.)
When Excel is closed the function xlAutoClose
is called. The hook for that is
Auto<Close>
.
The Add-In Manager calls xlAutoAdd
and xlAutoRemove
when add-ins are added and removed. After
xlAutoAdd
is called, Excel then calls xlAutoOpen
. When
xlAutoRemove
is called the xll library calls macros instantiated with
Auto<RemoveBefore>
, all add-in functions are unregistered, then macros instantiated with
Auto<Remove>
get called.
The xll library implements xlAutoFree
and xlAutoFree12
. If a function returns an
LPOPER
or LPOPER12
with either the xlbitDLLFree
or
xlbitXLFree
bit set, then it calls delete
or xlFree
respectively. Below are typical use scenarios. To be honest, I don't know if this allows for functions to be declared thread safe (XLL_THREAD_SAFE12
).
Threads can switch between any instruction and there is no guarantee how many instructions get executed when returning a pointer.
LPOPER WINAPI dll_function(double arg, ...) { #pragma XLLEXPORT static LPOPER px = new OPER("string"); // ... px->xltype |= xlbitDLLFree; return px; }
LPOPER WINAPI xl_function(double arg, ...) { #pragma XLLEXPORT static LOPER x; // ... x = Excel(xlfSomething, ...); return x.XLFree(); // sets xlbitXLFree }