Let us create a simple macro function that puts the current time in cell A1 of the current worksheet.
Create a new function in the XLL+ ClassWizard, as shown below. The function has no arguments.
Notice that the Macro function check-box is checked and the Worksheet function check-box is unchecked.
Amend the generated code as shown below.
//{{XLP_SRC(MacroFn)
// NOTE - the FunctionWizard will add and remove mapping code here.
// DO NOT EDIT what you see in these blocks of generated code!
IMPLEMENT_XLLFN2(MacroFn, "A", "MacroFn", "", "User Defined",
"Macro function to put the time in Cell A1", "", "", 2)
extern "C" __declspec( dllexport )
BOOL MacroFn()
{
//}}XLP_SRC
// Get the time now
double dNow;
XlNow(&dNow);
// Make a reference to cell A1
CXlOper xloRef;
xloRef.MakeRef("A1");
// Set the value of cell A1
xloRef.SetValue(CXlOper(dNow));
return 0;
}
Build the project and open the add-in in Excel.
We can invoke the macro in a number of ways. Let us examine a few of them.
Invoke the Run Macro dialog box, either by clicking the Tools - Macro - Macros... menu option or with Alt+F8.
Type in the macro name "MacroFn", as shown below, and click Run.
You can create menus and toolbars that will appear when your add-in is opened and be destroyed when the add-in is closed. Each menu item and toolbar tool can be attached to a named macro function.
Menu and toolbars are discussed in detail in Menus and Toolbars.
Using the Forms toolbar, create a new button.
In the Assign Macro dialog, type in "MacroFn", and click OK.
You can also run a macro from VBA code, using the Application.Run() method. For example, the following lines invoke macros with and without arguments:
Call Application.Run("MacroFn") Call Application.Run("MacroFn2", 12.6, "cheese")