XLL+ Class Library

Setting cell values

Let us create a simple macro function that puts the current time in cell A1 of the current worksheet.

Create the function

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.

Add the code

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.

Running the macro

We can invoke the macro in a number of ways. Let us examine a few of them.

  1. Directly

    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.

  2. With a menu or toolbar

    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.

  3. Attached to a button in a workbook

    Using the Forms toolbar, create a new button.

    In the Assign Macro dialog, type in "MacroFn", and click OK.

  4. With code

    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")
    

Next: Find/Replace >>