XLL Plus 7.0

Welcome to XLL+

XLL+ is a toolkit for writing Excel add-ins in C++. Use the links below to get started with XLL+.

Getting Started

Quick Start
To use XLL+ right away, use the Quick Start, a one-page guide to building an XLL add-in.
XLL+ User Guide
The XLL+ User Guide is a complete introduction to XLL+. It contains comprehensive instructions for using all XLL+ features.
What's New?
If you've used previous versions of XLL+ you should see what's new in this release.
How Do I...
Look at How Do I... for links to the essential XLL+ features.
Walkthroughs
To learn how to use particular features, look at the Walkthroughs.
Sample Projects
Inspect the sample projects, to find any features that you need for your own application.
Requirements
Check that you have the right development and run-time environments for XLL+.

You can find the latest samples, tools and templates on our web-site at http://www.planatechsolutions.com/xllplus/resources.htm

Overview

The XLL+ toolkit contains four main components:

XLL+ AppWizard
The XLL+ AppWizard creates a new Developer Studio project, containing all the code required to build and register an Excel add-in XLL library.
XLL+ Function Wizard
The XLL+ Function Wizard is an add-in for Microsoft Developer Studio which lets you create and edit add-in functions. It generates all the code required for registering the function with Excel and for input & output of Excel data structures.
XLL+ ToolWindow
The XLL+ ToolWindow appears within Microsoft Developer Studio. It shows a list of all the XLL+ add-in functions in the active document. You can make changes to your add-in functions directly, using the Visual Studio Properties window, and you can change any or all add-in functions at the same time.
XLL+ Runtime Libraries
The XLL+ Runtime Libraries contain C++ object classes which give you easy & safe access to Excel features from within your add-in functions.

There are also many examples of code, including complete applications and walkthroughs, to help you on your way. Finally, there are tools to help you leverage your code, such as a Help Generator and a COM Wrapper Generator.

Version | 7.0.6
Released | 28th February 2014
Web | www.planatechsolutions.com/xllplus
Email | support@planatechsolutions.com
Copyright | © Planatech Solutions Ltd 1997-2014

© 1997-2014 Planatech Solutions Ltd. All rights reserved.


What's New in Version 7.0

Version 7.0.6

XLL+ 7.0.4 introduces support for Microsoft Visual Studio 2014.

New features added with version 7.0.6 include:

Complex handle types
Object handles can now be complex types and can include namespaces and templates, e.g.: std::map<std::string, std::string>. It is no longer necessary to create a typedef for this kind of object.
Shared handles
Object handles can now be shared across separate XLLs, so one XLL can create and publish an object, and other XLLs can consume it.
Selective publishing of add-in functions
Developers can decide which of the add-ins contained in an XLL will be made available to users. The list can be controlled at run-time or at development-time.
New event handlers for Excel 2010+
Two new COM event handlers have been added to the library, to handle the WorkbookAfterSave and AfterCalculate events, introduced in Excel 2010. These event handlers will have no effect under earlier versions of Excel.

Version 7.0

XLL+ 7.0 contains some important new features, including:

64-bit libraries

XLL+ now creates both 32-bit and 64-bit builds of XLL add-ins, so that you can now provide your add-ins to users of Excel 2010 64-bit edition.

Also, all the XLL+ redistributable run-time servers are provided in both 32-bit and 64-bit formats.

Queued asynchonous functions

XLL+ now supports the new Excel 2010 asynchronous execution feature. This can greatly improve the efficiency of thread-safe functions that contend for a shared resource (such as a database or a data feed).

Ribbon support

XLL+ 7 provides full support for the Office Ribbon, managing all the COM interface issues, and routing the ribbon messages and events to a C++ event-handler function in your code.

Version 6.3

Version 6.3 of XLL+ contained many major changes, see What's New in 6.3 for details.

Upward compatibility

For instructions on how to use the XLL+ Upgrade Wizard to port existing projects to XLL+ 7, please see the topic Upgrading from a previous version of XLL+.

Change history

Refer to the Change history for a full list of changes made over all XLL+ versions.


64-bit libraries

64-bit add-ins can offer improved performance in some cases: particularly where the amount of data used is huge, whether the data is contained within the spreadsheet or is used within calculations external to the spreadsheet.

XLL+ now creates both 32-bit and 64-bit builds of XLL add-ins, so that you can now provide your add-ins to users of Excel 2010 64-bit edition.

All the XLL+ redistributable run-time servers are now provided in both 32-bit and 64-bit formats.

The XLL+ AppWizard now creates projects that can be built as 32-bit add-ins or as 64-bit, or both.

If you have existing 32-bit projects built with earlier versions of XLL+, you can use the XLL+ Upgrade Wizard to convert them to XLL+ 7 projects, with 64-bit support.


Queued asynchonous functions

Excel 7 supports Excel 2010's new Asynchronous flag.

Beginning in Excel 14 (Excel 2010), functions can be marked as "Asynchronous". (This flag does not mean that the functions immediately return "#WAIT!", run asynchronously and inform Excel when they have finished; see Asynchronous functions for this behavior.)

The effect of the new Asynchronous flag is subtle but powerful. If a function is marked as thread-safe then many threads may be running the same function at the same time. If the function makes use of a shared resource, such as a database, then all but one of the threads may be locked out, waiting for the thread currently using the resource to complete.

If the function is also marked as asynchronous, then Excel will call the function and immediately return, without waiting for the result. The branches of the recalculation tree whch are affected by the current cell will not be calculated at this time, but will be queued to be dealt with later. The calculation thread can now be used to resolve some other part of the tree, which is ready to be calculated. It is the responsibility of the add-in function to dispatch the task to a background thread, and to inform Excel when the background thread has completed the task (by calling the SDK call-back function xlAsyncReturn).

Once Excel has received the xlAsyncReturn signal, it knows that the cell is ready, and can continue to calculate the branches of the tree that were queued.

The effect of the behavior on functions which compete for the same resource can be very powerful: performance can improve by 100% or even more.

If you put a check against the function's flag, Create queued version, all the required code will be generated to create a queued version of the function, which will run in a background thread and report back to Excel using the xlAsyncReturn signal.

For details of the XLL+ implementation, see Queued functions in the User Guide.


Ribbon support

XLL+ 7 supports the Office Ribbon. You can now provide a more polished and flexible User Interface for your add-ins.

You can generate all the code required for a ribbon by checking the option Add a group to the ribbon in the XLL+ AppWizard.

Standard code generated by the XLL+ AppWizard makes it easy to support the Office Ribbon (when running under Excel 2007 or above) and to provide menus and/or toolbars when running under earlier versions of Excel.

For more about the Ribbon support in XLL+ 7 see The Ribbon in the User Guide.


What's New in Version 6.3

Version 6.3

XLL+ 6.3 brought some exciting new features, including:

Hidden regions

Almost all of the generated code is now surrounded by #pragma region blocks. This means that almost all of the implementation code for each add-in can be hidden, and you need only see the code that is interesting - the function signature and your own code.

XLL Wrapper Libraries

Sometimes it is useful to be able to call your Excel add-in functions from other environments, such as command-line programs or interactive applications, written in C++, Java, C# or Visual Basic.

The Xll Wrapper toolkit contains tools, a runtime library, samples and documentation to help with the development of COM modules and .NET assemblies that wrap Excel XLL add-ins.

The add-in functions in the library are available as COM and .NET methods to client programs that use the wrapper modules.

The wrapper objects can be used by clients written in any development environment that supports COM or .NET, including C++, Java, C#, Visual Basic and VBA.

Asynchronous functions

We've considerably improved the performance and scalability of the asynchronous function model. You can now place thousands of asynchronous functions in a spreadsheet without degrading performance.

Sample data feed application

We've added a new sample application which demonstrates how to integrate a data feed into an Excel add-in for high-performance real-time data add-in, written in C++, and which supports array real-time values as well as scalar values.

Portuguese language support

Help files can now be generated in any of three languages: English, French and now Portuguese.

Value Lists

The Value List Editor is now easier to use. You can copy and paste data to and from the dialog, so it's easy to edit lists in source code or in Excel, and paste them into the Value List Editor.

Version 6.2

Version 6.2 of XLL+ contained many major changes, see What's New in 6.2 for details.

Upward compatibility

For instructions on how to use the XLL+ Upgrade Wizard to port existing projects to XLL+ 6, please see the topic Upgrading from a previous version of XLL+.

Breaking changes

See Breaking changes for a list of changes that may affect code built with earlier versions of XLL+.

Change history

Refer to the Change history for full list of changes made over all XLL+ versions.


Hidden regions

In XLL+ we've added support for hidden regions.

Almost all of the generated code is now surrounded by #pragma region blocks. This means that almost all of the implementation code for each add-in can be hidden, and you need only see the code that is interesting - the function signature and your own code.

And, unless you click on the "+" symbol to expand the code, the XLL+ tool-kit will ensure that the implementation stays hidden, and out of your way.

Some of the more complicated add-in functions, particularly asynchronous functions, can have over a hundred lines of implementation code. It is much easier to maintain your own code if all of this detail is hidden.

See Hidden regions in the User Guide for more details.


Wrapper libraries

Sometimes it is useful to be able to call your Excel add-in functions from other environments, such as command-line programs or interactive applications, written in C++, Java, C# or Visual Basic.

The Xll Wrapper toolkit contains tools, a runtime library, samples and documentation to help with the development of COM modules and .NET assemblies that wrap Excel XLL add-ins.

The add-in functions in the library are available as COM and .NET methods to client programs that use the wrapper modules.

The wrapper objects can be used by clients written in any development environment that supports COM or .NET, including C++, Java, C#, Visual Basic and VBA.

See the XLL Wrapper Generator guide for more details.


What's New in Version 6.2

Version 6.2

XLL+ 6.2 contains some important new features, including:

Value Lists

Integer arguments can now have value lists assigned to them. These constrain the user's input, returning an error if the input value is not a value in the value list.

In addition, you can make a drop-down list appear in the Excel Formula Wizard, with descriptions for each of the values.

Importing .NET assemblies

Using XLL+ 6.2, you can import entire .NET assemblies, and XLL+ will automatically generate add-in functions for any methods or properties that you select.

RTD Object Handles

We've added a new kind of object handle, implemented using RTD (Real-Time Data). This has advantages over the previous model:

  • Objects can be destroyed as soon as they are no longer in use.
  • Recalculation of stale objects is automatic, and does not need macros.
  • Developers can customize the appearance of handles, to make them more user-friendly.
Asynchronous functions

We've considerably improved the implementation of the asynchronous function model. It no longer needs a separate signal cell as an input, and it is faster, more robust and less intrusive.

Logging framework

XLL+ (from version 6.2 onwards) contains a logging framework which helps you to write diagnostic and other information to a variety of destinations, including log files and the Visual Studio Output window.

New MFC Runtime Libraries

A new "minimum dependencies" build of the MFC runtime libraries has been added, which allows all MFC and CRT libraries to be included within the XLL. This removes the requirement for the Microsoft MFC and CRT DLLs to be installed on a user's machine.

New sample applications

We've added new sample applications to demonstrate all the new features.

Version 6.0

Version 6.0 of XLL+ contained many major changes, see What's New in 6.0 for details.

Upward compatibility

For instructions on how to use the XLL+ Upgrade Wizard to port existing projects to XLL+ 6, please see the topic Upgrading from a previous version of XLL+.

Breaking changes

See Breaking changes for a list of changes that may affect code built with earlier versions of XLL+.

Change history

Refer to the Change history for full list of changes made over all XLL+ versions.


Value Lists

You can now create a value list for any argument, using the Function Wizard.

Value lists can appear in 3 places:

  1. If an input value is not in the value list, then an informative error message can be returned, to make it easy for the user to correct the value, e.g.:

    CopyC++
    #VALUE! Expected one of 0,1,2,3,4,5,6 for DayCount

  2. A drop-down list will appear in the the Excel Formula Wizard, with the descriptions of each of the acceptable values:

  3. A table describing each of the values will be inserted into the function's on-line help topic.

See Value Lists in the User Guide for more information.


Importing .NET Assemblies

Using XLL+ 6.2, you can import entire .NET assemblies, and XLL+ will automatically generate add-in functions for any methods or properties that you select.

You can use Attributes in your .NET code to indicate which methods and properties you want to export, and to add any special treatment for functions or their arguments.

Alternatively, you can use the XLL+ Import Editor to select the exported methods, without changing your existing .NET code in any way.

See Importing .NET assemblies in the User Guide for more details.


Asynchronous functions

In XLL+ 6.2, we have significantly improved the implementation of asynchronous functions.

  1. Asynchronous functions no longer need to have a special "RtdSignal" cell.
  2. They now have exactly the same signature as standard synchronous functions.
  3. There is a lower performance cost to running a function asynchronously.
  4. The user experience is affected less - no cell formulae are changed, and the update is much less intrusive.

See Asychronous functions in the User Guide for more details.


Logging framework

XLL+ 6.2 contains a logging framework, cpplog, which helps you to write diagnostic and other information to log files and to the Visual Studio console window.

You can use a configuration file to control what is logged, the destination for the log statements, and what level of detail is recorded. By default nothing is written to the log, and the performance cost of log statements is extremely low.

See Logging in the User Guide for details. The class reference for the framework header files is here: cpplog.h.


RTD Object Handles

In XLL+ 6.2, we've added a new kind of object handle, implemented using RTD. This has several advantages over the previous model.

Object lifetimes

Using RTD, an event is raised when an object handle is no longer being used by Excel. The XLL+ run-time calls the destructor for the object as soon as this occurs. This means that the run-time cache is much smaller, since it contains only live objects, and performance is much improved, especially with large objects.

Also, it is not necessary to do any house-keeping, such as providing a "Clear handles" menu.

Recalculation

With RTD handles, it is no longer necessary to force a recalculation of handles in reopened workbooks. If a handle is stale, Excel and the XLL+ framework mangage this automatically. Any handle that needs to be rebuilt will be recalculated, and any that do not recalulation will be left intact.

Customizable handle formats

Developers can customize the layout and content of handles, and can include information from the object itself. For example, a handle can contain its type, name and other properties, as well as the computer-generated handle details:

YieldCurve:USD:2-Mar-09:{A6CBD52A-040D-4990-89EF-41A6721BADC6}:1280298484

This makes for much more user-friendly handles; it becomes much easier to understand the structure of a spreadsheet that uses handles, and to track down problems.

Object cache

We've added some classes to make it simple to store your objects in a cache for improved performance. The cache can be tuned using heuristics that include size of cache and age of object.

For more details see Object Handles in the User Guide.


What's New in Version 6.0

Version 6.0

Version 6.0 of XLL+ contained many major changes, including:

Excel 2007 Support

XLL+ 6 supports the new features of Excel 2007, including thread-safe functions, huge spreadsheets and Unicode strings.

Add-ins built with XLL+ 6 will work in Excel 2007 as well as in earlier versions of Excel, and will take advantage of all the features of each.

.NET support

XLL+ 6 now fully supports .NET integration. You can create .NET and Common Language Runtime classes, and call their methods and properties, from within an add-in function. The XLL+ AppWizard now has a setting which sets up all the necessary project settings for you.

Extensibility

With the new extensibility features of XLL+ 6, you can add your own data types, deliver data to the container classes of your choice, and add your own standard code fragments to be added to any or all add-in functions.

Easier development

Many of the most powerful features of an Excel add-in can now be added without any coding. You can add object handles or asynchronous functions with a single click of the mouse.

XLL Add-ins ToolWindow

The new XLL Add-ins ToolWindow lets you edit your add-in functions in the Visual Studio Properties window. You can make changes to multiple functions with one action.

Help for your add-ins

The new Help Generator automatically builds full-featured compiled help files for your add-ins, and lets you add your own HTML content that will be inserted into the compiled help.

Unicode support

XLL+ 6 fully supports Unicode builds, so that you can properly use Unicode character sets in your functions' categories, descriptions and help.

Local language support

All of the run-time messages, including validation error text, can be localized, so that it appears in the language of the user.

Upgrade Wizard

The Upgrade Wizard will automatically regenerate all the code of your existing add-ins that were built with XLL+ 5, to work with XLL+ 6 and use its new features.

New sample applications

We've added new sample applications to demonstrate all the new features.

Upward compatibility

For instructions on how to use the XLL+ Upgrade Wizard to port existing projects to XLL+ 6, please see the topic Upgrading from a previous version of XLL+.

Breaking changes

See Breaking changes for a list of changes that may affect code built with earlier versions of XLL+.

Change history

Refer to the Change history for full list of changes made over all XLL+ versions.


Excel 2007

Microsoft Excel 2007 contains many exciting new features, and XLL+ 6 supports them fully.

Thread-safe functions

With XLL+ 6, you can mark an add-in function as thread-safe, and it will be available to be used in a multi-threaded recalculation under Excel 2007. On a dual- or quad-core processor, or on a machine with multiple processors, this can lead to a substantial performance improvement.

All the XLL+ run-time classes that are available for use from add-in functions are now thread-safe.

Huge worksheets

Excel 2007 increases the maximum size of a worksheet, from 65536 rows x 256 columns to 1048576 rows x 16384 columns. XLL+ classes support the new sizes, as well as continuing to work correctly with the older versions of Excel.

Unicode support

Excel 2007 works natively with Unicode strings. This means that all the text associated with your function can be in the character set of your native language, including the function name, argument names and all help text.

XLL+ 6 fully supports Unicode, both in the tools and in the run-time library. In addition, the error text returned by XLL+ add-in functions can now be localized, so that it appears in the language of the spreadheet user.

More arguments per function

Excel 2007 supports up to 255 arguments to an add-in function (previous versions allowed only 30 arguments). XLL+ 6 supports the new limit, and also offers new and powerful features to help you group multiple arguments, to support older versions of Excel.

Long strings

String values can now be up to 32,767 characters long (previous versions supported only 255 characters).

Portable add-ins

The add-ins you build with XLL+ 6 will work under both Excel 2007 and older versions of Excel. Any Excel 2007 features that your functions use will not be available under when your add-in is opened with Excel 2003 or below.

The XLL+ framework will make sure that each function is registered correctly under either environment, and will handle the differences between the two, so that your code can be platform-independent.


.NET

XLL+ version 6 now supports .NET integration.

The XLL+ AppWizard has a new option that lets you choose to add Common Language Runtime support to your add-in.

A new set of runtime libraries handles all the intricacies of coordinating the initialization and management of the C++, .NET and Excel add-in environments.

We have added a new set of helper functions, to make it easy to convert data between .NET forms and standard C++ forms.

See the User Guide for more details of the new .NET/CLR support.


Extensibility

XLL+ 6 offers a variety of new extensibility features to make the code generated by the XLL+ tools fit ever more closely with your existing code-base.

Extended types

XLL+ has always been able to transform Excel inputs to standard C and C++ types, such as double, int, std::string etc.

With XLL+ 6, we have introduced extended types, which let you specify your own value types, such as date classes, currency codes or enumerated values, and have them appear in the Function Wizard along with the standard built-in types.

The Function Wizard generates all the code necessary to transform the Excel inputs to the extended type, as well as validating the input and generating appropriate error messages if input validation fails.

See Extended types in the User Guide for more on extended types.

Function extensions

With XLL+ 6, you can author your own function extensions, which will be inserted into the generated code for a function by the XLL+ Function Wizard whenever you select them.

Typical uses of function extensions include:

  • Writing usage information to a log.
  • Selectively allowing only certain classes of user to access certain add-in functions.
  • Standard handling for exceptions generated by calls to your existing libraries.
  • Serializing all arguments and passing the function call to a grid computing network.

See Function extensions in the User Guide for more information.

We have also used function extensions and extended types together to provide a new and almost code-free mechanism for object handles. See Object handles in the User Guide for more about this mechanism.

Container classes

Earlier versions of XLL+ offered limited container support. 1-dimensional inputs were placed into std::vector, and 2-dimensional inputs were delivered to ple::imtx matrix classes.

With XLL+ version 6, you can specify the container type for any or all of your vector and matrix inputs. So if you are writing XLL add-ins which call libraries of existing functions, you can deliver the Excel inputs directly into the container type expected by the libraries.

To illustrate this technique, we have provided a sample showing how to use the boost::multi_array class as a target matrix container.


Easier development

Adding powerful features to your add-in libraries is easier than ever with XLL+ 6.

Object handles

With XLL+ 6, you can return objects to Excel, and represent them as handles, without any coding. Handles can be passed as arguments to add-in functions, and the XLL+ Function Wizard will generate code to convert each handle to the object it represents.

Function Wizard with handles extension in use

The Function Wizard also generates code to handle all the house-keeping tasks for object handles.

See Object handles in the User Guide for more information and examples.

Asynchronous functions

If a function takes a very long time to complete, Excel is locked and unusable in the meantime. It is sometimes useful to run the function asynchronously, in a separate thread, so that Excel remains available while the function completes. While the calculation is continuing, the target cell will display "#WAIT!", and when it is complete, the result will automatically be updated to display the result.

In the past, this kind of functionality took a lot of effort to create, and incurred a high maintenance cost because of the complexity of the code. With XLL+ 6, the XLL+ Function Wizard lets you create an asynchronous version of a function with no coding.

Function Wizard with Create asynchronous version flag set

See Asynchronous functions in the User Guide for more information and examples.

Formula Wizard Preview

The new Formula Wizard Preview lets you see exactly how your function will look in the Excel Formula Wizard. You don't need to start up Excel to see if your names and descriptions will fit in the Wizard.

See Previewing the Function Wizard in the User Guide for more information.

Favorites

You can create a repository of "Favorite arguments" so that standard arguments to functions can be easily reused in new add-in functions. You can share the repository between team members so that all functions have standardized names, descriptions and signatures.

See Favorite arguments in the User Guide for more information.


XLL Add-ins ToolWindow

The XLL Add-ins window is a ToolWindow that lives inside Visual Studio, and lets you directly view and edit all of your add-in functions.

You can use the Add-ins window to navigate around your source code, and you can use it with the Visual Studio Properties window to make changes directly to your add-in functions without needing to pop up the XLL+ Function Wizard. You can select multiple functions, and make changes to them all at the same time.

Picture of Add-ins Window + Properties window in situ

More on the XLL Add-ins window

The XLL Add-ins ToolWindow
An introduction to the XLL Add-ins window, in the User Guide.
Summary of Commands
A list of the commands available from the XLL Add-ins window.
XLL Add-ins Window
Help page for the XLL Add-ins window.


Help generator

The new Help Generator builds full-featured compiled help files for your add-ins, and lets you add your own HTML content that will be inserted into the compiled help.

The help topics will automatically be available from the Excel Formula Wizard, when the user clicks on "Help for this function".

More on the Help Generator

Generating help
The User Guide chapter about using the help generator.


Unicode

XLL+ version 6 supports Unicode (16-bit) character sets as well as ANSI (8-bit) character sets.

You can use Unicode characters in the XLL+ wizards, for any descriptive text, including the help text that will appear in the Excel Formula Wizard.

Excel Formula Wizard with traditional Chinese help text

The XLL+ libraries now support Unicode builds as well as standard builds, and all library functions are now available in both Unicode and ANSI versions.

XLL+ 6 fully supports Unicode builds, so that you can properly use Unicode character sets in your functions' categories, descriptions and help.

The error messages produced by the XLL+ run-time libraries are now localizable, so that they can appear in the language of the user.


Breaking changes

During the development of the XLL+ run-time libraries, every effort has been made to preserve the behavior of code that uses older versions of XLL+. However, a few exceptions have proven impossible to avoid.

XLL+ 6.0

  • String arguments
  • CXlOper::Cell and CXlOper::VectorCell
  • CXlOper::CallAddin
  • CXlOper::GetRef
  • VersionInfo
  • COper methods
  • COper and CXlOper data members
  • CXllFn data members
  • CXlHandleStore::ObjectFromHandle

XLL+ 6.2

  • GDI32 linker error
  • Asynchronous functions

String arguments

If you have existing code which uses string arguments, it will in general continue working under XLL+ 6. The old version of the function had an argument of type const char*; the upgraded version will have const CXlStringArg&. The compiler will use the casting operator CXlStringArg::operator const char* and the code will work as before.

A problem arises if your code passes the string to a loosely-typed function such as printf() or CXlOper::Format. The code will compile successfully, but the compiler will not invoke the casting operator, and you must cast the value explicitly.

For example, an XLL+ 5 add-in function with a string argument might use it as follows:

CopyC++
extern "C" __declspec( dllexport )
LPXLOPER GetCustomerDetails(const char* customer)
{
//}}XLP_SRC
    char select[512];
    sprintf(select, "SELECT * FROM CUSTOMER WHERE NAME='%s'",
        customer);
    ...
}

Under XLL+ 6 the converted code will fail, and the argument to sprintf must be cast to const char*:

CopyC++
CXlOper* GetCustomerDetails_Impl(CXlOper& xloResult, const CXlStringArg&
    customer)
{
    // End of generated code
//}}XLP_SRC
    char select[512];
    sprintf(select, "SELECT * FROM CUSTOMER WHERE NAME='%s'",
        (const char*)customer);
    ...
}

CXlOper::Cell and CXlOper::VectorCell

Under previous versions of XLL+ (5 and below), these methods returned a reference to a CXlOper type, which was contained within the outer CXlOper. In order to support both Excel 2007 and older versions of Excel, this functionality has had to be changed.

The methods now return a new class of object, CXlCell or CXlConstCell, which can be used to refer to the cell, but is not itself of type CXlOper.

If your code retained a copy of the return value, as in for instance:

CopyC++
const CXlOper& item = xloArray.VectorCell(i);
total += item.ToDouble();

then it must be changed. The code above becomes:

CopyC++
CXlConstCell item = xloArray.VectorCell(i);
total += item.ToDouble();

If your code simply used the returned value without retaining a copy of it, then it will continue to compile. For example, the following code does not need to change:

CopyC++
xloArray.VectorCell(i) = 0.0;

CXlOper::CallAddin

A new model for implementing add-in functions has been introduced for XLL+ 6. There are two shell functions (generally MyFunction_4 and MyFunction_12) which are called by Excel; each in turn calls a common implementation function (generally MyFunction_Impl).

If you have been calling an add-in function from another add-in function in the same project, using CXlOper::CallAddin, then you will need to change the way you call it.

The internal call should now be to MyFunction_Impl instead of to MyFunction, and it should have one extra argument, which is the destination of the result.

For an example of the code change required, see the SimpOpt sample.

CXlRef::GetRef

Under XLL+ version 5 and below, this method returned a reference to the actual CXlRef contained within the CXlOper, which could then be written to directly. In order to support Excel 2007 as well as earlier versions of Excel, this functionality has had to be changed.

The method now returns a copy of the CXlRef contained in the CXlOper; in order to change its value, you must call SetRef to apply any changes. Thus, if your existing code is:

CopyC++
xloRef.GetRef().MoveBy(0, 1);

You will need to change it to:

CopyC++
CXlRef xlr = xloRef.GetRef();
xlr.MoveBy(0, 1);
xloRef.SetRef(xlr);

Alternatively, you can use one of the new short-hand functions CXlOper::MoveRefBy or CXlOper::SetRef, e.g.:

CopyC++
xloRef.MoveRefBy(0, 1);
xloRef.SetRef(1, 2);

VersionInfo functions

Earlier versions of XLL+ generated a VersionInfo add-in function that cannot be upgraded by the XLL+ Upgrade Wizard. To upgrade this function, the easiest solution is to generate a new VersionInfo function, using the Add VersionInfo Function command (on the Tools menu of the XLL Add-ins window). Then copy over any details you wish to retain from the old function, and delete it.

COper methods

Deprecated COper methods

For XLL+ 6, the COper class has been merged into the CXlOper class. Some COper functions that have been deprecated for some time were not included in the merge:

  • ColToVector
  • RowToVector
  • ReadOpt
  • ToMatrix

COper validation methods

For XLL+ 6, the mechanism for validation has been completely revised. Some COper functions that were used by the code generated by the Function Wizard are no longer used, and are not supported in XLL+ 6:

  • ReadArrayIntoOrderedCollection1D
  • ReadArrayIntoSet1D
  • ReadGroupItem
  • ReadOptional
  • ReadValue
  • ReadVectorItem

COper and CXlOper data members

In earlier versions of XLL+, the CXlOper and COper classes were publicly derived from their underlying C structures, XLOPER and OPER respectively. This allowed developers to directly access the data members of the underlying structure. In particular, the val and xltype data members could be read directly.

The CXlOper class is no longer directly derived from the XLOPER structure. It now holds a pointer to either a XLOPER or a XLOPER12 structure, depending on the version of Excel under which the add-in is running.

Code that uses the xltype member should call CXlOper::IsOfType() to inspect it.

Direct access to the val data member is no longer supported.

CXllFn data members

Several of the data members of CXllFn have been removed, and replaced by Excel-version-dependent data members.

XLL+ 5.0 | XLL+ 6 - Excel 2003 & below | XLL+ 6 - Excel 2007 & above
m_stEntryPoint | m_stEntryPoint4 | m_stEntryPoint12
m_stArgTemplate | m_stArgTemplate4 | m_stArgTemplate12
m_stArgNames | m_stArgNames4 | m_stArgNames12
m_stCategory | m_stCategory4 | m_stCategory12
m_stHelpText | m_stHelpText4 | m_stHelpText12
m_astArgHelpText | m_astArgHelpText4 | m_astArgHelpText12

Where possible you should replace use of the data members above with calls to the following functions. Each of these functions returns the value appropriate for the version of Excel which is currently running. In addition, these calls handle any localization that is required if the strings contain resource IDs.

Data member | Function call
m_stEntryPoint | GetEntryPoint()
m_stArgTemplate | GetArgumentTemplate()
m_stArgNames | GetArgumentName(), GetArgumentNames()
m_stCategory | GetCategory()
m_stHelpText | GetHelpText()
m_astArgHelpText | GetArgumentHelpText(), GetArgumentHelpTexts()

The following data members are no longer supported.

Data member | Replacement
m_astArgExt | m_stDefinition
m_stFnExt | m_stDefinition

Finally, the data member m_stName has changed type from a CString to a Unicode CStringW type. In particular, code that compares the name to an ANSI string will fail to compile, e.g.:

CopyC++
if (strcmp(pfn->m_stName, "MyFunc") == 0)

This comparison would need to be changed to:

CopyC++
if (wcscmp(pfn->m_stName, L"MyFunc") == 0)

CXlHandleStore::ObjectFromHandle

The method CXlHandleStore::ObjectFromHandle, which is used to convert Excel handles to object pointers, is no longer const. The signature has been changed to non-const because the CXlHandleStore is now thread-safe, and thus calls that were previously read-only now need to mutate the object in order to lock it.

GDI32 Linker Error

Projects that built perfectly with XLL+ 6.0 may fail to build with XLL+ 6.2, with the following linker errors.

CopyC++
xlllibsd.lib(WizardHook.obj) : error LNK2019: unresolved external symbol __imp__DeleteObject@4 referenced in function "public: void __thiscall CWizardHook::Uninstall(void)" (?Uninstall@CWizardHook@@QAEXXZ)
xlllibsd.lib(WizardHook.obj) : error LNK2019: unresolved external symbol __imp__CreateFontIndirectA@4 referenced in function "private: struct HFONT__ * __thiscall CWizardHook::CreateButtonFont(void)" (?CreateButtonFont@CWizardHook@@AAEPAUHFONT__@@XZ)
xlllibsd.lib(WizardHook.obj) : error LNK2019: unresolved external symbol __imp__SetBkMode@8 referenced in function "private: void __thiscall CWizardHook::DrawButton(int,struct tagDRAWITEMSTRUCT *)" (?DrawButton@CWizardHook@@AAEXHPAUtagDRAWITEMSTRUCT@@@Z)
xlllibsd.lib(WizardHook.obj) : error LNK2019: unresolved external symbol __imp__SelectObject@8 referenced in function "private: void __thiscall CWizardHook::DrawButton(int,struct tagDRAWITEMSTRUCT *)" (?DrawButton@CWizardHook@@AAEXHPAUtagDRAWITEMSTRUCT@@@Z)
xlllibsd.lib(WizardHook.obj) : error LNK2019: unresolved external symbol __imp__GetStockObject@4 referenced in function "private: void __thiscall CWizardHook::DrawButton(int,struct tagDRAWITEMSTRUCT *)" (?DrawButton@CWizardHook@@AAEXHPAUtagDRAWITEMSTRUCT@@@Z)

To resolve this problem add the library gdi32.lib to the list of Additional Dependencies in the Linker/Input page of the project's property pages.

Asynchronous functions

For XLL+ 6.2, the Asynchronous function implementation model was improved. Asynchronous versions of functions no longer take an extra argument "RtdSignal". If you have released add-ins with asynchronous functions, you should use the UseAsyncHandleModel to ensure that existing spreadsheets still continue to work correctly.

See Upgrading asynchronous functions from XLL+ 6.0 for details.

See Also

XLL+ Class Reference


How Do I...

The links below guide you through the common tasks you will need to do in order to build an XLL.

Creating an XLL+ project

Creating an XLL+ project in Visual Studio .NET or Visual Studio 2005.
Describes how to use the XLL+ AppWizard to create a new project in Visual Studio .NET or Visual Studio 2005.

Creating an add-in function

Creating an XLL+ add-in function
Describes how to use the XLL+ Function Wizard to create a new Excel add-in function.

Arguments and results

Passing vector arguments
This walkthrough describes how to use the XLL+ Function Wizard to pass vector arguments from Excel to an add-in function.
Returning a vector result
Describes how to return a one-dimensional array argument (a vector) from an add-in function.
Adding a matrix argument
Describes how to add a two-dimensional array argument (a matrix) to an add-in function.
Returning a matrix result
Describes how to return a two-dimensional array argument (a matrix) from an add-in function.
Value Lists
Describes how to restrict an argument to a limited set of values, like a C enumeration. Shows how to make these values appear in a drop-down list within the Excel Formula Wizard.
Object Handles
Discusses how to represent objects in Excel cells, as handles. Describes the various features of handles that XL+ supports.

XLL Add-ins Window

Showing the XLL Add-ins window
Describes how to show the XLL Add-ins window inside Visual Studio.

Deployment

Deploying an XLL
Discusses any additional steps required when deploying an XLL to a user's machine..

Function Wizard Features

Grouping multiple arguments into a single Excel range
Describes how to use the Function Wizard to create an add-in function that accepts and decodes multiple arguments in a single range, so as to reduce the total number of arguments to a function.
Improving performance by adding a results cache
Demonstrates how to use the Function Wizard to cache the results of any expensive calculation so that the results are instantaneous the next time the function is called with the same arguments.

Excel Features

Setting cell values
Describes how to change values directly in cells, other than by returning values from worksheet functions.

.NET

Importing a .NET Assembly
Describes how to import a .NET assembly, and automatically generate XLL add-in functions from its public methods and properties.

See Also

Samples and Walkthroughs | Sample applications | Walkthroughs | Example code | Frequently Asked Questions


Samples and Walkthroughs

XLL+ contains a wide variety of sample code. The links below will take you to lists of sample applications, walkthroughs and example code.

You can also find links to example code in the Examples section of class reference topics.

Sample applications | Complete sample applications
Walkthroughs | Step-by-step instructions for common scenarios
Example code | Functions and code fragments which illustrate a particular method


Sample Projects

The XLL+ sample projects are listed below, by category. Each can found in a sub-directory of the Samples directory.

  • Basic examples
  • Tutorials
  • Menus & Toolbars
  • Object handles
  • Interacting with Excel
  • Asynchronous functions
  • Common Language Runtime and .NET
  • Matrix adapter
  • Wrapper libraries
  • Dialogs
  • International support and localization
  • Advanced examples

Basic examples

SimpOpt
A typical calculator add-in, which values vanilla options
AvgOpt
An option value calculator add-in, which demonstrates the use of a results cache to speed up performance
LabelledArgs
A typical calculator add-in, using labelled arguments

Tutorials

Tutorial1
Contains most of the code from the User Guide
MfcTutorial
Contains the code for the MFC sample in the User Guide
AvgOpt
An option value calculator add-in, which demonstrates the use of a results cache to speed up performance

Menus & Toolbars

Ribbon Demo
Adds and manages controls in the Office Ribbon (New in XLL+ 7.0)
Simple Menus
Uses the CXlMenu class to add a menu to Excel's application menu bar
Advanced Menus
Adds a menu and dynamic sub-menus to Excel's application menu bar
Simple Toolbar
Uses the CXlToolbar class to add a toolbar to Excel's application window
Simple Toolbar using resources
Uses the CXlToolbar class to add a toolbar to Excel's application window
Dynamic Toolbar
Uses the CXlToolbar class to add a dynamic toolbar to Excel's application window

Object handles

RtdHandleDemo
Demonstrates the use of RTD handles to represent objects in Excel (New in XLL+ 6.2)
PersistentHandleDemo
Demonstrates the use of persistent RTD handles to represent objects in Excel (New in XLL+ 6.2)
MonteCarlo
Combines the use of object handles and asynchronous functions (Changed for XLL+ 6.2)
MonteCarlo2
Combines the use of object handles, and asynchronous functions, and also provides a persistent object cache (New in XLL+ 6.2)
NumericHandleDemo
Demonstrates the use of numeric handles to represent objects in Excel (New in XLL+ 6.0)
StringHandleDemo
Demonstrates the use of string handles to represent objects in Excel (New in XLL+ 6.0)
StringPtrHandleDemo
Demonstrates the use of string pointer handles to represent objects in Excel (New in XLL+ 6.0)
BoostHandles
Demonstrates the use of RTD handles to represent objects in Excel, where the objects are wrapped by boost::shared_ptr smart pointers (New in XLL+ 6.2)
ArrayHandles
Uses handles to represent vectors of numbers
LockableHandles
Demonstrates the use of RTD handles to represent objects in Excel (New in XLL+ 7.0)

Interacting with Excel

CallExcel
Demonstrates how to call Excel worksheet and macro functions from an add-in function
FindReplace
Uses the CXllFinder class to find and replace the contents of cells
ColorCell
Contains macro functions which set the colors of a cell
CreateBook
Demonstrates how to use CXlMacros methods to create and populate workbooks
SetFormula
Demonstrates how to set formulae
ExUIPopup
Demonstrates a popup editor within the Excel Formula Wizard (New in XLL+ 6.2)
ExUIPopupMFC
Demonstrates a popup editor within the Excel Formula Wizard (using MFC) (New in XLL+ 6.2)
ExUIPopupCLR
Demonstrates a popup editor within the Excel Formula Wizard (using .NET WinForms) (New in XLL+ 6.2)

Asynchronous functions

AvgOpt
An option value calculator add-in, which demonstrates the use of a results cache to speed up performance
MonteCarlo
Combines the use of object handles and asynchronous functions (Changed for XLL+ 6.2)
MonteCarlo2
Combines the use of object handles, and asynchronous functions, and also provides a persistent object cache (New in XLL+ 6.2)

Common Language Runtime and .NET

ClrDemo
Calls .NET methods from add-in functions
AssemblyDemo
Calls methods in a C# .NET assembly
PiaDemo
Uses the Excel object model, via the Primary Interop Assemblies

Matrix adapter

BoostMatrix
Demonstrates how to write a matrix adapter class, to integrate a matrix class into XLL+

Wrapper libraries

ApiTest
Demonstrates how to create a wrapper library which lets you call XLL Add-in functions directly from a C#, C++ or VBA application. (New in XLL+ 6.3)

Dialogs

Dialogs
Uses the CXlDialog class to display native Excel dialogs
Integration
Demonstrates how to create a meta-function from the relationship between two cells and use standard numerical methods to integrate the function

International support and localization

International
Demonstrates how to get and use Excel's international settings
Localized (Single DLL)
Demonstrates how to support multiple languages in a single XLL (Changed for XLL+ 6.0)
Localized (Multiple DLLs)
Demonstrates how to support multiple languages using one DLL per language (Changed for XLL+ 6.0)
Dynamic localized (Single DLL)
Demonstrates how to support multiple languages in a single XLL, switching between languages dynamically (New in XLL+ 6.0)
Dynamic localized (Multiple DLLs)
Demonstrates how to support multiple languages using one DLL per language, switching between languages dynamically (New in XLL+ 6.0)

Advanced examples

AvgOptCuda
An option value calculator add-in, which demonstrates the use of CUDA and a GPU to speed up performance
BoostMatrix
Demonstrates how to write a matrix adapter class, to integrate a matrix class into XLL+
CallExcel
Demonstrates how to call Excel worksheet and macro functions from an add-in function
UseTimer
Demonstrates how to use a timer to execute a macro function at regular intervals
PartialReg
Demonstrates how to control at run-time which add-in functions are registered and which are not
CreateBook
Demonstrates how to use CXlMacros methods to create and populate workbooks
BinaryData
Demonstrates the use of BinaryName ranges to store binary data in an invisible named range in a worksheet
CalcEvt
Demonstrates how to trap the OnCalculate event, and add your own data to a worksheet
SetFormula
Demonstrates how to set formulae
FInspect
Demonstrates how to inspect and display information about functions in an add-in (Changed for XLL+ 6.0)
Dialogs
Uses the CXlDialog class to display native Excel dialogs
Serialize
Demonstrates how to serialize Excel native data types to and from streams
Integration
Demonstrates how to create a meta-function from the relationship between two cells and use standard numerical methods to integrate the function
TFold
Demonstrates the use of the CXlOper class, in a useful worksheet function that constructs and manipulates arrays
Profiling
Demonstrates a function extension, which profiles the performance of add-in functions
LogDemo
An add-in that writes to a log
ExUIDynList
Changes the contents of a value list at run-time (New in XLL+ 6.2)
DemoFeed
Demonstrates how to integrate a data feed into an Excel add-in for high-performance real-time data add-in, written in C++, and which supports array real-time values as well as scalar values. (New in XLL+ 6.3)
ApiTest
Demonstrates how to create a wrapper library which lets you call XLL Add-in functions directly from a C#, C++ or VBA application. (New in XLL+ 6.3)
ExcepExt
Demonstrates a function extension, which catches a developer-defined exception
XlpGenDemo
Demonstrates how to use the XLPGEN.EXE command-line tool
Publish Opt-In Demo
Applies a function filter with an Opt-In policy
Publish Opt-Out Demo
Applies a function filter with an Opt-Out policy
Publish Run-time Demo
Applies a function filter using a configuration file
SharedHandles
Demonstrates how to share handles between separate add-ins

See Also

Samples and walkthroughs | Alphabetical List of Sample Projects


Alphabetical List of Sample Projects

The XLL+ sample projects are listed below, in alphabetical order. Each can found in a sub-directory of the Samples directory.

ApiTest
Demonstrates how to create a wrapper library which lets you call XLL Add-in functions directly from a C#, C++ or VBA application. (New in XLL+ 6.3)
ArrayHandles
Uses handles to represent vectors of numbers
AssemblyDemo
Calls methods in a C# .NET assembly
AvgOpt
An option value calculator add-in, which demonstrates the use of a results cache to speed up performance
AvgOptCuda
An option value calculator add-in, which demonstrates the use of CUDA and a GPU to speed up performance
BinaryData
Demonstrates the use of BinaryName ranges to store binary data in an invisible named range in a worksheet
BoostHandles
Demonstrates the use of RTD handles to represent objects in Excel, where the objects are wrapped by boost::shared_ptr smart pointers (New in XLL+ 6.2)
BoostMatrix
Demonstrates how to write a matrix adapter class, to integrate a matrix class into XLL+
CalcEvt
Demonstrates how to trap the OnCalculate event, and add your own data to a worksheet
CallExcel
Demonstrates how to call Excel worksheet and macro functions from an add-in function
ClrDemo
Calls .NET methods from add-in functions
ColorCell
Contains macro functions which set the colors of a cell
CreateBook
Demonstrates how to use CXlMacros methods to create and populate workbooks
DemoFeed
Demonstrates how to integrate a data feed into an Excel add-in for high-performance real-time data add-in, written in C++, and which supports array real-time values as well as scalar values. (New in XLL+ 6.3)
Dialogs
Uses the CXlDialog class to display native Excel dialogs
DynInterMulti - Dynamic localized (Multiple DLLs)
Demonstrates how to support multiple languages using one DLL per language, switching between languages dynamically (New in XLL+ 6.0)
DynInterSingle - Dynamic localized (Single DLL)
Demonstrates how to support multiple languages in a single XLL, switching between languages dynamically (New in XLL+ 6.0)
ExcepExt
Demonstrates a function extension, which catches a developer-defined exception
ExUIDynList
Changes the contents of a value list at run-time (New in XLL+ 6.2)
ExUIPopup
Demonstrates a popup editor within the Excel Formula Wizard (New in XLL+ 6.2)
ExUIPopupCLR
Demonstrates a popup editor within the Excel Formula Wizard (using .NET WinForms) (New in XLL+ 6.2)
ExUIPopupMFC
Demonstrates a popup editor within the Excel Formula Wizard (using MFC) (New in XLL+ 6.2)
FindReplace
Uses the CXllFinder class to find and replace the contents of cells
FInspect
Demonstrates how to inspect and display information about functions in an add-in (Changed for XLL+ 6.0)
Integration
Demonstrates how to create a meta-function from the relationship between two cells and use standard numerical methods to integrate the function
InterMulti - Localized (Multiple DLLs)
Demonstrates how to support multiple languages using one DLL per language (Changed for XLL+ 6.0)
International
Demonstrates how to get and use Excel's international settings
InterSingle - Localized (Single DLL)
Demonstrates how to support multiple languages in a single XLL (Changed for XLL+ 6.0)
LabelledArgs
A typical calculator add-in, using labelled arguments
LockableHandles
Demonstrates the use of RTD handles to represent objects in Excel (New in XLL+ 7.0)
LogDemo
An add-in that writes to a log
Menus - Simple Menus
Uses the CXlMenu class to add a menu to Excel's application menu bar
MfcTutorial
Contains the code for the MFC sample in the User Guide
MonteCarlo
Combines the use of object handles and asynchronous functions (Changed for XLL+ 6.2)
MonteCarlo2
Combines the use of object handles, and asynchronous functions, and also provides a persistent object cache (New in XLL+ 6.2)
NumericHandleDemo
Demonstrates the use of numeric handles to represent objects in Excel (New in XLL+ 6.0)
PartialReg
Demonstrates how to control at run-time which add-in functions are registered and which are not
PersistentHandleDemo
Demonstrates the use of persistent RTD handles to represent objects in Excel (New in XLL+ 6.2)
PiaDemo
Uses the Excel object model, via the Primary Interop Assemblies
Profiling
Demonstrates a function extension, which profiles the performance of add-in functions
PubDevIn - Publish Opt-In Demo
Applies a function filter with an Opt-In policy
PubDevOut - Publish Opt-Out Demo
Applies a function filter with an Opt-Out policy
PublishRT - Publish Run-time Demo
Applies a function filter using a configuration file
RibbonDemo - Ribbon Demo
Adds and manages controls in the Office Ribbon (New in XLL+ 7.0)
RtdHandleDemo
Demonstrates the use of RTD handles to represent objects in Excel (New in XLL+ 6.2)
Serialize
Demonstrates how to serialize Excel native data types to and from streams
SetFormula
Demonstrates how to set formulae
SharedHandles
Demonstrates how to share handles between separate add-ins
SimpOpt
A typical calculator add-in, which values vanilla options
StringHandleDemo
Demonstrates the use of string handles to represent objects in Excel (New in XLL+ 6.0)
StringPtrHandleDemo
Demonstrates the use of string pointer handles to represent objects in Excel (New in XLL+ 6.0)
SubMenus - Advanced Menus
Adds a menu and dynamic sub-menus to Excel's application menu bar
TFold
Demonstrates the use of the CXlOper class, in a useful worksheet function that constructs and manipulates arrays
Toolbar1 - Simple Toolbar
Uses the CXlToolbar class to add a toolbar to Excel's application window
Toolbar2 - Simple Toolbar using resources
Uses the CXlToolbar class to add a toolbar to Excel's application window
Toolbar3 - Dynamic Toolbar
Uses the CXlToolbar class to add a dynamic toolbar to Excel's application window
Tutorial1
Contains most of the code from the User Guide
UseTimer
Demonstrates how to use a timer to execute a macro function at regular intervals
XlpGenDemo
Demonstrates how to use the XLPGEN.EXE command-line tool

See Also

List of Sample Projects (Grouped by topic) | Samples and walkthroughs


Basic examples

This section contains the following samples:

SimpOpt
A typical calculator add-in, which values vanilla options
AvgOpt
An option value calculator add-in, which demonstrates the use of a results cache to speed up performance
LabelledArgs
A typical calculator add-in, using labelled arguments


AvgOpt Sample

An option value calculator add-in, which demonstrates the use of a results cache to speed up performance

Overview

This add-in contains a calculator for calculating the value of a complex option. It uses a results cache to speed up performance.

The calculation of the option value is very slow (since it uses a Monte-Carlo algorithm) and it is therefore worthwhile storing the results of calculations in a cache, and retrieving them if they are ever needed again. Since Excel often recalculates cells whose inputs have not changed, this technique offers a significant performance enhancement. The programming cost is zero, since the XLL+ AppWizard and Function Wizard generate and maintain all the code for using the cache.

Features

The sample displays the following features:

  • Uses a cache (CXlOperCache) to accelerate slow functions.
  • Saves the cache to disk and restores it each time the add-in is used.
  • Offers the user a menu to clear the cache.
  • Offers an asynchronous version of the function, which runs in a worker thread, and automatically updates the spreadsheet when it has completed.

Implementation

The following steps were significant in creating and completing the AvgOpt application.

  • When the AvgOpt project was generated by the XLL+ AppWizard, the Include a cache for results check-box was ticked, so that the cache object in the header file was included automatically. The Save the cache to file check-box was also ticked.

  • The Add a Menu check-box was ticked in the XLL+ AppWizard, so that code to create a menu was added to the project, in AvgOpt.cpp.

    The default menu captions and command name were changed in CAvgOptApp::OnXllOpen; the menu offers the user the option to clear the cache at any time.

    A new add-in function, AvgOptClearCache, was added, marked as a Macro Function in the XLL+ Function Wizard. The implementation calls the Clear() method of the application's cache object.

  • The add-in function AvgOptValue had several features added in the XLL+ Function Wizard, by checking four options on the Features tab.

    1. The function was marked as cached, by checking Cache results on the Features tab. Note that no coding on the part of the developer was required to make AvgOptValue a cached function; the Function Wizard generated it completely.

    2. A check was also put against Create asynchronous version", which caused a second function AvgOptValueAsync to be generated. This function returns immediately with the result #WAIT!, after dispatching the calculation to a background thread. In the meantime the spreadsheet remains available for use. The user can move about the sheet, and can even change cells. When the background thread completes the calculation, it informs Excel, which automatically updates the affected cells with the result of the calculation.

    3. A check was put against Do not call in Formula Wizard. This is an important behaviour for slow functions. Otherwise, the calculation is run in the Formula Wizard every time the user changes a value.

    4. Thread safe was also checked, to tell Excel that it is safe to call the AvgOptValue function from any number of different threads during calculation. In a spreadsheet which contains more than one instance of the formula, this can improve performance by up to 8 times.

Classes and functions used

CXlOperCache | CXlOperCache::Save | CXlOperCache::Restore | CXlOperCache::Clear | CXlOper::Format | CXlOper::Ret | CXlMenu | CXlMenu::SetTexts | CXlMenu::AddItem | CXlMenu::Create | CXlMenu::Destroy | CXllApp::WinMessageBox | ::XllGetTypedApp

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file AvgOpt.sln or the project file AvgOpt.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files AvgOpt.help.xml and AvgOpt.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


LabelledArgs Sample

A typical calculator add-in, using labelled arguments

Overview

This simple add-in contains a calculator for calculating the value and derivatives of a vanilla option, and is a simpler version of the function in the SimpOpt sample.

The BSValue2 function expects its arguments to be in two groups: RefArgs (which are the same for all options on the same underlying security) and StdArgs (which vary for each option). Each group of arguments is expected to be either in an ordered vector, or in a labelled two-column array.

The labelled layout is very flexible, and can also offer improved transparency to the user. Using labelled groups, the user can lay out arguments to suit their own purposes, rather than to suit the requirements of a particular calculator function. This is especially useful when different functions have different requirements for the order of arguments.

Features

The sample displays the following features:

  • The BSValue2 add-in function accepts two grouped arguments, RefArgs and StdArgs. The Function Wizard generated all the code that deals with extracting and validating values from the grouped arguments passed from Excel.
  • The automatically generated help file, LabelledArgs.chm contains complete descriptions of the grouped arguments, accessible from the Excel Formula Wizard.

Implementation

The following steps were significant in creating and completing the LabelledArgs application.

  1. Pre-cooked header and source files were added to the project, containing code for the business functions.
  2. The XLL+ Function Wizard was used to group the arguments and the wizard generated all the code required to unpack the values from the arrays passed by Excel.

Notes

The demonstration workbook, LabelledArgs.xls, shows how to use labelled arguments with the TFOLDT worksheet function for simple and powerful manipulation of large arrays of data.

Classes and functions used

CXlOper::Format | CXlOper::Ret

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file LabelledArgs.sln or the project file LabelledArgs.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files LabelledArgs.help.xml and LabelledArgs.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Groups (User Guide) | SimpOpt sample | TFOLD sample


SimpOpt Sample

A typical calculator add-in, which values vanilla options

Overview

This simple add-in contains a calculator for calculating the value and derivatives of a vanilla option.

It is typical of financial calculator add-ins, and offers a useful model for an XLL+ add-in which makes use of existing pure C libraries.

Features

The sample displays the following features:

  • The CfRevalCashflows add-in function accepts two vector arguments, of dates and cashflows. The Function Wizard generated all the code that deals with extracting and validating the vectors' values from the cell arrays passed by Excel.
  • The library includes a function which returns a range of values (BsCalc) and a set of functions (BsValue, BsDelta etc) which return only one value, extracted from the range returned by BsCalc.
  • The Div argument to the Black-Scholes functions is flexible. It can contain either a single number (representing dividend yield) or two columns containing the dates and values of predicted dividends.

Implementation

The following steps were significant in creating and completing the SimpOpt application.

  1. Pre-cooked header and source files were added to the project, containing code for the business functions.
  2. The Calendar functions (CalDiffYears, CalDiffDays, CalDaysInYear and CalDayCountText) were each implemented as a thin shell around existing business functions, with the majority of the code being generated by the XLL+ Function Wizard. This is typical of most real-world add-in functions.
  3. Each of Black-Scholes functions has the same arguments. Therefore only one was entered into the XLL+ Function Wizard. All the rest were created as clones of the first function, using the Copy signature from... field of the New Function dialog.
  4. Each of the single value Black-Scholes functions (BsValue, BsDelta etc) calls the array function (BsCalc), via CXlOper::CallAddin. The value of interest is then extracted from the array and returned to Excel.
  5. The BsCalc function, which returns an array, allocates the array with CXlOper::AllocArray and populates it using CXlOper::Cell.
  6. The Div argument to the Black-Scholes functions is specified as a CXlOper value type, meaning that it can contain any or no data. Code was written (in BsCalc_Impl) to examine the contents of the Div argument, and handle it differently depending on its shape.
  7. The Excel date functions (XlLSerialToDate and XlDateToLSerial) were used for all date conversions. This immunizes the code from the problem of the user setting an unusual zero date in Excel's options.

Porting from XLL+ 5

This project was upgraded from XLL+ 5.0 using the Upgrade Wizard. You can find the old version in the Backup directory underneath the project directory.

One (repeated) line of code was incompatible, and had to be changed by hand.

The calls to CXlOper::CallAddin() originally looked like this:

CopyC++
// Call the array version of the function
CXlOper xloCalc;
xloCalc.CallAddin(BsCalc(Spot, Put, Div, Borrow, ImpVol,
Strike, ValueDate, Maturity, RiskFree, DayCount));

The implementation function was renamed to BsCalc_Impl, and takes an extra first argument, xloResult, into which the result is put. The new version of the code therefore lookes like:

CopyC++
// Call the array version of the function
CXlOper xloCalc;
xloCalc.CallAddin(BsCalc_Impl(xloCalc, Spot, Put, Div, Borrow, ImpVol,
Strike, ValueDate, Maturity, RiskFree, DayCount));

See Breaking changes in the User Guide for more information.

Classes and functions used

CXlOper::IsDouble | CXlOper::ToDouble | CXlOper::IsArray | CXlOper::GetWidth | CXlOper::ReadVector | CXlOper::AllocArray | CXlOper::IsArray | CXlOper::Cell | CXlOper::CallAddin | CXlOper::RetString | CXlOper::Ret | ::XllGetTypedApp | CXlOperCache::Clear | ::XlLSerialToDate | ::XlDateToLSerial

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file SimpOpt.sln or the project file SimpOpt.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files SimpOpt.help.xml and SimpOpt.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


Tutorials

This section contains the following samples:

Tutorial1
Contains most of the code from the User Guide
MfcTutorial
Contains the code for the MFC sample in the User Guide
AvgOpt
An option value calculator add-in, which demonstrates the use of a results cache to speed up performance


MfcTutorial Sample

Contains the code for the MFC sample in the User Guide

Remarks

This project demonstrates the use of the Microsoft Foundation Classes in an XLL+ add-in.

Classes and functions used

CExcelWnd | CXllApp::OnXllOpenEx | ::XLL_FIX_STATE | ::XllGetApp | CXlOper::Ret

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file MfcTutorial.sln or the project file MfcTutorial.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files MfcTutorial.help.xml and MfcTutorial.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


Tutorial1 Sample

Contains most of the code from the User Guide

Remarks

This project contains examples of all of the most frequently used XLL+ classes and methods. Most of the code which is shown in the User Guide is contained in this project.

Classes and functions used

CXllApp::OnXllOpenEx | CXlOper::Ret | CXlOper::operator = | CXlOper::ReadVector | CXlOper::ReadMatrix | matrix<T>::rows | matrix<T>::cols | CXlOper::Format | matrix<T>::get_col_ptrs | ::XllGetApp | CXllApp::IsInFormulaWizard | CXllApp::GetCallerDims | CXlOper::AllocArray | CXlOper::Cell | CXlOper::MakeRef | CXlOper::SetValue

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file Tutorial1.sln or the project file Tutorial1.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files Tutorial1.help.xml and Tutorial1.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


Menus & Toolbars

This section contains the following samples:

Ribbon Demo
Adds and manages controls in the Office Ribbon (New in XLL+ 7.0)
Simple Menus
Uses the CXlMenu class to add a menu to Excel's application menu bar
Advanced Menus
Adds a menu and dynamic sub-menus to Excel's application menu bar
Simple Toolbar
Uses the CXlToolbar class to add a toolbar to Excel's application window
Simple Toolbar using resources
Uses the CXlToolbar class to add a toolbar to Excel's application window
Dynamic Toolbar
Uses the CXlToolbar class to add a dynamic toolbar to Excel's application window


Simple Menus Sample - Menus

Uses the CXlMenu class to add a menu to Excel's application menu bar

Remarks

This project demonstrates how to use the CXlMenu class to add a menu to Excel's main application menu bar, and how to remove it again.

Classes and functions used

CXlMenu | CXlMenu::SetTexts | CXlMenu::AddItem | CXlMenu::Create | CXlMenu::Destroy | CXllApp::OnXllOpenEx | CXllApp::OnXllClose

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file Menus.sln or the project file Menus.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files Menus.help.xml and Menus.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Advanced menus sample | Menus (User Guide)


Ribbon Demo Sample - RibbonDemo

Adds and manages controls in the Office Ribbon

Remarks

This project demonstrates how to add controls to the Office Ribbon and how to control their appearance and behavior from an OnRibbonEvent event handler.

Classes and functions used

CXllApp | CXllApp::OnRibbonEvent | CXllApp::InvalidateRibbon | CRibbonEvtParams | CRibbonEvtParams::GetCallback | CRibbonEvtParams::GetId | CRibbonEvtParams::GetPressed | CRibbonEvtParams::GetIndex

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file RibbonDemo.sln or the project file RibbonDemo.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files RibbonDemo.help.xml and RibbonDemo.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | The Ribbon (User Guide) | Ribbon Reference


Advanced Menus Sample - SubMenus

Adds a menu and dynamic sub-menus to Excel's application menu bar

Remarks

This project demonstrates how to use the CXlMenu class to add a menu with sub-menus to Excel's main application menu bar, and how to remove it again.

It also shows how to manipulate menus dynamically.

Classes and functions used

CXlMenu | CXlMenu::Create | CXlMenu::SetTexts | CXlMenu::AddItem | CXlMenu::Destroy | CXllApp::OnXllOpenEx | CXllApp::OnXllClose | CXlMenu::DeleteItem | CXlMenu::EnableItem | CXlMenu::GetCallingMenu

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file SubMenus.sln or the project file SubMenus.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files SubMenus.help.xml and SubMenus.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Simple menus sample | Menus (User Guide)


Simple Toolbar Sample - Toolbar1

Uses the CXlToolbar class to add a toolbar to Excel's application window

Remarks

This project demonstrates how to use the CXlToolbar class to add a toolbar to Excel's main window, and how to remove it again. The bitmaps for the toolbar's buttons are held in BMP files at run-time.

As part of the build, each of the bitmap files is copied to the target directory (alongside Toolbar1.xll).

Classes and functions used

CXlToolbar | CXlToolbar::AddToolbar | CXlToolbar::ShowToolbar | CXlToolbar::DeleteToolbar | CXlToolbar::AddTool | CXlToolbar::SetToolBitmap | CXllApp::OnXllOpenEx | CXllApp::OnXllClose

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file Toolbar1.sln or the project file Toolbar1.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files Toolbar1.help.xml and Toolbar1.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Simple Toolbar using resources | Dynamic Toolbar | Toolbars (User Guide)


Simple Toolbar using resources Sample - Toolbar2

Uses the CXlToolbar class to add a toolbar to Excel's application window

Remarks

This project demonstrates how to use the CXlToolbar class to add a toolbar to Excel's main window, and how to remove it again. The bitmaps for the toolbar's buttons are built into the add-in as resources.

Classes and functions used

CXlToolbar | CXlToolbar::AddToolbar | CXlToolbar::ShowToolbar | CXlToolbar::DeleteToolbar | CXlToolbar::AddTool | CXlToolbar::SetToolBitmap | CXllApp::OnXllOpenEx | CXllApp::OnXllClose

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file Toolbar2.sln or the project file Toolbar2.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files Toolbar2.help.xml and Toolbar2.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Simple Toolbar | Dynamic Toolbar | Toolbars (User Guide)


Dynamic Toolbar Sample - Toolbar3

Uses the CXlToolbar class to add a dynamic toolbar to Excel's application window

Remarks

This project demonstrates how to use the CXlToolbar class to add a toolbar to Excel's main window, and how to dynamically enable and press the buttons. The bitmaps for the toolbar's buttons are built into the add-in as resources.

Buttons 1 and 2 enable and disable button 3. Button 4 can be pressed down and up.

Classes and functions used

CXlToolbar | CXlToolbar::AddToolbar | CXlToolbar::ShowToolbar | CXlToolbar::DeleteToolbar | CXlToolbar::AddTool | CXlToolbar::SetToolBitmap | CXlToolbar::EnableTool | CXlToolbar::PressTool | CXllApp::OnXllOpenEx | CXllApp::OnXllClose

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file Toolbar3.sln or the project file Toolbar3.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files Toolbar3.help.xml and Toolbar3.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Simple Toolbar | Simple Toolbar using resources | Toolbars (User Guide)


Object handles

This section contains the following samples:

RtdHandleDemo
Demonstrates the use of RTD handles to represent objects in Excel (New in XLL+ 6.2)
PersistentHandleDemo
Demonstrates the use of persistent RTD handles to represent objects in Excel (New in XLL+ 6.2)
MonteCarlo
Combines the use of object handles and asynchronous functions (Changed for XLL+ 6.2)
MonteCarlo2
Combines the use of object handles, and asynchronous functions, and also provides a persistent object cache (New in XLL+ 6.2)
NumericHandleDemo
Demonstrates the use of numeric handles to represent objects in Excel (New in XLL+ 6.0)
StringHandleDemo
Demonstrates the use of string handles to represent objects in Excel (New in XLL+ 6.0)
StringPtrHandleDemo
Demonstrates the use of string pointer handles to represent objects in Excel (New in XLL+ 6.0)
BoostHandles
Demonstrates the use of RTD handles to represent objects in Excel, where the objects are wrapped by boost::shared_ptr smart pointers (New in XLL+ 6.2)
ArrayHandles
Uses handles to represent vectors of numbers
LockableHandles
Demonstrates the use of RTD handles to represent objects in Excel (New in XLL+ 7.0)


ArrayHandles Sample

Uses handles to represent vectors of numbers

Overview

This project demonstrates the use of handles to represent large data sets. Each handle represents a vector of numbers.

Object creation

Each vector is held in a NumericVector object; the NumericVector class is a thin wrapper around std::vector.

CopyC++
class NumericVector : public std::vector<double> {
public:
    NumericVector() { }
    NumericVector(const std::vector<double>& source)
    {
        assign(source.begin(), source.end());
    }
    NumericVector(size_t size)
    {
        resize(size);
    }
};

The add-in function CreateVector takes a vector of numbers as an argument, creates a NumericVector object, adds it to the object cache and returns a handle to the object.

CopyC++
CXlOper* CreateVector_Impl(CXlOper& xloResult, const CXlOper* numbers_op)
{
    // Input buffers
    std::vector<double> numbers;
    // Validate and translate inputs
    XlReadVector(*numbers_op, numbers, L"numbers", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC
    NumericVector* vec = new NumericVector(numbers);
    xloResult = psl::CreateHandleInCache(vec);
    return xloResult.Ret();
}

Using a handle

The add-in function UseVector1 takes a handle to a NumericVector as an argument, and returns the sum of the numbers in the vector. The XLL+ Function Wizard was used to declare the argument vec as of type Handle to NumericVector.

In the code below, note that the auto-generated code deals with all the work of converting the handle into a pointer to the cached NumericVector object. If the conversion fails, then an exception is thrown and the developer-defined code that uses vec is never reached.

CopyC++
CXlOper* UseVector1_Impl(CXlOper& xloResult, const CXlStringArg& vec_op)
{
    // Input buffers
    const NumericVector* vec;
    // Validate and translate inputs
    XlReadScalarEx(vec_op, vec, psl::HandleConverter<NumericVector >(),
        CScalarConvertParams<const NumericVector*>(L"vec", 0, 0, -1).
        SetStringParam(0, L"NumericVector"));
    // End of generated code
//}}XLP_SRC
    xloResult = std::accumulate(vec->begin(), vec->end(), 0.0);
    return xloResult.Ret();
}

Variable type argument

The add-in function UseVector2 uses a variable type argument, which can be either:

  1. a handle to a NumericVector object; or
  2. a one-dimensional array of numbers.

This behavior is achieved by defining the argument as a Choice type, which can be either a Double[] or a Handle to NumericVector, as shown below:

CopyC++
CXlOper* UseVector2_Impl(CXlOper& xloResult, const CXlOper* HandleOrArray)
{
    // Input buffers
    std::vector<double> numbers;
    const NumericVector* vec;
    // Validate and translate inputs
    int HandleOrArray__index = -1;
    if (HandleOrArray__index < 0) {
        try {
            XlReadVector(*HandleOrArray, numbers, L"numbers", XLA_TRUNC_ONEMPTY|
                XLA_TRUNC_ONBLANK);
            HandleOrArray__index = 0;
        } catch(...) {}
    }
    if (HandleOrArray__index < 0) {
        try {
            XlReadScalarEx(*HandleOrArray, vec, psl::HandleConverter<
                NumericVector >(), CScalarConvertParams<const NumericVector*>(
                L"vec", 0, 0, -1).SetStringParam(0, L"NumericVector"));
            HandleOrArray__index = 1;
        } catch(...) {}
    }
    if (HandleOrArray__index < 0)
        throw CXlChoiceFailedException("HandleOrArray");
    // End of generated code
//}}XLP_SRC
    const std::vector<double>* input = (HandleOrArray__index == 0)
            ? &numbers : (const std::vector<double>*)vec;
    xloResult = std::accumulate(input->begin(), input->end(), 0.0);
    return xloResult.Ret();
}

The auto-generated code shown above takes care of reading the argument into one of the variables numbers or vec. Note that the code sets the indicator variable HandleOrArray__index to either 0 or 1 to indicate which input variable was set. So the developer-provided code simply inspects HandleOrArray__index and uses the appropriate input variable:

CopyC++
const std::vector<double>* input = (HandleOrArray__index == 0)
    ? &numbers : (const std::vector<double>*)vec;

Classes and functions used

psl::CreateHandleInCache

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file ArrayHandles.sln or the project file ArrayHandles.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files ArrayHandles.help.xml and ArrayHandles.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


BoostHandles Sample

Demonstrates the use of RTD handles to represent objects in Excel, where the objects are wrapped by boost::shared_ptr smart pointers

Overview

This add-in contains the code referred to in the User Guide topic Specifying a smart pointer type.

The code is based on the RtdHandleDemo sample, with the following changes:

  1. RTDHANDLES_PTR_CLASS The macro RTDHANDLES_PTR_CLASS is used to define the smart pointer type used by the object cache:

    CopyC++
    #include <boost\shared_ptr.hpp>
#define RTDHANDLES_PTR_CLASS boost::shared_ptr
#include <extensions\rtdhandles.h>

    Note that this definition must appear before the includion of rtdhandles.h.

  2. psl::CreateHandleInCache The argument passed to the global function psl::CreateHandleInCache is a reference to a smart pointer, rather than a normal pointer:

    CopyC++
    CXlOper* Thing_Create_Impl(CXlOper& xloResult, const CXlStringArg& Name,
    long Value)
{
    // End of generated code
//}}XLP_SRC
    boost::shared_ptr<Thing> sp_thing(new Thing(Name, Value, CXlDate::Now()));
    xloResult = psl::CreateHandleInCache(sp_thing);
    return xloResult.Ret();
}

Requirements

To edit the functions in this add-in, you need to load the extension file RtdHandles.xpe. See Loading an extension file for instructions.

You should also make sure that none of the following extension files is loaded, since the various types of handles are mutually exclusive.

  • NumericHandles.xpe
  • StringHandles.xpe
  • StringPtrHandles.xpe

Notes

In order to build this sample project, you need to do the following:

  1. Download and install the boost libraries. (Visit http://www.boost.org.)

  2. In the project's list of Additional Include Directories, change the directory C:\3rdParty\boost_1_46_0 to the directory where you installed the boost libraries. (The directory you select should be the parent of the main boost sub-directory.)

Classes and functions used

psl::CreateHandleInCache

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file BoostHandles.sln or the project file BoostHandles.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files BoostHandles.help.xml and BoostHandles.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Specifying a smart pointer type | RtdHandleDemo sample


LockableHandles Sample

Demonstrates the use of RTD handles to represent objects in Excel

Overview

This add-in contains a lockable version of the object cache described in the User Guide topic Using object handles.

See the documentation for LockableHandleCache for details of the use pattern. You can find VBA code that makes of handle locks in the demo files LockableHandlesDemo.xls and LockableHandlesDemo.xlsm.

Requirements

To edit the functions in this add-in, you need to load the extension file RtdHandles.xpe. See Loading an extension file for instructions.

You should also make sure that none of the following extension files is loaded, since the various types of handles are mutually exclusive.

  • NumericHandles.xpe
  • StringHandles.xpe
  • StringPtrHandles.xpe

Classes and functions used

psl::CreateHandleInCache | LockableHandleCache<T>

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file LockableHandles.sln or the project file LockableHandles.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files LockableHandles.help.xml and LockableHandles.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Using object handles | NumericHandleDemo sample


MonteCarlo Sample

Combines the use of object handles and asynchronous functions

Overview

This add-in demonstrates the combined use of:

  • Object handles
  • Asynchronous functions

Requirements

To edit the functions in this add-in, you need to load the extension file RtdHandles.xpe. See Loading an extension file for instructions.

You should also make sure that none of the following extension files is loaded, since the various types of handles are mutually exclusive.

  • NumericHandles.xpe
  • StringHandles.xpe
  • StringPtrHandles.xpe

In addition, at run-time the RTD Async Function Server DLL, XllRtdLink.dll, should be registered. On a machine where the XLL+ toolkit has been installed, this DLL should already be registered. See Requirements for asynchronous functions for details.

At run-time the RTD Handle Server DLL, RtdHandleServer.dll, should be registered. On a machine where the XLL+ toolkit has been installed, this DLL should already be registered. See Object handles: Requirements and deployment for details.

Object handles

The main calculator function is MonteCarlo. This runs a MonteCarlo simulation and accumulates a set of results. The function returns this object to Excel as a handle, which is a representation of an external object - in this case a MCResults object.

The other functions are "getters" which take an object handle as an argument and return a property of the object:

  • MonteCarlo.Value
  • MonteCarlo.MinValue
  • MonteCarlo.MaxValue
  • MonteCarlo.AllValues

For a full discussion of object handles, refer to the topic Object handles in the XLL+ User Guide.

Asynchronous functions

An asynchronous version of MonteCarlo is available: MonteCarloAsync. This function returns #WAIT! when first called, and then dispatches the calculation to a background thread. When the thread completes the calculation the function is called again, and this time it returns a valid handle.

Excel remains available during the background thread calculation, and the user can continue to edit cells or to work in other workbooks, without waiting for the calculation to complete.

For more information on asynchronous functions see Asynchronous functions in the XLL+ User Guide.

Clearing the cache

When clearing the cache, the features must be cleared in the following order:

  1. RtdAsyncManager - first stop all running worker threads
  2. Results cache (if used)
  3. Handle cache

In this sample, the code is as follows:

CopyC++
CXllApp::Instance()->GetRtdAsyncManager()->Clear();
psl::ClearHandleCache<MCResults>();

Recalculation

Whenever a spreadsheet containing MCResults handles is reopened, you will notice that the formula is recalculated. This may not be desired behavior, particularly for slow expensive functions. See the MonteCarlo2 sample for a solution to this issue.

Classes and functions used

CXlRuntimeException | CXlOper::Ret

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file MonteCarlo.sln or the project file MonteCarlo.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files MonteCarlo.help.xml and MonteCarlo.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | MonteCarlo2 sample | Using object handles | Asynchronous functions


MonteCarlo2 Sample

Combines the use of object handles, and asynchronous functions, and also provides a persistent object cache

Overview

This add-in demonstrates the combined use of:

  • Object handles
  • Persistent object handles
  • Asynchronous functions

Requirements

To edit the functions in this add-in, you need to load the extension file RtdHandles.xpe. See Loading an extension file for instructions.

You should also make sure that none of the following extension files is loaded, since the various types of handles are mutually exclusive.

  • NumericHandles.xpe
  • StringHandles.xpe
  • StringPtrHandles.xpe

In addition, at run-time the RTD Async Function Server DLL, XllRtdLink.dll, should be registered. On a machine where the XLL+ toolkit has been installed, this DLL should already be registered. See Requirements for asynchronous functions for details.

At run-time the RTD Handle Server DLL, RtdHandleServer.dll, should be registered. On a machine where the XLL+ toolkit has been installed, this DLL should already be registered. See Object handles: Requirements and deployment for details.

Persistent objects

This project is identical to the MonteCarlo sample, with one difference: each MCResults object is saved to an object cache. As a result, when a spreadsheet is reopened, the MonteCarlo formula is not recalculated.

For a full discussion of persistent object handles, refer to the topic Persistent object handles in the XLL+ User Guide.

The code below is the entire implementation of the persistent object cache:

CopyC++
// Serialization functions for the MCResults class
inline CXlIStream& operator>>(CXlIStream& is, MCResults*& t)
{
    std::vector<double> values;
    is >> values;
    t = new MCResults(values);
    return is;
}
inline CXlOStream& operator<<(CXlOStream& os, const MCResults* t)
{
    os << t->AllValues();
    return os;
}

// A serialized object cache for PersistentThing instances
const TCHAR* pszCacheFile = _T("%TMP%\\MCResults_MonteCarlo2.dat");

psl::PersistentHandleCache<MCResults> thePersistentCache(
    NULL,         // Use the default handle formatter
    pszCacheFile, // Data file
    100,          // Maximum number of items in saved file
    0,            // Maximum age in seconds (ignored if 0)
    true);        // AutoSave

Clearing the cache

When clearing the cache, the features must be cleared in the following order:

  1. RtdAsyncManager - first stop all running worker threads
  2. Results cache (if used)
  3. Handle cache

In this sample, the code is as follows:

CopyC++
CXllApp::Instance()->GetRtdAsyncManager()->Clear();
psl::ClearHandleCache<MCResults>();

Classes and functions used

PersistentHandleCache<T> | CXlIStream | CXlOStream

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file MonteCarlo2.sln or the project file MonteCarlo2.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files MonteCarlo2.help.xml and MonteCarlo2.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | MonteCarlo sample | Persistent object handles | Asynchronous functions


NumericHandleDemo Sample

Demonstrates the use of numeric handles to represent objects in Excel

Overview

This add-in contains the code described in the User Guide topic Using object handles.

Numeric handles (as implemented in the NumericHandles.xpe extension) consist of the object's address in memory. This is the least verbose form of handle of the three styles available, but it can be hard for the user to debug, since the addresses are large meaningless numbers.

Requirements

To edit the functions in this add-in, you need to load the extension file NumericHandles.xpe. See Loading an extension file for instructions.

You should also make sure that none of the following extension files is loaded, since the various types of handles are mutually exclusive.

  • RtdHandles.xpe
  • StringHandles.xpe
  • StringPtrHandles.xpe

Classes and functions used

CXlOper::operator = | CXlOper::Ret

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file NumericHandleDemo.sln or the project file NumericHandleDemo.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files NumericHandleDemo.help.xml and NumericHandleDemo.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Using object handles | RtdHandleDemo sample | StringHandleDemo sample | StringPtrHandleDemo sample


PersistentHandleDemo Sample

Demonstrates the use of persistent RTD handles to represent objects in Excel

Overview

This add-in contains the code described in the User Guide topic Persistent object handles.

RTD handles (as implemented in the RtdHandles.xpe extension) are impermanent. When you reopen a workbook that contains RTD handles, they are all automatically refreshed - and any cell that depends on them is also recalculated.

This add-in demonstrates techniques for avoiding this recalculation by storing the objects themselves in persistent storage on disk.

  1. When the add-in is opened, all saved objects are reloaded from persistent storage on disk.
  2. When a workbook containing RTD handles is opened, the handle is searched for in the set that was loaded from persistent storage. If the handle is found, the object is restored to the object cache, and no recalculation takes place.
  3. If a handle is not found in storage, then it is recreated as usual, and the cells that depend on it are recalculated.
  4. When a workbook containing handles is saved, its handles are added to the persistent store in memory.
  5. When the add-in is closed, the persistent store is saved to disk.

Implementation

There are 2 steps required for implementing persistent object handle storage:

  1. Define streaming operators for the object to be saved. For an object of type T, these are:

    CopyC++
    CXlIStream& operator>>(CXlIStream& is, T*& t);
CXlOStream& operator<<(CXlOStream& os, const T* t)

    Note that the operators act on pointers to T, not to the objects directly.

  2. Create an instance of PersistentHandleCache<T>, and assign the location of the persistent storage file and the performance characteristics of the persistent cache.

Streaming operators

The object to be serialized is PersistentThing:

CopyC++
class PersistentThing {
public:
    PersistentThing(const TCHAR* name_, int value_, double created_)
      : name(name_), value(value_), created(created_)
    {
    }
    std::tstring name;
    int value;
    double created;
};

To serialize the object so that it can be saved to disk, the following operator overload is used:

CopyC++
inline CXlOStream& operator<<(CXlOStream& os, const PersistentThing* t)
{
    os << t->name << t->value << t->created;
    return os;
}

This is a simple object, and can be serialized easily by using the streaming operators for the built-in types std::tstring, int and double. The CXlOStream and CXlIStream classes contain many other useful streaming operators, including support for std::vector, std::map and matrices of type ple::imtx; so it is easy to serialize complex objects as well.

To deserialize the object from disk into memory, the following operator overload is used:

CopyC++
inline CXlIStream& operator>>(CXlIStream& is, PersistentThing*& t)
{
    std::tstring name;
    int value;
    double created;
    is >> name >> value >> created;
    t = new PersistentThing(name.c_str(), value, created);
    return is;
}

Note that the PersistentThing instance must be created on the heap, using new, and the passed pointer t is set to point to the new object.

An alternative approach might be to set the properties directly, after using a parameterless constructor, as follows:

CopyC++
inline CXlIStream& operator>>(CXlIStream& is, PersistentThing*& t)
{
    t = new PersistentThing();
    is >> t->name >> t->value >> t->created;
    return is;
}

PersistentHandleCache

In this sample the instance of PersistentHandleCache is declared globally; you could equally well make it a member variable of the application class.

The constructor includes all the run-time parameters required for the persistent cache:

CopyC++
const TCHAR* pszCacheFile = _T("%TMP%\\PersistentThings.dat");

psl::PersistentHandleCache<PersistentThing> thePersistentCache(
    NULL,         // Use the default handle formatter
    pszCacheFile, // Data file
    100,          // Maximum number of items in saved file
    0,            // Maximum age in seconds (ignored if 0)
    true);        // AutoSave

The path used for the location of the data file includes an environment variable, %TMP%. This will be expanded at run-time to a complete path. This is a sensible location to use for per-user storage, since the user will always have read and write permission to the location, regardless of the operating system or security setup.

The AutoSave parameter is set to true, which saves any further coding: the cache will be restored from file during the OnXllOpenEx() event and saved to file during the OnXllClose() event.

Requirements

To edit the functions in this add-in, you need to load the extension file RtdHandles.xpe. See Loading an extension file for instructions.

You should also make sure that none of the following extension files is loaded, since the various types of handles are mutually exclusive.

  • NumericHandles.xpe
  • StringHandles.xpe
  • StringPtrHandles.xpe

Classes and functions used

PersistentHandleCache<T> | CXlIStream | CXlOStream

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file PersistentHandleDemo.sln or the project file PersistentHandleDemo.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files PersistentHandleDemo.help.xml and PersistentHandleDemo.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Using object handles | RtdHandleDemo sample


RtdHandleDemo Sample

Demonstrates the use of RTD handles to represent objects in Excel

Overview

This add-in contains the code described in the User Guide topic Using object handles.

It contains four sets of add-in functions, each of which consists of a creator function (e.g. Thing.Create), which creates an object and returns it to Excel as a handle, and some "getter" functions, which return properties of the object (e.g. Thing.Value).

The three sets of functions demonstrate different handle techniques:

Object Functions Description

Thing

Thing.Create
Thing.Name
Thing.Value
Thing.CreationTime

The simple case: a Thing object is created, and is returned as a handle.

CachedThing

CachedThing.Create
CachedThing.Name
CachedThing.Value
CachedThing.CreationTime

The creator function CachedThing.Create is marked as Cache results. This means that no unnecessary objects are created: for any given set of constructor parameters, only one object is ever created.

See Combining handles with other features in the User Guide for more details.

CustomThing

CustomThing.Create
CustomThing.Name
CustomThing.Value
CustomThing.CreationTime

A custom formatter class CustomThingHandleFormatter is defined, and is applied to the object cache for CustomThings.

See Custom handles formats in the User Guide for more details.

map

Map.Create
Map.GetValue

The object created is a complex type, std::map<std::string, std::string>, which contains namespaces and a template with arguments. Note that as of XLL+ version 7.0.6 the generated code deals with this seamlessly.

You may encounter some warnings (warning C4503) when you compile the code. This is due to the length of the names of the templated types. As is normal with this warning, you can use a typdef to work around it; this also makes the code more readable.

Requirements

To edit the functions in this add-in, you need to load the extension file RtdHandles.xpe. See Loading an extension file for instructions.

You should also make sure that none of the following extension files is loaded, since the various types of handles are mutually exclusive.

  • NumericHandles.xpe
  • StringHandles.xpe
  • StringPtrHandles.xpe

Classes and functions used

psl::CreateHandleInCache | CHandleFormatter<T>

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file RtdHandleDemo.sln or the project file RtdHandleDemo.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files RtdHandleDemo.help.xml and RtdHandleDemo.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Using object handles | NumericHandleDemo sample | StringHandleDemo sample | StringPtrHandleDemo sample


StringHandleDemo Sample

Demonstrates the use of string handles to represent objects in Excel

Overview

This add-in contains code very similar to that described in the User Guide topic Using object handles. The difference is that it uses string handles instead.

String handles (as implemented in the StringHandles.xpe extension) consist of the object's name followed by its index within the list of all active handles. This is the easiest handle type for a user to "debug", since the numbers are manageably short, unlike the pointers which are used by the NumericHandles.xpe and StringPtrHandles.xpe extensions. However, this type of handle is slightly less robust than the other two styles, since it is possible for a handle which has been erroneously changed from a formula to a value to remain a valid - but misleading - handle value.

Requirements

To edit the functions in this add-in, you need to load the extension file StringHandles.xpe. See Loading an extension file for instructions.

You should also make sure that none of the following extension files is loaded, since the various types of handles are mutually exclusive.

  • RtdHandles.xpe
  • NumericHandles.xpe
  • StringPtrHandles.xpe

Changing handle type

The add-in functions in this sample were copied from the NumericHandleDemo sample. The following steps are required to change the handle type from numeric to string:

  1. Using the Tool/Options/XLL+/Extensions page, unload NumericHandles.xpe and load StringHandles.xpe.
  2. In the XLL Add-ins window, select all the add-in functions in the source file, and click the Regenerate functions command. All the handle code will be regenerated, and some argument types will be changed from numeric to string.
  3. At the top of the source file, remove the line: #include "extensions\NumericHandles.h".

The project can then immediately be rebuilt and run.

Classes and functions used

CXlOper::operator = | CXlOper::Ret

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file StringHandleDemo.sln or the project file StringHandleDemo.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files StringHandleDemo.help.xml and StringHandleDemo.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Using object handles | RtdHandleDemo sample | NumericHandleDemo sample | StringPtrHandleDemo sample


StringPtrHandleDemo Sample

Demonstrates the use of string pointer handles to represent objects in Excel

Overview

This add-in contains code very similar to that described in the User Guide topic Using object handles. The difference is that it uses string pointer handles instead.

String pointer handles (as implemented in the StringPtrHandles.xpe extension) consist of the object's name followed by its address in memory. This is a more verbose form of handle than the other two styles, but it is both robust and a little more transparent for the user than the purely numeric handle type.

Requirements

To edit the functions in this add-in, you need to load the extension file StringPtrHandles.xpe. See Loading an extension file for instructions.

You should also make sure that none of the following extension files is loaded, since the three types of handles are mutually exclusive.

  • NumericHandles.xpe
  • StringHandles.xpe

Changing handle type

The add-in functions in this sample were copied from the NumericHandleDemo sample. The following steps are required to change the handle type from numeric to string pointer:

  1. Using the Tool/Options/XLL+/Extensions page, unload NumericHandles.xpe and load StringPtrHandles.xpe.
  2. In the XLL Add-ins window, select all the add-in functions in the source file, and click the Regenerate functions command. All the handle code will be regenerated, and some argument types will be changed from numeric to string.
  3. At the top of the source file, remove the line: #include <extensions\NumericHandles.h>.

The project can then immediately be rebuilt and run.

Classes and functions used

CXlOper::operator = | CXlOper::Ret

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file StringPtrHandleDemo.sln or the project file StringPtrHandleDemo.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files StringPtrHandleDemo.help.xml and StringPtrHandleDemo.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Using object handles | RtdHandleDemo sample | NumericHandleDemo sample | StringHandleDemo sample


Interacting with Excel

This section contains the following samples:

CallExcel
Demonstrates how to call Excel worksheet and macro functions from an add-in function
FindReplace
Uses the CXllFinder class to find and replace the contents of cells
ColorCell
Contains macro functions which set the colors of a cell
CreateBook
Demonstrates how to use CXlMacros methods to create and populate workbooks
SetFormula
Demonstrates how to set formulae
ExUIPopup
Demonstrates a popup editor within the Excel Formula Wizard (New in XLL+ 6.2)
ExUIPopupMFC
Demonstrates a popup editor within the Excel Formula Wizard (using MFC) (New in XLL+ 6.2)
ExUIPopupCLR
Demonstrates a popup editor within the Excel Formula Wizard (using .NET WinForms) (New in XLL+ 6.2)


CallExcel Sample

Demonstrates how to call Excel worksheet and macro functions from an add-in function

Overview

This add-in uses the CXlFuncs and CXlMacros classes to call Excel worksheet and macro functions from an add-in function.

Classes and functions used

CXlMacros | CXlMacros::ActiveCell | CXlMacros::EvaluateIntl | CXlMacros::Alert | CXlMacros::WorkbookInsert | CXlMacros::FormulaArrayIntl | CXlFuncs | CXlFuncs::Offset | CXlFuncs::Today | CXlFuncs::Year | CXlFuncs::Roman | CXlFuncs::CellAddress | CXlFuncs::CellCol | CXlFuncs::CellColor | CXlFuncs::CellContents | CXlFuncs::CellFileName | CXlFuncs::CellFormat | CXlFuncs::CellParentheses | CXlFuncs::CellPrefix | CXlFuncs::CellProtect | CXlFuncs::CellRow | CXlFuncs::CellType | CXlFuncs::CellWidth | CXlOper::MakeRef | CXlOper::SetValue | CXlOper::RetError | CXlOper::Ret

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file CallExcel.sln or the project file CallExcel.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files CallExcel.help.xml and CallExcel.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


ColorCell Sample

Contains macro functions which set the colors of a cell

Remarks

This project contains a macro function, ColorCells(...), which sets the foreground and background colors of the active cell.

It also contains a function to show the numeric index which represents the color of the active cell.

Classes and functions used

CXlMacros::Patterns | CXlMacros::FontProperties | CXlMacros::GetCell

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file ColorCell.sln or the project file ColorCell.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files ColorCell.help.xml and ColorCell.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


CreateBook Sample

Demonstrates how to use CXlMacros methods to create and populate workbooks

Remarks

This project contains several macro functions which create workbooks, adds worksheets and populates them. It demonstrates the use of the CXlMacros class.

Classes and functions used

CXlMacros | CXlMacros::NewDefaultWorkbook | CXlMacros::NewSingleSheetWorkbook | CXlMacros::Open | CXlMacros::WorkbookGetWorksheetNames | CXlMacros::WorkbookActivate | CXlMacros::WorkbookInsert | CXlMacros::GetActiveWorkbookName | CXlMacros::GetActiveWorksheetName | #ERROR Uses not found for CXlMacros_WorkbookGetWorksheetCount | CXlMacros::WorkbookMove | CXlOper::MakeRef | CXlOper::SetValue

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file CreateBook.sln or the project file CreateBook.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files CreateBook.help.xml and CreateBook.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


ExUIPopup Sample

Demonstrates a popup editor within the Excel Formula Wizard

Overview

This project demonstrates how to show a popup editor for an argument in the Excel Formula Wizard. It contains a single worksheet function, SimulateLife.

A class CFileNamePopupProvider is defined, which is derived from CXlWizExUIPopupProviderBase, and implements the virtual function Edit.

CFileNamePopupProvider

CFileNamePopupProvider::Edit does the 3 steps required of an editor.

  1. Creates a dialog (in this case by initializing an OPENFILENAME structure) and initializes the values in the dialog (in this case, by setting the file name to be the value of strValue passed to Edit).
  2. Shows the dialog.
  3. If the user selects a file, sets strValue and returns true. The file name is surrounded by quotes, so that it is a legal Excel string value. If the user presses Cancel, then Edit returns false.

Note that CFileNamePopupProvider contains a data member, m_strTitle, which will be displayed in the title of the file dialog. This member can be set to be different for each of the arguments for which this editor is provided.

CopyC++
virtual bool Edit(CString& strValue, HWND hwndParent)
{
    // Setup a file dialog
    TCHAR achFileName[MAX_PATH + 1];
    OPENFILENAME ofn;
    // ... omitted for brevity

    // Clean up strValue
    // ... omitted for brevity

    // Show file dialog
    BOOL ok = ::GetSaveFileName(&ofn);

    // Copy results to output
    if (ok)
    {
        strValue = CString(_T("\"")) + achFileName + _T("\"");
        return true;
    }
    else
        return false;
}

Registering the popup provider

To register the popup editor, an instance of CXlWizExUIArgumentPopupCreator is declared at global scope. The arguments to the constructor include (i) the name of the add-in function for which the editor is being registered, (ii) the index of the argument to which it applies and (iii) an instance of the popup provider, CFileNamePopupProvider.

Note that a specialized title is provided in the constructor of CFileNamePopupProvider, which applies only to the popup editor for this specific argument (DataFile in SimulateLife). In this case the title is "Select a data file".

Note that the developer is responsible for constructing the instance of CFileNamePopupProvider, but the framework is responsible for destroying it. For this reason, if a destructor is provided for a popup provider class, it must be declared as virtual.

Classes and functions used

CXlWizExUIPopupProviderBase | CXlWizExUIPopupProviderBase::Edit | CXlWizExUIArgumentPopupCreator | CXlWizExUIArgumentPopupCreator::CXlWizExUIArgumentPopupCreator

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file ExUIPopup.sln or the project file ExUIPopup.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files ExUIPopup.help.xml and ExUIPopup.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Popup Editors (User Guide) | ExUIPopupMFC sample | ExUIPopupClr sample


ExUIPopupCLR Sample

Demonstrates a popup editor within the Excel Formula Wizard (using .NET WinForms)

Overview

This project demonstrates how to show a popup editor for an argument in the Excel Formula Wizard, using the .NET Common Language Runtime, including WinForms. It contains a single worksheet function, SimulateLife.

A class CFileNamePopupProvider is defined, which is derived from CXlWizExUIPopupProviderBase, and implements the virtual function Edit.

Project setup

In order to make this project build and run, the following steps were required:

  • Check the /clr option in the XLL+ Application Wizard.
  • Add references to System.dll and System.Windows.Forms.dll, which can be found in the ".NET" page of the "Add New Reference..." dialog. (You can add an assembly reference by opening the "Common Properties/References" page of the Project Properties dialog and clicking "Add New Reference...".)
  • For programming convenience, add the line using namespace System::Windows::Formws;
  • For access to the class WinWrapper, add the line #include <xlpclrforms.h>.

CFileNamePopupProvider

CFileNamePopupProvider::Edit does the 3 steps required of an editor.

  1. Creates a dialog (in this case by initializing a SaveFileDialog object) and initializes the values in the dialog (in this case, by setting the file name to be the value of strValue passed to Edit).
  2. Shows the dialog.
  3. If the user selects a file, sets strValue and returns true. The file name is surrounded by quotes, so that it is a legal Excel string value. If the user presses Cancel, then Edit returns false.

Note that CFileNamePopupProvider contains a data member, m_strTitle, which will be displayed in the title of the file dialog. This member can be set to be different for each of the arguments for which this editor is provided.

The helper class WinWrapper is used to create a temporary parent form for the dialog.

CopyC++
virtual bool Edit(CString& strValue, HWND hwndParent)
{
    try
    {
        SaveFileDialog^ fd = gcnew SaveFileDialog();
        fd->FileName = toClr(strValue)->Replace(_T("\""), _T(""));
        fd->Filter = toClr(_T("Text files (*.txt)|*.txt|All files|*.*"));
        fd->OverwritePrompt = false;
        if (m_strTitle.GetLength() > 0)
            fd->Title = toClr(m_strTitle);
        if (fd->ShowDialog(gcnew XllPlus::Forms::WinWrapper(hwndParent)) == DialogResult::OK)
        {
            strValue = toXl(toClr(_T("\"")) + fd->FileName + toClr(_T("\"")));
            return true;
        }
    }
    catch(System::Exception^)
    {
    }
    return false;
}

Registering the popup provider

To register the popup editor, an instance of CXlWizExUIArgumentPopupCreator is declared at global scope. The arguments to the constructor include (i) the name of the add-in function for which the editor is being registered, (ii) the index of the argument to which it applies and (iii) an instance of the popup provider, CFileNamePopupProvider.

Note that a specialized title is provided in the constructor of CFileNamePopupProvider, which applies only to the popup editor for this specific argument (DataFile in SimulateLife). In this case the title is "Select a data file".

Note that the developer is responsible for constructing the instance of CFileNamePopupProvider, but the framework is responsible for destroying it. For this reason, if a destructor is provided for a popup provider class, it must be declared as virtual.

Classes and functions used

CXlWizExUIPopupProviderBase | CXlWizExUIPopupProviderBase::Edit | CXlWizExUIArgumentPopupCreator | CXlWizExUIArgumentPopupCreator::CXlWizExUIArgumentPopupCreator | WinWrapper

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file ExUIPopupCLR.sln or the project file ExUIPopupCLR.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files ExUIPopupCLR.help.xml and ExUIPopupCLR.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Popup Editors (User Guide) | ExUIPopup sample | ExUIPopupMFC sample


ExUIPopupMFC Sample

Demonstrates a popup editor within the Excel Formula Wizard (using MFC)

Overview

This project demonstrates how to show a popup editor for an argument in the Excel Formula Wizard, using the Microsoft Foundation Classes (MFC). It contains a single worksheet function, SimulateLife.

A class CFileNamePopupProvider is defined, which is derived from CXlWizExUIPopupProviderBase, and implements the virtual function Edit.

CFileNamePopupProvider

CFileNamePopupProvider::Edit does the 3 steps required of an editor.

  1. Creates a dialog (in this case by initializing a CFileDialog object) and initializes the values in the dialog (in this case, by setting the file name to be the value of strValue passed to Edit).
  2. Shows the dialog.
  3. If the user selects a file, sets strValue and returns true. The file name is surrounded by quotes, so that it is a legal Excel string value. If the user presses Cancel, then Edit returns false.

Note that CFileNamePopupProvider contains a data member, m_strTitle, which will be displayed in the title of the file dialog. This member can be set to be different for each of the arguments for which this editor is provided.

CopyC++
virtual bool Edit(CString& strValue, HWND hwndParent)
{
    // Fix the scope of the MFC DLL
    XLL_FIX_STATE;

    // Clean up strValue
    CString strFileName;
    // ... Omitted for brevity

    // Create an MFC wrapper for the parent window
    CWndAdapter wndParent(hwndParent);

    // Set up a file dialog
    CFileDialog fd(FALSE, 0, (LPCTSTR)strFileName,
        OFN_HIDEREADONLY | OFN_PATHMUSTEXIST,
        _T("Text files (*.txt)|*.txt|All files|*.*||"),
        &wndParent);

    // Show file dialog
    if (fd.DoModal() == IDOK)
    {
        // Copy user's selection to output, with quotes
        strValue.Format(_T("\"%s\""), fd.GetPathName());
        return true;
    }
    else
        return false;
}

Attaching to the HWND

A helper class CWndAdapter is provided, which creates a CWnd object for the supplied HWND hwndParent, but does not destroy the HWND when it goes out of scope (as the standard CWnd constructor would do).

Registering the popup provider

To register the popup editor, an instance of CXlWizExUIArgumentPopupCreator is declared at global scope. The arguments to the constructor include (i) the name of the add-in function for which the editor is being registered, (ii) the index of the argument to which it applies and (iii) an instance of the popup provider, CFileNamePopupProvider.

Note that a specialized title is provided in the constructor of CFileNamePopupProvider, which applies only to the popup editor for this specific argument (DataFile in SimulateLife). In this case the title is "Select a data file".

Note that the developer is responsible for constructing the instance of CFileNamePopupProvider, but the framework is responsible for destroying it. For this reason, if a destructor is provided for a popup provider class, it must be declared as virtual.

Classes and functions used

CXlWizExUIPopupProviderBase | CXlWizExUIPopupProviderBase::Edit | CXlWizExUIArgumentPopupCreator | CXlWizExUIArgumentPopupCreator::CXlWizExUIArgumentPopupCreator

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file ExUIPopupMFC.sln or the project file ExUIPopupMFC.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files ExUIPopupMFC.help.xml and ExUIPopupMFC.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Popup Editors (User Guide) | ExUIPopup sample | ExUIPopupClr sample


FindReplace Sample

Uses the CXllFinder class to find and replace the contents of cells

Remarks

This project contains a single macro function which finds and replaces text in worksheet cells. It demonstrates the use of the CXllFinder class.

Classes and functions used

CXllFinder | CXllFinder::FindNext | CXllFinder::GetCurrentValue | CXllFinder::SetCurrentValue

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file FindReplace.sln or the project file FindReplace.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files FindReplace.help.xml and FindReplace.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


SetFormula Sample

Demonstrates how to set formulae

Overview

This sample add-in shows how to use the CXlOper class to set the formula of a cell, using various techniques.

Breaking changes

In the original version of this sample, the non-const version of CXlOper::GetRef() was used to change the cell of a reference CXlOper "in-place". This technique is no longer available, and the replacement method CXlOper::MoveRefBy has been used instead. Please see Breaking changes - GetRef for details.

Classes and functions used

CXlOper::SetFormula | CXlOper::SetFormulaIntl | CXlOper::SetLongFormula | CXlOper::SetLongFormulaIntl | CXlOper::ConvertFormula | CXlOper::ConvertFormulaIntl | CXlOper::MoveRefBy

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file SetFormula.sln or the project file SetFormula.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files SetFormula.help.xml and SetFormula.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


Asynchronous functions

This section contains the following samples:

AvgOpt
An option value calculator add-in, which demonstrates the use of a results cache to speed up performance
MonteCarlo
Combines the use of object handles and asynchronous functions (Changed for XLL+ 6.2)
MonteCarlo2
Combines the use of object handles, and asynchronous functions, and also provides a persistent object cache (New in XLL+ 6.2)


Common Language Runtime and .NET

This section contains the following samples:

ClrDemo
Calls .NET methods from add-in functions
AssemblyDemo
Calls methods in a C# .NET assembly
PiaDemo
Uses the Excel object model, via the Primary Interop Assemblies


AssemblyDemo Sample

Calls methods in a C# .NET assembly

Overview

This project contains three add-in functions that call methods in an associated .NET class library (MyAssembly), authored in C#.

For more information on using your own or 3rd-party .NET assemblies from add-in functions, see Deploying your .NET assemblies in the User Guide.

Run-time requirements

Please note that if you are using Visual Studio 2005, you must have Service Pack 1 installed in order to build a valid XLL.

If the sample fails to load into Excel at run-time, please see the technical note .NET requirements.

In order to build MyAssembly.dll, you need the C# project system to be installed on your computer.

Project setup

In order to make this project build and run, the following steps were required:

  • Check the /clr option in the XLL+ Application Wizard.
  • Add a reference to MyAssembly.dll, so that the associated .NET class library is available. (You can add an assembly reference by opening the "Common Properties/References" page of the Project Properties dialog and clicking "Add New Reference...".)

The add-in expects to find the associated .NET class library (MyAssembly.dll) in its own directory, so the Visual Studio solution is configured to deliver the XLL and the .NET assembly to the same directory.

Note that if you wanted to deploy the .NET assembly to a different directory, you could call CXllApp::SetPrivateBinPath() during the XllOpenEx event, to specify the directory or directories where the XLL will search for .NET assemblies.

MyCalculation

The add-in function MyCalculation calls a static .NET method: public static double[,] MyCalculation(double[] vector, double[,] matrix).

The array inputs, AddedVector and Matrix, are converted to .NET arrays using the conversion function ple::clr::toClr().

The array that is returned by the .NET function is converted to a C++ matrix using another conversion function, ple::clr::toXl()

CopyC++
array<double, 2>^ resultArray = MyAssembly::MyStaticClass::MyCalculation(
    toClr(AddedVector), toClr(Matrix));
xloResult = toXl(resultArray);

Because MyAssembly::MyStaticClass::MyCalculation expects the vector to be the same size as the height of the matrix, the XLL+ Function Wizard was used to add a constraint to the height of the matrix.

RevalPayments

The add-in function RevalPayments calls another static .NET method:

CopyC#
public static double RevalPayments(DateTime[] dates, double[] amounts,
    double riskFree, DateTime revalDate)

The helper function ple::clr::toClrDates() is used to convert the date array from Excel's numeric format to an array of System::DateTime values. In addition, ple::clr::toClrDate() is used to convert the ValueDate input, and ple::clr::toClr(<T>) is used to convert the vector of values to a .NET array.

CopyC++
CXlOper* RevalPayments_Impl(CXlOper& xloResult, const CXlOper* Dates_op,
    const CXlOper* Amounts_op, double RiskFree, long ValueDate)
{
    ...
    //}}XLP_SRC
    xloResult = MyAssembly::MyStaticClass::RevalPayments(
      toClrDates(Dates),
      toClr(Amounts),
      RiskFree,
      toClrDate(ValueDate));
    return xloResult.Ret();
}

Again, the XLL+ Function Wizard was used to add a constraint to the sizes of the two vector arguments.

PrefixArray

The add-in function PrefixArray creates an instance of a .NET class, calls a method, and returns the result.

Again, the conversion helper functions toClr() and toXl() are used to convert inputs and outputs respectively.

CopyC++
// Create an instance of a .NET class
MyAssembly::MyClass^ instance = gcnew MyAssembly::MyClass(toClr(Prefix));
// Use an instance method of the class, and return the result to Excel.
xloResult = toXl(instance->AddPrefix(toClr(StringArray)));

Classes and functions used

ple::clr::toClr | ple::clr::toClrDate | ple::clr::toClrDates | ple::clr::toXl

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file AssemblyDemo.sln or the project file AssemblyDemo.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files AssemblyDemo.help.xml and AssemblyDemo.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


ClrDemo Sample

Calls .NET methods from add-in functions

Run-time requirements

Please note that if you are using Visual Studio 2005, you must have Service Pack 1 installed in order to build a valid XLL.

If the sample fails to load into Excel at run-time, please see the technical note .NET requirements.

Remarks

This project contains two add-in functions that use the Common Language Runtime and the .NET class libraries.

For more information on calling .NET code from add-in functions, see Using .NET and the Common Language Runtime in the User Guide.

The worksheet function ClrDate converts an Excel date to an instance of System::DateTime, and then uses the method System::DateTime::ToString(format) to return a CLR formatted date string.

CopyC++
CXlOper* ClrDate_Impl(CXlOper& xloResult, double date,
    const CXlStringArg& format)
{
    // End of generated code
    //}}XLP_SRC
    // Call a CLR method, using toClr() to translate the arguments
    // & toXl() to translate the result.
    xloResult = toXl(toClrDate(date).ToString(toClr(format)));
    return xloResult.Ret();
}

Inputs are converted to CLR types using the global functions toClr() and toClrDate(). The output of the CLR method (a System::String) is converted back to an Excel string using toXl().

The macro command ShowDialog calls the WinForms library method System::Windows::Forms::MessageBox::Show. An instance of ExcelForm is created, to pass the Excel application window's handle to the WinForms library, so that the message box has the correct owner window.

CopyC++
CXlOper* ShowDialog_Impl(CXlOper& xloResult)
{
    // End of generated code
    //}}XLP_SRC

    // Call a WinForms method, using a new instance of
    // the ExcelForm to create an IWin32Window interface
    // for the main Excel application window.
    MessageBox::Show(
        gcnew XllPlus::Forms::ExcelForm(),
        "Hello from .NET", ".NET message box",
        MessageBoxButtons::OK,
        MessageBoxIcon::Hand);
    return xloResult.Ret();
}

Requirements

In order to make this project build and run, the following step was required:

  • Check the /clr option in the XLL+ Application Wizard.

The following steps were required in order to use WinForms:

  • Add a reference to system.windows.forms.dll, so that the WinForms library is available. (You can add an assembly reference by opening the "Common Properties/References" page of the Project Properties dialog and clicking "Add New Reference...".)
  • Add #include <xlpclrforms.h> to ClrDemo.cpp, to gain access to the ExcelForm class.
  • For convenience, the statement using namespace System::Windows::Forms; was added.

Classes and functions used

ExcelForm | ple::clr::toClr | ple::clr::toClrDate | ple::clr::toXl

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file ClrDemo.sln or the project file ClrDemo.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files ClrDemo.help.xml and ClrDemo.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


PiaDemo Sample

Uses the Excel object model, via the Primary Interop Assemblies

Overview

This project shows how to gain access to the Excel object model in C++/CLI, and how to use Excel object model classes, properties and methods to create, format and populate a workbook.

For more information on using the Excel object model via .NET, see Using the Excel object model in the User Guide.

Run-time requirements

Please note that if you are using Visual Studio 2005, you must have Service Pack 1 installed in order to build a valid XLL.

If the sample fails to load into Excel at run-time, please see the technical note .NET requirements.

This sample contains its own copy of the .NET Primary Interop Assemblies for Excel. If you already have these assemblies installed into the GAC, you can remove these assemblies, and replace the reference to the private assembly with a reference to the installed version as described below.

Project setup

In order to make this project build and run, the following steps were required:

  • Check the /clr option in the XLL+ Application Wizard.
  • Add a reference to Microsoft.Office.Interop.Excel.dll, which can be found in the ".NET" page of the "Add New Reference..." dialog. (You can add an assembly reference by opening the "Common Properties/References" page of the Project Properties dialog and clicking "Add New Reference...".)
  • For programming convenience, add the line using namespace Microsoft::Office::Interop::Excel;

Application object

The add-in function UseObjectModel first gets a handle to the Excel Application object from the XLL+ framework, and casts it to an _Application interface:

CopyC++
_Application^ theApp = safe_cast<_Application^>(
    CXllApp::Instance()->GetApplicationObject());
if (theApp == nullptr)
    return CXlOper::RetError(xlerrNA);

Note the use of safe_cast to safely cast the application object.

If the interface cannot be found, the function aborts.

Using the object model

The add-in function then calls various objects, properties and methods of the Excel object model to create, format and populate a new workbook.

CopyC++
// Create a new workbook
theApp->Workbooks->Add(System::Reflection::Missing::Value);

// Create a range that points to the 4 cells in the top-left corner
_Worksheet^ ws = safe_cast<_Worksheet^>(theApp->ActiveSheet);
Range^ range = safe_cast<Range^>(ws->Cells[1, 1])->Resize[2, 2];

// Apply values and formats to the range
range->Interior->ColorIndex = 4;
range->Interior->Pattern = Constants::xlSolid;
range->Font->ColorIndex = 3;
range->Value2 = "A value";

// Select C3:D4
range->Offset[2, 2]->Select();

A number of points are worth noting here:

  • Missing values are represented by System::Reflection::Missing::Value. They cannot simply be omitted.
  • A number of properties in the Excel model, including Application.ActiveSheet and Range.Cells, return untyped objects. You need to use safe_cast to convert them to the appropriate interface.
  • Many methods are unexpectedly implemented as properties. Range.Resize is a commonly used example of this.
  • The class Microsoft::Office::Interop::Excel::Constants contains many of the Excel constants.

Classes and functions used

CXllApp::GetApplicationObject

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file PiaDemo.sln or the project file PiaDemo.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files PiaDemo.help.xml and PiaDemo.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


Matrix adapter

This section contains the following samples:

BoostMatrix
Demonstrates how to write a matrix adapter class, to integrate a matrix class into XLL+


BoostMatrix Sample

Demonstrates how to write a matrix adapter class, to integrate a matrix class into XLL+

Overview

This add-in demonstrates how to integrate matrix classes into XLL+.

The example uses the boost::multi_array class as its matrix container. A simple adapter class, mtx_multi_array_adapter<T>, is created, which provides a bridge between the ple::imtx<T> interface, which is used by the XLL+ data validation functions, and the boost::multi_array<T, 2> template class.

Boost

See the boost web-site at http://www.boost.org/libs/multi_array/doc/index.html for more information about the multi_array class. Visit http://www.boost.org to download a copy of the latest version of the boost libraries.

Features

The sample displays the following features:

  • An add-in function delivers an Excel array argument directly into a matrix of type boost::multi_array<double, 2>. All the code for this is generated by the XLL+ Function Wizard.
  • An add-in function returns a boost matrix value to Excel, using an adapter class and the CXlOper = operator.

Setting the container of a matrix argument

In the example function, MyMatrixAdd, the two matrix arguments were amended in the XLL+ Function Wizard, as shown below:

Argument Details window with Container field populated

The container class for the first argument was typed into the Container field. For the second argument, it appears in the drop-down, which saves on typing and reduces errors.

Argument Details window with Container drop-down

As a result of the change to the arguments' container class, slightly different code was generated by the XLL+ Function Wizard:

CopyC++
CXlOper* MyMatrixAdd_Impl(CXlOper& xloResult, const CXlOper* A_op,
    const CXlOper* B_op)
{
    // Input buffers
    boost::multi_array<double, 2> A;
    boost::multi_array<double, 2> B;
    // Named bounds
    long heightOfA = -1;
    long widthOfA = -1;
    // Validate and translate inputs
    XlReadMatrix(*A_op, mtx_adapter(A), L"A", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK|XLA_FLAG_REJECT_NULL_ARRAY, &heightOfA, 0, &widthOfA);
    XlReadMatrix(*B_op, mtx_adapter(B), L"B", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK|XLA_FLAG_REJECT_NULL_ARRAY, &heightOfA, 0, &widthOfA);
    // End of generated code
    //}}XLP_SRC

The only difference between this code and the standard wizard-generated code is in the declaration of the local variables that hold the matrix values. Instead of the standard ple::mtx_ptrs container, boost::multi_array is used.

The global function mtx_adapter is called, which creates an adapter for the multi_array instance and passes that to the validation function, XlReadMatrix.

For more about setting an argument's container class, see Matrix containers in the User Guide.

Returning a matrix value to Excel

The sample function uses the two input matrices, A and B, and adds them to make a third matrix, C, also of type boost::multi_array. The function then returns the value to Excel by wrapping it in an adapter class, as shown below:

CopyC++
CXlOper* MyMatrixAdd_Impl(CXlOper& xloResult, const CXlOper* A_op, const CXlOper
    * B_op)
{
    // Input buffers
    boost::multi_array<double, 2> A;
    boost::multi_array<double, 2> B;
    ...
    // End of generated code
    //}}XLP_SRC
    boost::multi_array<double, 2> C(boost::extents[heightOfA][widthOfA]);

    for (long i = 0; i < heightOfA; i++)
    for (long j = 0; j < widthOfA; j++)
    C[i][j] = A[i][j] + B[i][j];

    xloResult = mtx_adapter(C);
    return xloResult.Ret();
}

Adapter class

The matrix adapter class is defined in the file XlpMultiArray.h in the sample directory.

The XLL+ validation methods expect matrix classes to support the ple::imtx interface. The following ple::imtx methods are used by the validation functions, and must be implemented by an adapter class.

  • void resize(bool preserve, mtx_size dim0, mtx_size dim1);
  • T& at(mtx_size i0, mtx_size i1);

In addition, if you wish to return matrix values to Excel, the adapter class must implement the following methods:

  • mtx_size size(int dim) const;
  • const T& at(mtx_size i0, mtx_size i1) const;

(Note: mtx_size is typedef'd to size_t in the XLL+ implementation of imtx.)

The code for the adapter class is shown below:

CopyC++
template<class T>
class mtx_multi_array_adapter : public ple::imtx_impl<T> {
public:
    mtx_multi_array_adapter(boost::multi_array<T, 2>& impl) : _impl(&impl) {}
    virtual void resize(bool preserve, mtx_size dim0, mtx_size dim1) {
        boost::multi_array<T, 2>::extent_gen extents;
        (*_impl).resize(extents[dim0][dim1]);
    }
    virtual T& at(mtx_size i0, mtx_size i1) {
        return (*_impl)[i0][i1];
    }
    virtual const T& at(mtx_size i0, mtx_size i1) const {
        return (*_impl)[i0][i1];
    }
    virtual mtx_size size(int dim) const {
        return (mtx_size)(*_impl).shape()[dim];
    }
protected:
    boost::multi_array<T, 2>* _impl;
};
template<class T>
mtx_multi_array_adapter<T> mtx_adapter(boost::multi_array<T, 2>& src) {
    return mtx_multi_array_adapter<T>(src);
}

The adapter is derived from the abstract base class ple::imtx_impl<T>.

The constructor takes a reference to a multi_array instance as its only argument, and saves it in _impl.

resize() calls multi_array::resize with the arguments transformed into the notation used by multi_array. (Note that the preserve argument is ignored. The calls made to resize() by the validation functions always assume that the content is destroyed after a resize operation.)

The two at() methods simply pass the coordinates through to the adapted class.

size() extracts the size of the matrix in the requested dimension and returns it, cast to the appropriate integer type.

Finally, the generic template function mtx_adapter creates a new instance of the adapter class and returns it. This global function is used by the validation functions to create adapters for all matrix types. As we saw above, it can also be used in your own code, to create an adapter for a matrix, so that it can be used with the XLL+ run-time library.

Notes

In order to build this sample project, you need to do the following:

  1. Download and install the boost libraries. (Visit http://www.boost.org.)

  2. In the project's list of Additional Include Directories, change the directory C:\3rdParty\boost_1_46_0 to the directory where you installed the boost libraries. (The directory you select should be the parent of the main boost sub-directory.)

When you use the boost libraries under Visual Studio 2005, a host of C4996 warnings appear. These can be prevented by adding /D _SCL_SECURE_NO_WARNINGS to the project's advanced compiler options, or by adding #define _SCL_SECURE_NO_WARNINGS to your code. The former was done for the sample project.

Classes and functions used

imtx<T> | CXlOper::Ret

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file BoostMatrix.sln or the project file BoostMatrix.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files BoostMatrix.help.xml and BoostMatrix.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Matrix containers


Wrapper libraries

This section contains the following samples:

ApiTest
Demonstrates how to create a wrapper library which lets you call XLL Add-in functions directly from a C#, C++ or VBA application. (New in XLL+ 6.3)


Dialogs

This section contains the following samples:

Dialogs
Uses the CXlDialog class to display native Excel dialogs
Integration
Demonstrates how to create a meta-function from the relationship between two cells and use standard numerical methods to integrate the function


Dialogs Sample

Uses the CXlDialog class to display native Excel dialogs

Remarks

This project contains a number of dialog classes, descended from CXlDialog, which demonstrate the use of Excel native dialogs.

It also makes use of the CXlMenu class to install a user-defined menu in Excel's main application menu bar.

Classes and functions used

CXlDialog | CXlDialog::EndDialog | CXlDialog::SetFocus | CXlDialog::Show | CXlDialog::Add | CXlControl | CXlControl::SetEnabled | CXlControl::GetValue | CXlControl::SetValue | CXlControl::GetText | CXlControl::SetText | CXlControlGroupBox | CXlControlOptionGroup | CXlControlOption | CXlControlStatic | CXlControlNumberEdit | CXlControlOK | CXlControlCancel | CXlControlTextEdit | CXlControlRefEdit | CXlControlFormulaEdit | CXlMenu | CXllApp::OnXllOpenEx | CXllApp::OnXllClose

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file Dialogs.sln or the project file Dialogs.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files Dialogs.help.xml and Dialogs.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


Integration Sample

Demonstrates how to create a meta-function from the relationship between two cells and use standard numerical methods to integrate the function

Overview

This sample add-in contains a dialog which allows the user to integrate a mathematical function f(x).

A function can be implied by the relationship between two cells: we treat the contents of the input cell as x and the value in the output cell as f(x).

We can then use standard numerical methods to integrate the function between two x values.

Features

The sample displays the following features:

  • Displays a dialog to let the user select cells for: x, f(x) and the lower and upper bounds of integration, and a cell in which to put the result. The dialog also lets the user select an integration algorithm.

  • The implied function f(x) is calculated by (i) putting the value of x into the input cell, (ii) recalculating the worksheet and (iii) reading the value of the output cell. (This mechanism is referred to as the meta-function.)

  • The integration of the meta-function is performed by standard methods from 'Numerical Recipes in C'. The meta-function has the correct signature to be used by NR methods: double func(double).

  • As a time-saving feature, if the active cell is a cell that has been used in a previous integration operation, the dialog automatically fills in all the fields as they were filled in on the last occasion. (In addition, this information is saved with the worksheet when it is closed.)

Implementing the meta-function

The CMetaFunction class is used to represent the meta-function. The following points are important to the implementation.

  1. The class is initialized with the addresses of the input and output cells:

    CopyC++
    CMetaFunction::CMetaFunction(const CXlOper& xloInput, const CXlOper& xloOutput)
  : m_xloInput(xloInput),
    m_xloOutput(xloOutput)
{
    // Register self as global instance
    mc_instance = this;
}

  2. The class implements a call to the meta-function using CXlOper::SetValue(), CXlMacros::CalculateNow() and CXlOper::Coerce(), as follows:

    CopyC++
    double Func_(double x)
{
    ...

    // Set x into m_xloInput
    if (!m_xloInput.SetValue(x))
    {
        strErr.Format("Unable to set the value of X in cell %s",
            (LPCSTR)m_xloInput.GetRef().ToString(TRUE));
        throw CMetaFunctionException(strErr);
    }

    // Recalculate
    CXlMacros::CalculateNow();

    // Read y (as a number) from m_xloOutput
    CXlOper xloValue;
    if (xloValue.Coerce(m_xloOutput) != 0)
    {
        strErr.Format("Calculation failed for value %f", x);
        throw CMetaFunctionException(strErr);
    }
    if (xloValue.ChangeType(xltypeNum) != 0)
    {
        strErr.Format("Result of calculation was not a number for value %f", x);
        throw CMetaFunctionException(strErr);
    }
    return xloValue.ToDouble();
}

Preserving state

In calling the meta-function, we change the contents of the worksheet. It is polite to restore it to its original state after the operation is complete.

  1. The CMetaFunctionState class is used to save the state of the worksheet before the meta-function is used to restore it after the meta-function has completed for the last time.

  2. The class records (i) the contents of the input cell, which may be a formula or a value, and (ii) the calculation mode, since we will be setting it to Manual.

  3. In addition, the CMetaFunctionState class is responsible for switching off warnings, and switching them back on when the operation is complete.

Integrating with Numerical Recipes code

The following steps were significant in integrating the application with code from 'Numerical Recipes'.

  1. The "Numeric Recipes" code was used without any changes.

  2. The nrerror() function was implemented to throw an exception.

    CopyC++
    void nrerror(const char* err)
{
    throw CMetaFunctionException(err);
}

    This technique is safe to use, because these NR functions do not allocate any memory. The exception must be caught by all functions that use NR code.

  3. The following static method was added to the CMetaFunction class, with the correct signature for use by NR methods.

    double CMetaFunction::Func(double);

    Thus, lines like the following can be used:

    CopyC++
    dResult = qgauss(CMetaFunction::Func, dLower, dUpper);

Implementing the Dialog

The CIntegrationDialog class contains all the logic for populating and displaying a dialog.

  1. The CIntegrationDialog class is descended from the CXlDialog class. (For more details on using CXlDialog, see the Dialogs sample.)

  2. Five RefEdit fields are used to let the user assign cells to x, f(x), Lower x, Upper x and the result. Each field is assigned a sequential ID.

  3. The layout and creation of all fields is done in the constructor.

  4. The virtual method OnOK() is implemented, to trap the pressing of the OK button. The method first validates the input fields; if any errors are found, the dialog is left open, and the focus is set to the aberrant field. If validation succeeds, EndDialog(TRUE); is called, to close the dialog and return TRUE from the CXlDialog::Show() method. (The OnOK() method is also responsible for saving the contents of the input fields for later reuse.)

Reusing dialog data

The DIALOG_DATA structure is used to save the contents of the dialog's entry fields, and to repopulate them later, if the user invokes the dialog from a cell that was used in a previous intergration operation.

  1. The DIALOG_DATA structure is a single continuous block of memory. It can therefore be used as the data assigned to a binary name (see Persistent Data below).

  2. The SerializeDataset() method can read the contents of input fields into a DIALOG_DATA structure, or it can populate the input fields from a DIALOG_DATA structure that was created earlier.

  3. The FindCurrentDataset() method is used to search a set of DIALOG_DATA structures for a data set that includes the address of the active cell.

Persistent data

The dialog saves the current list of DIALOG_DATA sets as binary data within the active worksheet, using binary names. For a complete example using binary names, see the BinaryData sample.

  1. The entire vector of DIALOG_DATA objects is treated as a single BLOB, and saved as a binary name:

    CopyC++
    void CIntegrationDialog::SaveDatasets()
{
    CXllApp::DefineBinaryName(mc_pszDataSetName, &m_datasets[0],
        m_datasets.size() * sizeof(DIALOG_DATA));
}

  2. The BLOB is restored using GetBinaryName() and copied into the dialog's vector:

    CopyC++
    void CIntegrationDialog::RestoreDatasets()
{
    CXlBinaryNameData data;
    if (CXllApp::GetBinaryName(mc_pszDataSetName, data))
    {
        m_datasets.assign((DIALOG_DATA*)data.GetData(),
            (DIALOG_DATA*)(((char*)data.GetData()) + data.GetCount()));
    }
}

  3. The data saved in the current sheet is completely removed by calling the ClearBinaryName() method:

    CopyC++
    static void CIntegrationDialog::ClearDatasets()
{
    CXllApp::ClearBinaryName(mc_pszDataSetName);
}

    This function is declared as static so that it can be called without the hassle of instantiating a CIntegrationDialog object. (It's not beautiful, but it is convenient, and it works because CXllApp::ClearBinaryName is also a static method.)

Menu

The following steps were significant in creating and completing the application's menu.

  1. The project was created with the Add a Menu option switched on, so that the code to display a menu was automatically added to the project.

  2. The menu code was amended to call our two add-in functions: ShowIntegrationDialog() and ClearIntegrations().

    CopyC++
    BOOL CIntegrationApp::OnXllOpenEx()
{
    // Set up menu
    m_menu.SetTexts("Integ&rate");
    m_menu.AddItem("&Run integration...", "ShowIntegrationDialog");
    m_menu.AddItem("&Clear previous integrations", "ClearIntegrations");
    m_menu.Create();
    return TRUE;
}

Excel 2007

Under Excel 2007, the restoration of the serialized data fails, and the dialog fields remain empty. This is because of a known bug with BinaryName data in Excel 2007 which, it has been announced, will be fixed in Office 2007 SP1.

Classes and functions used

CXlDialog | CXlDialog::Show | CXlDialog::SetFocus | CXlDialog::ControlFromID | CXlControlRefEdit | CXlControlRefEdit::GetRef | CXlControlRefEdit::SetRef | CXlControlListBox | CXlControlListBox::AddString | CXlControlListBox::GetCurSel | CXlControlListBox::SetCurSel | CXllApp::DefineBinaryName | CXllApp::GetBinaryName | CXllApp::ClearBinaryName | CXllApp::SetCalculationMode | CXllApp::SetErrorHandling | CXllApp::GetUserAbort | CXllApp::CancelUserAbort | CXllApp::XlMessageBox | CXlMacros::CalculateNow | CXlOper::MakeRef | CXlOper::Coerce | CXlOper::ChangeType | CXlOper::GetRef | CXlOper::GetFormula | CXlOper::SetFormula | CXlOper::SetValue | CXlRef::ToString | CXlMenu | CXlMenu::SetTexts | CXlMenu::AddItem | CXlMenu::Create | CXlMenu::Destroy

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file Integration.sln or the project file Integration.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files Integration.help.xml and Integration.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


International support and localization

This section contains the following samples:

International
Demonstrates how to get and use Excel's international settings
Localized (Single DLL)
Demonstrates how to support multiple languages in a single XLL (Changed for XLL+ 6.0)
Localized (Multiple DLLs)
Demonstrates how to support multiple languages using one DLL per language (Changed for XLL+ 6.0)
Dynamic localized (Single DLL)
Demonstrates how to support multiple languages in a single XLL, switching between languages dynamically (New in XLL+ 6.0)
Dynamic localized (Multiple DLLs)
Demonstrates how to support multiple languages using one DLL per language, switching between languages dynamically (New in XLL+ 6.0)


Dynamic localized (Multiple DLLs) Sample - DynInterMulti

Demonstrates how to support multiple languages using one DLL per language, switching between languages dynamically

Overview

This add-in demonstrates how to support multiple languages using a single XLL, and multiple resource-only DLLs. The add-in will start with the language that matches the user's current regional settings in the Control Panel. The user can switch between languages using a menu.

The program logic is almost identical to that in the Dynamic localized (Single DLL) sample, and the code of the two projects may usefully be compared.

See Deployment for a discussion of using resource-only DLLs to support multiple languages. For step-by-step instructions on how to convert an existing project to support multiple languages, see Conversion of an existing project in the User Guide.

For a discussion of the steps involved in localizing an XLL using multiple DLLs, see the Localized (Multiple DLLs) sample. The discussion in this sample focuses on the changes required in order to allow the language to be switched dynamically.

Setting the language at run-time

In order to change the language at run-time, you need to consider all the areas of behavior that are localized:

  1. Menu text
  2. Toolbar text
  3. Toolbar bitmaps
  4. Functions' category help text

Normally much of this code is handled in the event handlers, OnXllOpenEx() and OnXllClose(), so that it is called when the add-in is opened or closed. In the add-in, the relevant code is removed from the event handlers and placed in RegisterLocalized() and UnregisterLocalized().

CopyC++
void CDynInterMultiApp::RegisterLocalized()
{
    // Set up menu
    m_menu.SetTexts("#2");
    m_menu.AddItem("#3", "BuyWater");
    m_menu.AddItem("-", "");    // Separator
    for (size_t i = 0; i < m_languageNames.size(); i++)
        m_menu.AddItem(m_languageNames[i], "SelectLanguage");
    m_menu.Create();

    // Save position of 1st language menu item
    m_nFirstLanguageMenu = 3;   // (Menu item positions are zero based)

    // Create toolbar
    CXlToolbar::AddToolbar(m_pszToolbarName);
    CXlToolbar::AddTool(m_pszToolbarName, 1, "BuyWater", "#5");
    CXlToolbar::SetToolBitmap(m_pszToolbarName, 1, IDB_BITMAP1);
    CXlToolbar::ShowToolbar(m_pszToolbarName, true, CXlToolbar::DockRight);

    // Save actual toolbar name, for deregistration
    m_strToolbarNameUsed = ::XllGetTranslatedString(m_pszToolbarName);

    // Reregister functions using new texts
    RegisterFunctions();
}

void CDynInterMultiApp::UnregisterLocalized()
{
    // Delete menu
    m_menu.Destroy();

    // Delete toolbar
    CXlToolbar::DeleteToolbar(m_strToolbarNameUsed);

    // Unregister functions
    UnregisterFunctions();
}

The program logic of switching languages is done handled by SetLanguageID(), using XllSetStringResourceHandle():

CopyC++
void CDynInterMultiApp::SetLanguageID(LANGID langid, BOOL bFirstTime)
{
    if (bFirstTime)
        // Unregister functions: the framework has already registered
        // them and they may be in the wrong language
        UnregisterFunctions();
    else
        // Unregister everything
        UnregisterLocalized();

    HINSTANCE hinstRes = m_languageHelper.GetLanguageResources(langid);
    if (hinstRes == NULL)
        hinstRes = XllGetResourceHandle();
    XllSetStringResourceHandle(hinstRes);

    RegisterLocalized();
}

Testing the add-in

  1. Before opening the add-in, use the Control Panel's Regional settings applet to set the current language to English, French or another language.
  2. Open the add-in, and note that the menu is either in English (Water) or in French (Eau) depending on your current regional settings.
  3. Use the list of languages in the menu to switch between languages.
  4. Note that the menu text changes language, as does the popup help for the tool button.
  5. The tool button's bitmap (which is language-sensitive) also changes.
  6. In the Excel Formula Wizard, help text appears in the selected language.

Classes and functions used

::XllSetStringResourceHandle | ::XllGetTranslatedString

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file DynInterMulti.sln or the project file DynInterMulti.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files DynInterMulti.help.xml and DynInterMulti.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Localized (Multiple DLLs) sample | Dynamic localized (Single DLL) sample


Dynamic localized (Single DLL) Sample - DynInterSingle

Demonstrates how to support multiple languages in a single XLL, switching between languages dynamically

Overview

This add-in demonstrates how to support multiple languages in a single XLL, using a resource file. The add-in will start with the language that matches the user's current regional settings in the Control Panel. The user can switch between languages using a menu.

For step-by-step instructions on how to convert an existing project to support multiple languages, see Conversion of an existing project in the User Guide.

For a discussion of the steps involved in localizing an XLL using a single DLL, see the Localized (Single DLL) sample. The discussion in this sample focuses on the changes required in order to allow the language to be switched dynamically.

Getting a list of supported languages

InitLanguageList() is called once, during OnXllOpenEx(), to initialize a list of languages supported by the XLL. The utility function ResListLanguages is used to get a list of all the languages supported by the resource file.

CopyC++
void CDynInterSingleApp::InitLanguageList()
{
    ResListLanguages(XllGetStringResourceHandle(), m_languageIDs,
    LOCALE_SNATIVELANGNAME, m_languageNames);
}

Setting the language at run-time

In order to change the language at run-time, you need to consider all the areas of behavior that are localized:

  1. Menu text
  2. Toolbar text
  3. Toolbar bitmaps
  4. Functions' category help text

Normally much of this code is handled in the event handlers, OnXllOpenEx() and OnXllClose(), so that it is called when the add-in is opened or closed. In this add-in, the relevant code is removed from the event handlers and placed in RegisterLocalized() and UnregisterLocalized().

RegisterLocalized() handles all the creation tasks. Note that the first time it is called, it is not necessary to register the add-in functions themselves, since the XLL+ framework has already taken care of this. On later calls, the add-in functions have been unregistered (by UnregisterLocalized()) and need to be explicitly reregistered.

CopyC++
void CDynInterSingleApp::RegisterLocalized(BOOL bRegFunctions)
{
    // Set up menu
    m_menu.SetTexts("#2");
    m_menu.AddItem("#3", "BuyWater");
    m_menu.AddItem("-", "");    // Separator
    for (size_t i = 0; i < m_languageNames.size(); i++)
        m_menu.AddItem(m_languageNames[i], "SelectLanguage");
    m_menu.Create();

    // Save position of 1st language menu item
    m_nFirstLanguageMenu = 3;   // (Menu item positions are zero based)

    // Create toolbar
    CXlToolbar::AddToolbar(m_pszToolbarName);
    CXlToolbar::AddTool(m_pszToolbarName, 1, "BuyWater", "#5");
    CXlToolbar::SetToolBitmap(m_pszToolbarName, 1, IDB_BITMAP1);
    CXlToolbar::ShowToolbar(m_pszToolbarName, true, CXlToolbar::DockRight);

    // Save actual toolbar name, for deregistration
    m_strToolbarNameUsed = ::XllGetTranslatedString(m_pszToolbarName);

    // Reregister functions using new texts
    if (bRegFunctions)
        RegisterFunctions();
}

void CDynInterSingleApp::UnregisterLocalized()
{
    // Delete menu
    m_menu.Destroy();

    // Delete toolbar
    CXlToolbar::DeleteToolbar(m_strToolbarNameUsed);

    // Unregister functions
    UnregisterFunctions();
}

The program logic of switching languages is done handled by SetLanguageID(), using XllSetStringLanguageID():

CopyC++
void CDynInterSingleApp::SetLanguageID(LANGID langid)
{
    UnregisterLocalized();
    XllSetStringLanguageID(langid);
    RegisterLocalized(TRUE);
}

Testing the add-in

  1. Before opening the add-in, use the Control Panel's Regional settings applet to set the current language to English, French or another language.
  2. Open the add-in, and note that the menu is either in English (Water) or in French (Eau) depending on your current regional settings.
  3. Use the list of languages in the menu to switch between languages.
  4. Note that the menu text changes language, as does the popup help for the tool button.
  5. The tool button's bitmap (which is language-sensitive) also changes.
  6. In the Excel Formula Wizard, help text appears in the selected language.

Classes and functions used

::ResListLanguages | ::XllSetStringLanguageID | ::XllGetTranslatedString

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file DynInterSingle.sln or the project file DynInterSingle.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files DynInterSingle.help.xml and DynInterSingle.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Localized (Single DLL) sample | Dynamic localized (Multiple DLLs) sample


Localized (Multiple DLLs) Sample - InterMulti

Demonstrates how to support multiple languages using one DLL per language

Overview

This add-in demonstrates how to support multiple languages using a single XLL, and multiple resource-only DLLs. The add-in will use the language that best matches the user's current regional settings, as set in the Control Panel.

For step-by-step instructions on how to convert an existing project to support multiple languages, see Conversion of an existing project in the User Guide.

For a sample that allows the language to be changed dynamically, see Dynamic localized (Multiple DLLs) sample.

The program logic is almost identical to that in the Localized (Single DLL) sample, and the code of the two projects is compared below.

See Deployment for a discussion of using resource-only DLLs to support multiple languages. For step-by-step instructions on how to convert an existing project to support multiple languages, see Conversion of an existing project in the User Guide.

Impact of localization

Depending on which language is being used, various features of the add-in will appear differently:

Feature | English | French
Menu texts |  |
Toolbar bitmaps and texts |  |
Error messages |  |
Excel Formula Wizard |  |
Message box |  |

Resource files

The resource file InterMulti.rc contains resources in one language only - English (US).

The resource-only DLL InterMultiRes_1036.DLL contains a resource file InterMultiRes_1036.rc with resources in one language only - French (France).

Resource-only DLL

The project InterMultiRes_1036 can be found in the sub-directory Samples\InterMulti\InterMultiRes_1036. This project builds a French language resource-only DLL for the InterMulti sample.

Note that xlpresfrfr.rc, the French language version of the XLL+ error strings, is included in the resource file, instead of the US English version, xlpres.rc.

Resource IDs

In contrast to a standard XLL, this one uses resource IDs such as #202 instead of strings wherever possible. These IDs represent strings held in the resource file. The XLL+ run-time libraries take care of loading the correct language version of the string.

Resource IDs should be used in the following places:

For the library name:
CopyC++
/* static */ LPCTSTR CInterSingleApp::m_pszDefName = _T("#1");
For menu text:
CopyC++
m_menu.SetTexts(_T("#2"));
m_menu.AddItem(_T("#3"), "BuyWater");
For toolbar text:
CopyC++
// Create toolbar
CXlToolbar::AddToolbar(m_pszToolbarName);
CXlToolbar::AddTool(m_pszToolbarName, 1, _T("BuyWater"), _T("#5"));
CXlToolbar::SetToolBitmap(m_pszToolbarName, 1, IDB_BITMAP1);
CXlToolbar::ShowToolbar(m_pszToolbarName, true, CXlToolbar::DockRight);
For add-in function help text and category, using the XLL+ Function Wizard:

In message boxes and dialogs:
CopyC++
CXllApp::XlMessageBox(XllGetTranslatedString("#0x0005"),
    XlMessageBoxTypeExclamation);
(Notice that this string uses a hexadecimal string ID, prefixed with "0x", instead of a decimal ID. Either form can be used at any time.)

Testing the add-in

  1. Before opening the add-in, use the Control Panel's Regional settings applet to set the current language to English or French.

  2. Open the add-in, and note that all the following are localized:

    • Menu texts
    • Toolbar bitmaps and texts
    • Error messages (when an input fails validation)
    • Excel Formula Wizard
    • Message box (which appears when you click a menu or toolbutton)

  3. Close Excel.

  4. Return to the Regional settings applet, and change to French or English.

  5. Open Excel again, and open the add-in. Note that all the features listed above are now in a different language.

Comparison to a single DLL solution

This add-in is almost identical to that of the Single DLL sample. There are four key differences:

CLanguageHelper instance

There is an instance of CLanguageHelper declared within the application class, CInterMultiApp. This object manages the language DLLS, and makes sure that any loaded instances are properly disposed.

Loading the language DLL

The code added to InitInstance() (discussed above) uses the CLanguageHelper class to find all the available language DLLs, and to load the appropriate one.

Main resource file

There is only one language in the resource file of the main application, corresponding to the LANGID passed to CLanguageHelper::Initialize().

Resource-only DLL

A resource-only DLL is required for each additional language.

Classes and functions used

::XllSetStringResourceHandle | ::XllGetTranslatedString

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file InterMulti.sln or the project file InterMulti.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files InterMulti.help.xml and InterMulti.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Localized (Single DLL) sample


International Sample

Demonstrates how to get and use Excel's international settings

Overview

This add-in uses the CXlApp::GetInternational function to get the current list separator. It then inserts a formula into a cell, using the correct separator.

In English the formula is =MyFunc(101,99) . In German the formula will be =MyFunc(101;99) .

CopyC++
BOOL PasteFormulaIntl()
{
    XLL_FIX_STATE;
    //}}XLP_SRC

    CXlOper xloListSep, xloActive;
    char achFormula[256];

    if (CXllApp::GetInternational(XlInternationalListSeparator, xloListSep))
    {
        // Print the formula using the current separator
        // e.g.: "=MyFunc(101,99)" in English
        //    or "=MyFunc(101;99)" in German
        _snprintf(achFormula, sizeof(achFormula), "=MyFunc(%.0f%s%.0f)",
        101.0,(LPCSTR)xloListSep.ToString(), 99.0);
        if (xloActive.GetActiveCell()
         && xloActive.SetFormula(achFormula))
            return TRUE;
    }
    return FALSE;
}

You may need to use a similar technique for number formats etc.

Calling GetInternational() from a worksheet function

The simple worksheet function GetInternational() also calls CXlApp::GetInternational() and returns the value found. Note that the add-in function is marked as "Defer recalculation". CXllApp::GetInternational() will always fail if called from worksheet functions that have not been marked as "Defer recalculation".

Note also that the add-in function is marked as "Volatile". This causes the formula to be automatically recalculated whenever Excel recalculates the current sheet. Under most versions of Windows and Excel, Excel recalculates whenever the user changes the regional settings, so the formula will update automatically.

See the workbook International.xls for examples of the add-in function in use.

Classes and functions used

CXllApp::GetInternational | CXlOper::GetActiveCell | CXlOper::SetFormula

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file International.sln or the project file International.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files International.help.xml and International.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


Localized (Single DLL) Sample - InterSingle

Demonstrates how to support multiple languages in a single XLL

Overview

This add-in demonstrates how to support multiple languages in a single XLL, using a resource file. The add-in will use the language that best matches the user's current regional settings, as set in the Control Panel.

For step-by-step instructions on how to convert an existing project to support multiple languages, see Conversion of an existing project in the User Guide.

For a sample that allows the language to be changed dynamically, see Dynamic localized (Single DLL) sample.

Impact of localization

Depending on which language is being used, various features of the add-in will appear differently:

Feature | English | French
Menu texts |  |
Toolbar bitmaps and texts |  |
Error messages |  |
Excel Formula Wizard |  |
Message box |  |

Resource file

The resource file InterSingle.rc contains two string tables, one in English (US) and one in French (France). It also contains two bitmaps, one for each language.

To localize run-time error messages, the french error message file xlpresfrfr.rc is included along with the standard english file xlpres.rc.

Resource IDs

In contrast to a standard XLL, this one uses resource IDs such as #202 instead of strings wherever possible. These IDs represent strings held in the resource file. The XLL+ run-time libraries take care of loading the correct language version of the string.

Resource IDs should be used in the following places:

For the library name:
CopyC++
/* static */ LPCTSTR CInterSingleApp::m_pszDefName = _T("#1");
For menu text:
CopyC++
m_menu.SetTexts(_T("#2"));
m_menu.AddItem(_T("#3"), "BuyWater");
For toolbar text:
CopyC++
// Create toolbar
CXlToolbar::AddToolbar(m_pszToolbarName);
CXlToolbar::AddTool(m_pszToolbarName, 1, _T("BuyWater"), _T("#5"));
CXlToolbar::SetToolBitmap(m_pszToolbarName, 1, IDB_BITMAP1);
CXlToolbar::ShowToolbar(m_pszToolbarName, true, CXlToolbar::DockRight);
For add-in function help text and category, using the XLL+ Function Wizard:

In message boxes and dialogs:
CopyC++
CXllApp::XlMessageBox(XllGetTranslatedString("#0x0005"),
    XlMessageBoxTypeExclamation);
(Notice that this string uses a hexadecimal string ID, prefixed with "0x", instead of a decimal ID. Either form can be used at any time.)

Testing the add-in

  1. Before opening the add-in, use the Control Panel's Regional settings applet to set the current language to English or French.

  2. Open the add-in, and note that all the following are localized:

    • Menu texts
    • Toolbar bitmaps and texts
    • Error messages (when an input fails validation)
    • Excel Formula Wizard
    • Message box (which appears when you click a menu or toolbutton)

  3. Close Excel.

  4. Return to the Regional settings applet, and change to French or English.

  5. Open Excel again, and open the add-in. Note that all the features listed above are now in a different language.

Classes and functions used

::XllGetTranslatedString

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file InterSingle.sln or the project file InterSingle.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files InterSingle.help.xml and InterSingle.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Conversion of an existing project | Localized (Multiple DLLs) sample | Dynamic localized (Single DLLs) sample


Advanced examples

This section contains the following samples:

AvgOptCuda
An option value calculator add-in, which demonstrates the use of CUDA and a GPU to speed up performance
BoostMatrix
Demonstrates how to write a matrix adapter class, to integrate a matrix class into XLL+
CallExcel
Demonstrates how to call Excel worksheet and macro functions from an add-in function
UseTimer
Demonstrates how to use a timer to execute a macro function at regular intervals
PartialReg
Demonstrates how to control at run-time which add-in functions are registered and which are not
CreateBook
Demonstrates how to use CXlMacros methods to create and populate workbooks
BinaryData
Demonstrates the use of BinaryName ranges to store binary data in an invisible named range in a worksheet
CalcEvt
Demonstrates how to trap the OnCalculate event, and add your own data to a worksheet
SetFormula
Demonstrates how to set formulae
FInspect
Demonstrates how to inspect and display information about functions in an add-in (Changed for XLL+ 6.0)
Dialogs
Uses the CXlDialog class to display native Excel dialogs
Serialize
Demonstrates how to serialize Excel native data types to and from streams
Integration
Demonstrates how to create a meta-function from the relationship between two cells and use standard numerical methods to integrate the function
TFold
Demonstrates the use of the CXlOper class, in a useful worksheet function that constructs and manipulates arrays
Profiling
Demonstrates a function extension, which profiles the performance of add-in functions
LogDemo
An add-in that writes to a log
ExUIDynList
Changes the contents of a value list at run-time (New in XLL+ 6.2)
DemoFeed
Demonstrates how to integrate a data feed into an Excel add-in for high-performance real-time data add-in, written in C++, and which supports array real-time values as well as scalar values. (New in XLL+ 6.3)
ApiTest
Demonstrates how to create a wrapper library which lets you call XLL Add-in functions directly from a C#, C++ or VBA application. (New in XLL+ 6.3)
ExcepExt
Demonstrates a function extension, which catches a developer-defined exception
XlpGenDemo
Demonstrates how to use the XLPGEN.EXE command-line tool
Publish Opt-In Demo
Applies a function filter with an Opt-In policy
Publish Opt-Out Demo
Applies a function filter with an Opt-Out policy
Publish Run-time Demo
Applies a function filter using a configuration file
SharedHandles
Demonstrates how to share handles between separate add-ins


AvgOptCuda Sample

An option value calculator add-in, which demonstrates the use of CUDA and a GPU to speed up performance

Overview

This add-in contains a calculator for calculating the value of a complex option. It uses CUDA code, executed on the GPU (Graphical Processing Unit), to speed up performance.

Building the sample

This sample requires the Nvidia GPU toolkit in order to be built. See the topic CUDA sample in the User Guide for instructions.

Classes and functions used

CXlRuntimeException | CXlOper | CXlOper::Ret

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file AvgOptCuda.sln or the project file AvgOptCuda.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files AvgOptCuda.help.xml and AvgOptCuda.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | CUDA (User Guide) | CUDA sample project (User Guide)


BinaryData Sample

Demonstrates the use of BinaryName ranges to store binary data in an invisible named range in a worksheet

Overview

This sample add-in demonstrates how to store your own binary data in a worksheet using hidden named ranges that are accessible only to the programmer.

Features

The sample displays the following features:

  • Saves the original book and sheet name and creation time in hidden BinaryName ranges that are not accessible to the user.
  • Creates BinaryName ranges in every new workbook, by setting an event handler for the NewWorkbook event.
  • Displays a menu of actions to let the user set and view the stored data.

Implementation

The following steps were significant in creating and completing the application.

  1. The project was created with the Add a Menu option switched on, so that the code to display a menu was added to the project.

  2. An observer class MyNewWorkbookObserver, derived from CXlNewWorkbookEventStaticObserver, was created, and an instance of it was placed within the application class.

    CopyC++
    class MyNewWorkbookObserver : public CXlNewWorkbookEventStaticObserver
{
    protected:
    virtual void Update(CXlWorkbookEventArgs* e);
};
MyNewWorkbookObserver m_onNewWorkbook;

  3. The observer class's virtual function Update was implemented. This function is called whenever a new workbook is opened.

  4. The Update function uses CXllApp::DefineBinaryName to add numeric data (the creation time) to the front sheet of the workbook and to add string data (the original sheet name - e.g. [book1]sheet1) to every sheet in the new workbook.
  5. Various command macros display or edit the values of the data stored in the BinaryName ranges of the active worksheet, using CXllApp::DefineBinaryName and CXllApp::GetBinaryName. These can all be triggered by the add-in's menu.

Worksheet functions

The add-in also contains 2 worksheet functions, BinGetOriginalName and BinGetOriginalName2. These two functions call CXllApp::GetBinaryName in an attempt to retrieve the contents of the BinaryName "OriginalName". Both functions fail in different ways.

BinGetOriginalName calls CXllApp::GetBinaryName without passing a workbook or sheet name. Consequently, the function looks for the value in the active sheet of the active workbook, rather than in the worksheet containing the cell which called the function. This behavior means that the function will return arbitrarily different values, depending on the state of Excel at the time, making it it pretty much useless.

The second function, BinGetOriginalName2, passes a workbook and sheet name to CXllApp::GetBinaryName. This call usually fails, because it requires Excel to activate a different book and/or sheet, which is illegal during a worksheet function.

These notes should make the developer wary of using BinaryName data within worksheet functions.

Excel 2007

There is a known problem with Excel 2007 as of SP0. Binary names can only be created at workbook level, not in a worksheet. If a binary name with the same name exists on another sheet, then a new binary name saved to a different sheet will overwrite it, regardless of which sheet is active when the binary name is saved.

Excel 2010

There is a known problem with Excel 2010 as of SP0. The function xlGetBinaryName always fails to find the requested name. As a result, CXllApp::GetBinaryName() always fails. This bug is fixed in Microsoft's hotfix 2459118. More information can be found at http://support.microsoft.com/kb/2459118.

Classes and functions used

CXllApp::DefineBinaryName | CXllApp::GetBinaryName | CXlMacros::WorkbookGetWorksheetNames | CXllApp::WinMessageBox | CXlFuncs::Text | CXlOper::GetCaller | CXlOper::GetActiveCell | CXlOper::Coerce | CXlOper::ChangeType | CXlOper::ToString | CXlOper::Ret

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file BinaryData.sln or the project file BinaryData.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files BinaryData.help.xml and BinaryData.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


CalcEvt Sample

Demonstrates how to trap the OnCalculate event, and add your own data to a worksheet

Overview

This sample add-in shows how to trap the OnCalculate event, which occurs just after a sheet has finished calculating.

It also demonstrates the use of CXlOper to manipulate cell references.

Features

The sample displays the following features:

  • The add-in function PutFile(FileName, Destination) returns the timestamp of the named file. It also puts the contents of the file, word by word, into the cells referred to by the Destination argument.
  • Because a worksheet function cannot change the values of cells directly, PutFile keeps a copy of the file name and the destination range for later processing.
  • When the OnCalculate event occurs, each of the files noted for later processing is inspected. If the content of the file differs from the contents of the destination range, then the cells are populated. If the cells are up to date, they are left unchanged.
  • The sample also contains a pair of functions for manipulating file paths, GetDir(path) and MakePath(path1, path2), which are used to calculate the path of a file in the same directory as the example workbook.

Notes

The processing at the end of the function CTextFileTask::PopulateDestination is very important.

CopyC++
// Get the current contents of the destination range
xloOldValue.Coerce(m_xloDest);

// Compare the current value with the contents of the file
// and update the destination range ONLY if they are different.
if (xloOldValue != xloValue)
    m_xloDest.SetValue(xloValue);

We look at the current contents of the destination range, and compare them to the values we intend to put there. If they are identical then we do not update the range.

Every time we update a cell, we can cause the sheet to be calculated. Since this method is called during OnCalculate, we might go into an endless loop, which is to be avoided.

By making sure that we only update the cells when necessary, we only cause a finite number of cascading calculations.

Classes and functions used

CXlCalculateEventStaticObserver | CXlOper::ChangeType | CXlOper::GetCaller | CXlOper::IsRef | CXlOper::GetSheetName | CXlOper::AllocArray | CXlOper::Cell | CXlOper::Coerce | CXlOper::SetValue | CXlOper::RetError | CXlOper::Ret | CXlMenu::CheckItem | ::XllGetTypedApp

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file CalcEvt.sln or the project file CalcEvt.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files CalcEvt.help.xml and CalcEvt.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


DemoFeed Sample

[image]

XLL+ Demo Feed Sample
DemoFeed Sample
See Also Send Feedback

This sample demonstrates a way to author a real-time data-feed as a high-performance C++ Excel add-in.

The application uses Excel’s RTD (Real-Time Data) protocol, and demonstrates the following features:

  • Real-time data functions that return arrays as well as scalars.
  • Enhanced user interface for the Excel Formula Wizard, including drop-down lists for enumerated values, such as field identifiers, and a pop-up dialog for locating a security code.
  • Controls for managing the performance of the feed.

In This Section

Building and running

Instructions for building and running the sample applications.

Data feed architecture

An introduction to the components of a data feed add-in, and the flows between the components.

XllRtdFeed

A general-purpose RTD server which provides the infrastructure and "wiring" for the Excel add-in.

DemoFeed

A demonstration data feed server application.

FeedAddin

A demonstration Excel add-in which allows Excel to display live data items from a data feed.

ConsoleClient

A demonstration command-line program that communicates with the data feed.

Deployment

Instructions for deploying a feed server add-in on a user's computer.

See Also

Other Resources

XllRtdFeedServerProxy.h Reference


Building and running the sample

[image]

XLL+ Demo Feed Sample
Building and running the sample
See Also Send Feedback

Follow the steps below to build and run the sample applications.

Build the sample applications

To build the samples, open the solution file samples\DemoFeed\DemoFeed.sln in Visual Studio, and build the solution.

Note that all the executable files for each project are built to the same directory – either DemoFeed\Debug or DemoFeed\Release, depending on the build.

Running the feed server

Once the samples are built, start the feed server as follows: At the command-line, navigate to the directory containing the executables and type DemoFeed, e.g.:

cd "C:\Program Files\Planatech\XllPlus\6.0\VS9.0\samples\DemoFeed\Debug"

DemoFeed

The server will run until you kill it by pressing Ctrl+C.

Starting the Excel add-in

To start the add-in for the first time under the debugger, build the Debug build, and then:

  1. Open FeedAddin\FeedAddin.cpp.

  2. Go to the XLL Add-ins window. (If it is not visible, use the menu command View/Other Windows/XLL Add-ins to show it).

  3. On the Tools menu in the XLL Add-ins window, click Set up Debugging.

You can then debug the add-in at any time by pressing F5.

Alternatively, you can open either build (debug or relase) of the add-in file FeedAddin.xll in Excel using File/Open, or you can add it to Excel using Tools/Add-ins....

Test data

You will find some large spreadsheets containing test data in the TestData sub-directory.

  1. Start the DemoFeed server application ( see above).

  2. Start Excel. If you have not registered FeedAddin.xll using Tools/Add-ins..., open the add-in.

  3. Open TestData\PublishLargeDataSet.xls. If the buttons in the workbook are disabled, you should enable macros for the workbook. Click on the Publish values button.

  4. Start a second copy of Excel. If you have not registered FeedAddin.xll using Tools/Add-ins..., open the add-in.

  5. Open TestData\ShowLargeDataSet.xls.

  6. Rearrange the Excel application windows so that you can see both at the same time.

  7. In PublishLargeDataSet, click on Increment & Publish. Note that the data in ShowLargeDataSet is updated, including the vectors under "Series" at the right of Sheet1.

You may find it useful to investigate the VBA code in PublishLargeDataSet.xls. Note that ShowLargeDataSet.xls contains no macros, just formulae.

Tuning

You can adjust the responsiveness of the data feed add-in by changing the Excel Application.RTD.ThrottleInterval setting.

In Excel, go to the Visual Basic for Applications window (Alt+F11) and open the Immediate window (press Ctrl+G).

You can see the current setting - in milliseconds - by entering the line below:

CopyVBA
?Application.RTD.ThrottleInterval

You can set the throttle interval to 1/10 of a second by entering the line below:

CopyVBA
Application.RTD.ThrottleInterval = 100

See Also

Other Resources

DemoFeed Sample
Demo Feed server
FeedAddin XLL add-in


Data feed architecture

[image]

XLL+ Demo Feed Sample
Data feed architecture
See Also Send Feedback

This topic outlines the components of the data feed application, and the data flows between the components.

Components

There are four components involved in providing a real-time data feed in Excel.

Excel

The user enters real-time data formulae in the cells of an Excel spreadsheet. In response, Excel calls the specified add-in functions in the XLL.

XLL

This is an XLL+ Excel add-in, written in C++ by the developer. All the significant code resides here, including the following:

  • User-friendly add-in functions which return real-time data. These functions are responsible for transforming the user's input into the form required to query the data feed.
  • An event-handler function which responds to "update" messages from the data feed.
  • Event-handler functions that respond to the Excel events that are raised when (i) a topic is removed from a spreadsheet, and (ii) an old topic is requested when a spreadsheet containing real-time data is reopened.
RTD Server

An RTD (Real-Time Data) server module is a means of extending Excel so that it can respond quickly and reliably to data that changes in the outside world. An RTD server must be provided as a COM module and must support the COM interface IRtdServer.

The XLL+ data feed server is an RTD server provided as part of the XLL+ tool-kit (version 6.3 and above). The file is named XllRtdFeed.dll and can be found in the bin sub-directory of the XLL+ installation directory.

Data Feed

A 3rd-party data feed with a C++ API is the final component. Typically, the API of such a feed will allow an application (in this case, the XLL) to do the following:

  • Initialize and terminate a connection to the data feed.
  • Request the latest value of a data item.
  • Register interest in a data item, so that the application will be informed, via a call-back function, whenever the data item's value is updated. This action is often referred to as "Advise".
  • Inform the data feed that the application is no longer interested in a particular data item (often called "Unadvise").

The data feed supplied as part of the sample application is simple and very limited, and is provided only to demonstrate the techniques for writing an add-in that uses it. It is described in more detail in Demo Feed server.

As you will see in the following section, Flows, the data flows required to manage real-time data in Excel can be quite complicated. The XllRtdFeed RTD server and the C++ API supplied in XllRtdFeedServerProxy.h abstract most of this complexity and make the process of developing a data feed add-in much simpler.

Flows

The data flow between Excel and the various components of a real-time feed is described below.

Excel calls add-in function

Flow: Excel calls function

When Excel calls the add-in function for the first time, the following steps occur:

  1. Excel calls the add-in function in the XLL.

  2. The add-in function requests the data from the feed, and registers an interest in updates to the data.

  3. The feed either returns the current value for the data, or returns a success code, indicating that the data will be sent later, asynchronously.

  4. The add-in function informs the RTD server that this data is real-time, and may be updated at a later time. This is done by calling the function CXllRtdFeedServerProxy::CallRtd().

  5. The add-in function returns the current value (or a "Wait" message) to Excel.

The data feed sends an update

From time to time the data feed will send data asynchronously to the XLL add-in. This may be because a data value previously supplied has been updated, or because a data value previously requyested is now available.

  1. The data feed sends a message when an interesting data item is updated. This is received by a call-back function in the XLL add-in, and may occur in a background thread.

  2. The XLL's call-back function informs the RTD server that this particular topic has changed.

  3. Whenever Excel is ready for input, the RTD server informs Excel that the topic's value has changed.

After this, Excel will call the add-in function again for any cell that refers to the updated topic, and the data flow will be as discussed above under Excel calls add-in function.

If calculation in Excel is set to Automatic, then a recalculation will occur as soon as Excel receives the update message. If calculation is set to Manual, then the affected cells will be recalculated the next time F9 is pressed.

A spreadsheet containing real-time data is reopened

When a spreadsheet is opened that contains real-time data formulae, Excel may need to refresh the real-time values. The following steps occur:

  1. Excel informs the RTD server that it wants up-to-date values for the topics used in the spreadsheet.

  2. The RTD informs the XLL by invoking the IXllRtdFeedCallback::OnGetDataState() event handler function, which is implemented in the XLL.

  3. During IXllRtdFeedCallback::OnGetDataState(), the XLL requests the latest value of the data item from the data feed.

  4. The feed either returns the current value for the data, or returns a success code, indicating that the data will be sent later, asynchronously.

  5. The XLL's implementation of IXllRtdFeedCallback::OnGetDataState() returns a state value which describes the current value of the requested data item.

  6. The RTD server returns the state value to Excel. Excel compares it to the last state value it received for this data item, and decides whether the value is out of date.

After this, Excel will call the add-in function again for any cell that refers to the reopened topic, and the data flow will be as discussed above under Excel calls add-in function.

See Also

Other Resources

XllRtdFeed RTD server


XllRtdFeed RTD server

[image]

XLL+ Demo Feed Sample
XllRtdFeed RTD server
See Also Send Feedback

XLLRTDFEED.DLL is a general-purpose RTD feed server component. It is supplied as a component of the XLL+ tool-kit (version 6.3 and above).

This RTD server routes all necessary RTD messages back to an XLL that uses it. Thus all the significant application code can be in one place - the XLL add-in.

The server must be registered as a COM module before it can be used with Excel. See Deploying a feed server add-in for details.

XllRtdFeed API

All the communication between the RTD server and an XLL is through a C++ API. To use the API, add the header file to your application code:

CopyC++
#include <XllRtdFeedServerProxy.h>

XLL add-ins make calls to the RTD server via the CXllRtdFeedServerProxy class. The XLL must also provide a callback object, derived from IXllRtdFeedCallback, which will handle events raised by the RTD server.

CXllRtdFeedServerProxy class

This class has four public methods.

Method | Description
RegisterClient | Registers this XLL as a client of the RTD server, and initializes the RTD server if necessary.
UnregisterClient | Unregisters this XLL as a client of the RTD server. No further call-backs will be routed to the XLL.
CallRtd | Makes a call to the RTD server, via Excel. If called from an add-in function, has the effect of linking the caller cell to the specified topic. The cell will automatically be recalculated whenever the topic is updated.
UpdateTopic | Informs the RTD server that the specified topic has been updated. Any cells depending on the topic will automatically be recalculated. This method may be called from any thread.

IXllRtdFeedCallback interface

An XLL must create an instance of a class derived from IXllRtdFeedCallback, and pass a pointer to the instance during CXllRtdFeedServerProxy::RegisterClient(). The class must implement two virtual functions.

Method | Description
OnGetDataState | Called whenever Excel needs to know whether a data item is available, and whether its value has changed.
OnTopicRemoved | Called whenever Excel is no longer interested in a particular topic. This will occur when the last cell range that refers to the topic is removed, changed or closed.

Client usage

Normally, an XLL will interact with XllRtdFeed as follows.

  1. Call CXllRtdFeedServerProxy::RegisterClient() during initialization, usually during OnXllOpenEx().
  2. Invoke CXllRtdFeedServerProxy::CallRtd() during any add-in function that returns live data.
  3. Call CXllRtdFeedServerProxy::UpdateTopic() asynchronously, whenever the feed server sends an update for a topic of interest.
  4. Call CXllRtdFeedServerProxy::UnregisterClient() during close-down, usually during OnXllClose() .

In addition, the implementation of IXllRtdFeedCallback should handle the following callbacks.

CopyC++
virtual bool OnGetDataState(LPCWSTR lpszClient, LPCWSTR lpszTopic,
    LPVARIANT lpvntState);

This virtual function is called whenever Excel needs to know the current value or availability of the specified topic.

  1. The XLL should examine its cache for the requested data.
  2. If the data is found, then it should set *lpvntState to a value which describes the state of the data and return true. (See State values below.)
  3. If the data is not found, the XLL should request it from the feed.
  4. If the data item will never be found, OnGetDataState() should return false.
CopyC++
virtual void OnTopicRemoved(LPCWSTR lpszClient, LPCWSTR lpszTopic,
    long lTopicID);

This virtual function is called when Excel is no longer interested in a topic.

  1. The XLL should inform the feed that it is no longer interested in the topic.
  2. The XLL should remove the specified data from its cache.

State Values

It is not necessary to inform RTD of the actual value of the data that has changed; you merely need to pass a value that changes whenever the value itself changes. This distinction is important, because RTD cannot accept array values, only scalars, so it is not possible to pass an array value to RTD.

The state value is any associated value that changes at the same time as the data value itself. Possible state values are:

  • Timestamp of new data value.
  • A numeric hash of the full data value.
  • For a scalar value, the data value itself.
  • A sequence id which is incremented whenever the value is changed.

For most purposes, a timestamp is the simplest option. The demo add-in uses as timestamp as the state value.

See Also

Other Resources

FeedAddin XLL add-in
DemoFeed Sample
XllRtdFeedServerProxy.h Reference


Demo Feed server

[image]

XLL+ Demo Feed Sample
Demo Feed server
See Also Send Feedback

The DEMOFEED application is a simplified data server. It supports multiple clients on a single computer, with updates shared between all clients.

The feed is not designed to be scalable, extensible or robust. It is designed only for demonstration purposes.

Commands

The following commands are supported:

Command | Description
GET | Gets a single data item (which may be scalar or array)
SET | Sets a single data item
FIND | Gets a list of securities whose codes match the search string
ADVISE | Registers interest in a single data item, so that the client will receive an update message whenever the value changes.
UNADVISE | Unregisters interest in a data item, so that update messages for the item are no longer sent to the client.
GET_UPDATES | Gets all queued update messages concerning changes to items in which the client has registered interest.
SAVE_DATA | Saves all data from the database to a text file
RESTORE_DATA | Restores saved data from a text file, optionally clearing all current data

Fields

The feed server contains a small in-memory database of securities. The table below lists the fields available for each security.

ID | Name | Type | Description
0 | Code | String | Unique code for security
1 | Name | String | Name of security
2 | Bid | Floating-point | Latest bid price
3 | Ask | Floating-point | Latest ask price
4 | Series | Vector of floating-point | Series of traded prices
5 | Latency | Integer | The number of milliseconds the feed should delay before responding to GET commands for the security.
6 | Dictionary | List | Data dictionary. (This is only available if the security code is "!".)

API

The client API for the feed consists of a single class, FeedConnection, which supports two-way communication with the feed. The application and its client API are self-contained, and do not rely in the XLL+ run-time libraries.

The methods are summarized below.

int Connect();
Connects to the data feed.
int Disconnect();
Disconnects from the data feed.
int Get(const wchar_t* pszSecurityCode, int nPropertyId, wstring& strValue, timestamp_type& tsValue);
Gets a single value, in text format, from the data feed.
int Set(const wchar_t* pszSecurityCode, int nPropertyId, const wchar_t* pszValue);
Publishes a single value, in text format, to the data feed.
int Find(const wchar_t* pszSecurityCodeSearch, std::vector<std::wstring>& astrCodes);
Gets a list of securities whose codes match the search string
int Advise(const wchar_t* pszSecurityCode, int nPropertyId);
Registers interest in a single data item, so that the client will receive an update message whenever the value changes.
int Unadvise(const wchar_t* pszSecurityCode, int nPropertyId);
Unregisters interest in a data item, so that update messages for the item are no longer sent to the client.
int StartListener();
Starts a background thread to listen for updates. This thread will call the OnGetUpdates() virtual method whenever an update is received to an item for which Advise() has been called.
void StopListener();
Stops the listener thread. Updates will no longer be passed to OnGetUpdates().
virtual void OnGetUpdates(const std::vector<FeedMessage>& updates);
Called by the listener thread when updates to items of interest are received.

Database

The demo feed server loads an initial data set from a data file if one is specified on the command line. If no data file is specified, or if the specified data file is not found, the following data-set is loaded:

Code | Name | Bid | Ask | Series | Latency
MGC | MegaCorp | 100 | 101.5 | 99.0;99.5;101.0;100.0;100.25 | 0
CD | Cheesedale | 50 | 52 | 49.0;49.5;51.0;50.0;50.25 | 0

Usage

To run the data server, run it at the command-line, e.g.:

DATAFEED

Optionally, specify a data file in the same directory as the file DATAFEED.EXE:

DATAFEED -o data2.txt

You can specify the level of information written to the command line using the –l option. The level should be ERROR, WARNING, INFO, DEBUG or TRACE.

DATAFEED -l INFO

To stop the data server, just type Control+C at the command-line.

See Also

Other Resources

FeedAddin XLL add-in
Demo Feed server


FeedAddin XLL add-in

[image]

XLL+ Demo Feed Sample
FeedAddin XLL add-in
See Also Send Feedback

The demonstration add-in is contained in project FeedAddin.vcproj in the sample solution, DemoFeed.sln.

This topic contains the following sections.

  • Overview
  • Initialization and termination
  • Callbacks
  • Feed helper functions
  • Add-in functions
  • User interface extensions
  • Components
  • See Also

Overview

The add-in project was created as a standard XLL+ Add-in project, using the XLL+ AppWizard.

For convenience in using the RTD server API and the Demo Feed API, Unicode characters were chosen. For simplicity in coding a popup dialog, the MFC (Microsoft Foundation Classes) libraries were selected.

The add-in contains various styles of function:

  • Worksheet add-in functions that return live data.

  • Worksheet add-in functions that return snap-shots of data.

  • Command macros that publish data to the feed.

  • Command macros that control the behavior of the feed.

An extended user interface is provided for some of the worksheet functions, so that the user is helped to select inputs in the Excel Formula Wizard.

The rest of this topic examines the C++ source code in FeedAddin.vcproj.

Initialization and termination

Open FeedAddin.cpp, which is the main source file for the project.

We start with CFeedAddinApp::OnXllOpenEx(). This contains 4 steps:

  1. Start logging.

  2. Connect to the data feed.

  3. Connect to the RTD server.

  4. Set up the user interface.

The RTD server initialization looks like this:

CopyC++
        // Initialize RTD
if (!m_rtdServer.RegisterClient(RTD_CLIENT_NAME, &m_rtdCallback))
{
    XlMessageBox(_T("Failed to connect to RTD server"),
        XlMessageBoxTypeExclamation);
    return FALSE;
}

If RegisterClient() fails, then the add-in will not be able to provide live data, and therefore FALSE is returned to indicate that the add-in should not be opened.

A client name is passed as the first argument to RegisterClient(). This should be a name used only by this XLL. The RTD server can support multiple XLLs simultaneously, and therefore each client XLL must have a unique name. You can safely use the file name of the XLL for this purpose.

The second argument is a pointer to an object that implements IXllRtdFeedCallback. This object will handle call-backs from the RTD server.

In CFeedAddinApp::OnXllClose(), the add-in terminates its services.

  1. Tear down the user interface.

  2. Disconnect from the RTD server

  3. Disconnect from the data feed.

The RTD server is terminated as follows:

CopyC++
// Terminate connection to RTD feed server
m_rtdServer.UnregisterClient();

If RegisterClient() failed earlier, then UnregisterClient() will fail harmlessly.

Callbacks

Next in FeedAddin.cpp are three small callback functions. Each redirects to a method of the application class.

  • MyXllRtdFeedCallback::OnGetDataState() is called when Excel needs some information about a cell containing live data.

  • MyXllRtdFeedCallback:: OnTopicRemoved () is called when Excel is no longer using a particular item of live data.

  • MyFeedConnection::OnGetUpdates() is called by the data feed’s listener thread whenever the data feed has sent some updates for data in which the add-in is interested.

This section contains the following subsections.

  • OnRtdGetDataState
  • OnRtdTopicRemoved
  • OnFeedGetUpdates

OnRtdGetDataState

This call-back is the most important part of the real-time data implementation. It is called by Excel whenever it needs to know about a particular topic.

This call may occur at any of three points:

  1. For a new topic, that has just been requested from an add-in function, via a call to CXllRtdFeedServerProxy::CallRtd().

  2. From a cell in a previously saved workbook which has been reopened.

  3. For a topic that has been updated by the client XLL using CXllRtdFeedServerProxy::UpdateTopic().

The implementation consists of three steps.

  1. Look up the requested item in the cache. (This should be a thread-safe operation.)

  2. If the requested item is not yet on the cache, then add the item, and request the data from the data feed. (This should also be thread-safe.)

  3. Set the value of the parameter *lpvntState to the timestamp of the data.

OnRtdTopicRemoved

This method is called when Excel informs us (via the RTD server) that the specified topic has been removed from the RTD server's list of active topics.

This will occur after the last cell range that uses the topic is removed, closed, or for any other reason ceases to be connected to the specified topic - for instance because an argument to a formula has changed, and therefore the topic has changed.

The call is not guaranteed to come immediately after the topic becomes unused. It may be delayed - Excel controls the timing.

The implementation consists of two steps.

  1. Remove the requested item from the cache. This should be a thread-safe operation.

  2. Inform the data feed that we are no longer interested in the item (Unadvise).

OnFeedGetUpdates

This method is called whenever updates arrive from the data feed. It may be called by the data feed listener thread or by the main thread. Like the other event handler callback functions, all the operations it calls must be thread-safe.

If the feed is currently paused, then the update messages are queued and no further action is taken until the feed is restarted.

If the feed is not currently paused, then 2 steps are required for each update message:

  1. Update the data item in the cache. If it is not present in the cache, discard the message.

  2. Call CXllRtdFeedServerProxy::UpdateTopic() to tell Excel that the topic is changed, and that all cells depending on it should be recalculated.

Feed helper functions

The next section of the source code contains helper functions for using the data feed.

AddFeedItemToCache

This utility method adds a data item to the cache and connects it to the data feed.

  1. Add the item to the cache, without any data.

  2. Fetch the data from the data feed (using a synchronous GET call).

  3. Send an ADVISE message to the feed to register for future updates.

As with all the other core functions of the add-in, all of the operations in this method are thread-safe.

PauseFeed

This method switches on the update queue, so that asynchronous updates no longer reach the cache or Excel. Until the feed is restarted, all updates will be stored in the update queue.

RestartFeed

This method switches the update queue off, so that asynchronous update messages go directly to the cache and to Excel. It also processes all queued update messages that arrived while the feed was paused.

LoadDictionary

LoadDictionary() downloads the data dictionary from the feed, and stores it in a local copy. This copy will be used to validate property identifiers and to enrich the user interface.

Add-in functions

Finally, in FeedAddin.cpp, we reach the code for the add-in functions.

Function | Type | Description
DF_LIVE | Worksheet, real-time data | Get a named data item as live data
DF_GET | Worksheet | Get a named data item. Do not receive updates.
DF_FIND | Worksheet | Gets a list of security codes that match the search string
DF_TOGGLE_FEED | Macro | Pauses or restarts the data feed
DF_SET | Macro | Publishes a single value to the data feed
DF_SET_RANGE | Macro | Publishes the values in the specified range. If no range is specified, the current selection is used.
DF_SET_THROTTLE_INTERVAL | Macro | Sets the time between calls to the data feed, getting updated items
DF_FIND_POPUP | Macro | Displays a dialog for searching for security codes

DF_LIVE

DF_LIVE(Security, Property)

Real-time data worksheet function

This function is a simple and typical real-time data function. It is a real-time data function: it returns live data, which is automatically refreshed when the data is updated.

DF_LIVE makes use of the methods in the helper class CFeedHelper, which handle the basic tasks of converting data formats between Excel and the DemoFeed API.

CopyC++
CXlOper* DF_LIVE_Impl(CXlOper& xloResult, const CXlStringArg& Security,
    const CXlStringArg& Property)
{
    CFeedAddinApp* papp = XllGetTypedApp();

    // Parse input
    CStringW strSecurityCode = CFeedHelper::MakeSecurityCode(Security);
    int nPropertyId = CFeedHelper::ValidateProperty(Property);

    // Check the cache
    if (!papp->m_dataCache.GetValue((LPCWSTR)strSecurityCode,
        nPropertyId, &xloResult, 0))
    {
        // For new items, add to the cache, get the data from the feed,
        // and also advise future updates.
        papp->AddFeedItemToCache((LPCWSTR)strSecurityCode,
            nPropertyId, xloResult);
    }

    // Call RTD, to inform Excel that this is live data
    CXlOper xloRtdResult;
    std::wstring strTopic = CDataCache::MakeTopic(
        (LPCWSTR)strSecurityCode, nPropertyId);
    papp->m_rtdServer.CallRtd(xloRtdResult, strTopic.c_str());

    return xloResult.Ret();
}

The function performs four steps.

  1. Validate and convert the inputs, throwing an exception if the property is invalid.

  2. Check the cache for the requested data.

  3. If the data is not in the cache, request it from the feed and add it to the cache. Also send an ADVISE message to the feed, so that our feed listener thread will receive update messages about this data item.

  4. Inform Excel that the calling cell is dependent on external data, by calling CXllRtdFeedServerProxy.CallRtd(), with a topic that defines the data item.

The last step is very important. Even if the data is found in the cache, we must still inform Excel that the data may change in the future; if we don’t use CallRtd(), then Excel will not know this.

Note that all calls to shared components are thread-safe.

Note also that the returned data may be scalar (single-cell) or an array. CFeedHelper::ParsePropertyValue() handles the conversion, making use of the data dictionary to determine the data type and rank of the property.

DF_GET

DF_GET(Security, Property)

Worksheet function

This function is equivalent to DF_LIVE, except that it is not a real-time data function: it simply returns the requested item from the feed – cells will not be refreshed when the data is updated.

CopyC++
CXlOper* DF_GET_Impl(CXlOper& xloResult, const CXlStringArg& Security,
    const CXlStringArg& Property)
{
    CStringW strSecurityCode = CFeedHelper::MakeSecurityCode(Security);
    int nPropertyId = CFeedHelper::ValidateProperty(Property);

    std::wstring strValue;
    DemoFeed::timestamp_type tsValue;
    int rc = XllGetTypedApp()->m_connection.Get(strSecurityCode,
        nPropertyId, strValue, tsValue);
    if (rc == 0)
        xloResult = CFeedHelper::ParsePropertyValue(strValue,
            nPropertyId);
    else
        xloResult.Format(_T("#ERROR %d"), rc);

    return xloResult.Ret();
}

DF_GET makes use of the methods in the helper class CFeedHelper, which handle the basic tasks of converting data formats between Excel and the DemoFeed API.

DF_GET performs three steps:

  1. Validate and convert inputs.

  2. Request data from the data feed.

  3. Convert returned data to Excel format.

Note that the returned data may be scalar (single-cell) or an array. CFeedHelper::ParsePropertyValue() handles the conversion, making use of the data dictionary to determine the data type of the property.

DF_FIND

DF_FIND(Search)

Worksheet function

This simple function sends a partial security code to the data feed and returns the list of security codes that match. It is not a real-time data function, and does not receive automatic updates.

DF_TOGGLE_FEED

DF_TOGGLE_FEED()

Macro

This macro function pauses or restarts the data feed. It also updates the text of the Excel menu item to match the current state of the feed.

CopyC++
CXlOper* DF_TOGGLE_FEED_Impl(CXlOper& xloResult)
{
    CFeedAddinApp* papp = XllGetTypedApp();

    if (papp->FeedIsPaused())
        papp->RestartFeed();
    else
        papp->PauseFeed();

    papp->m_menu.ReplaceItem(0, papp->FeedIsPaused()
        ? _T("Restart &Feed") : _T("Pause &Feed"));

    return xloResult.Ret();
}

Note that the three methods used – FeedIsPaused(), PauseFeed() and RestartFeed() – are all thread-safe operations, to avoid conflicts with the feed listener thread.

DF_SET

DF_SET(Security, Property, Value)

Macro

This macro function publishes a single data value to the feed. It can be called from VBA code, e.g.:

CopyVBA
Application.Run "DF_SET", "MGC", 2, 99.9

It is useful for writing VBA macros that test functionality, performance and latency.

DF_SET_RANGE

DF_SET_RANGE(Range)

Macro

This macro function publishes a range of data values to the feed. It can be called from VBA code, e.g.:

CopyVBA
Application.Run "DF_SET_RANGE", Range("F3:K24")

If Range is omitted, then the current selection is used as the input. A command on the Excel Demo Feed menu, Set data from Selection, invokes this macro.

The macro accepts three forms of data range.

Table

A table should contain at least 2 x 2 cells, with property identifiers in the top row (except for the top-left cell), security codes in the left-most column (except for the top-left cell) and values in the rest of the table. The top-left cell must be empty.

NAME | BID | ASK
MGC | MegaCorp | 100 | 100.5
CD | Cheesedale | 50 | 51
List

A list should contain 3 columns and any number of rows. The three columns, from left to right, should contain (i) Security Code, (ii) Property Identifier, and (iii) Value.

MGC | BID | 100
MGC | ASK | 100.5
CD | BID | 50
CD | ASK | 51
Vector

A vector should contain one column and at least 3 rows. The top two cells contain the security code and the property name or id. The third and subsequent cells contain the vector data that is being published.

MGC
Series
100
101
102
...

DF_SET_THROTTLE_INTERVAL

DF_SET_THROTTLE_INTERVAL(Period)

Macro

The data feed client uses a pull-push mechanism. It polls the server periodically from a background (listener) thread. Use this macro to set the period, in milliseconds.

DF_FIND_POPUP

DF_FIND_POPUP()

Macro

This macro function pops up the security code search dialog that is discussed below under User Interface extensions. If the user selects a code, it is placed in the active cell.

User interface extensions

DemoFeedUI.cpp contains code that enriches the user interface of the Excel Formula Wizard.

Drop-down lists

In CFeedAddinApp::SetupPropertyValueLists(), the data dictionary is used to build a drop-down list which will appear in the Formula Wizard:

For more information about drop-down lists of values see the User Guide.

Pop-up dialogs

CSecurityCodePopupProvider implements a popup editor for finding security codes, which appears when the user clicks the browse (...) button in the Excel Formula Wizard:

Statically declared CXlWizExUIArgumentPopupCreator objects are used to register the popup editors for each appropriate argument.

(As with much of the Demo Feed sample, this is a minimal implementation, just to give you an idea of what you might do. It is not intended to be a complete, elegant or powerful example of a search tool.)

For more information on pop-up dialogs, see the User Guide.

Components

The add-in application contains several components that handle specific tasks.

CXllRtdFeedServerProxy

CXllRtdFeedServerProxy is used to make calls from the XLL to the RTD server.

CallRtd() tells Excel that a cell depends on an RTD topic.

UpdateTopic() tells Excel that a topic has been updated.

MyXllRtdFeedCallback

MyXllRtdFeedCallback is a class derived from IXllRtdFeedCallback. It handles RTD events raised by Excel.

MyFeedConnection

MyFeedConnection is a class derived from DemoFeed::FeedConnection. It handles communications with the data feed, including handling asynchronous update messages.

CDataCache

DataCache is a thread-safe data cache class. It holds all the active topics and their current values and state.

CMessageQueue

A thread-safe collection class, used as a temporary buffer for holding update messages while the feed is paused.

DemoFeed::Dictionary

A copy of the feed’s data dictionary.

CFeedHelper

A static helper class which performs data conversion and validation tasks.

CXllRtdFeedServerProxy

The application class, CFeedAddinApp, contains an instance of CXllRtdFeedServerProxy, which is used to send requests and update messages to the RTD server.

CopyC++
class CFeedAddinApp : public CXllApp
{
    ...
    // Connection to RTD
    CXllRtdFeedServerProxy m_rtdServer;
    ...
}

Whenever a topic of interest is updated, the RTD server is informed during CFeedAddinApp::OnFeedGetUpdates():

CopyC++
m_rtdServer.UpdateTopic(pszTopic);

During every add-in function that supplies live data, a call is made to CallRtd():

CopyC++
// Call RTD, to inform Excel that this is live data
CXlOper xloRtdResult;
std::wstring strTopic = CDataCache::MakeTopic(strSecurityCode, Property);
papp->m_rtdServer.CallRtd(xloRtdResult, strTopic.c_str());

MyXllRtdFeedCallback

This class is derived from the abstract base class IXllRtdFeedCallback. It handles two important call-backs from the RTD server. In both cases, they are routed to the application class:

CopyC++
bool MyXllRtdFeedCallback::OnGetDataState(LPCWSTR lpszClient,
    LPCWSTR lpszTopic, LPVARIANT lpvntState)
{
    return XllGetTypedApp()->OnRtdGetDataState(lpszClient, lpszTopic,
        lpvntState);
}

void MyXllRtdFeedCallback::OnTopicRemoved(LPCWSTR lpszClient,
    LPCWSTR lpszTopic, long lTopicID)
{
    XllGetTypedApp()->OnRtdTopicRemoved(lpszClient, lpszTopic,
        lTopicID);
}

The application class’s implementations of these event handlers are discussed elsewhere.

MyFeedConnection

This class is derived from DemoFeed::FeedConnection, and implements the virtual function, OnGetUpdates(), which is called from a listener thread whenever updates arrive.

CopyC++
class MyFeedConnection : public DemoFeed::FeedConnection
{
public:
    virtual void OnGetUpdates(const std::vector<DemoFeed::FeedMessage>&
        updates)
    {
        XllGetTypedApp()->OnFeedGetUpdates(updates);
    }
};

The updates are routed to the application class method OnGetFeedUpdates(). This is discussed elsewhere.

An instance of MyFeedConnection is contained in the application class:

CopyC++
class CFeedAddinApp : public CXllApp
{
    ...
    // Connection to data feed
    MyFeedConnection m_connection;
    ...
}

The instance is used to send requests to the data feed, including the following:

  • Get() and Advise() are called when an add-in function requests a particular data topic.

  • Unadvise() is called Excel informs us (through MyXllRtdFeedCallback::OnTopicRemoved()) that a topic is no longer of interest.

CDataCache

This class is a thread-safe lookup table. The key to each item in the table is a pair: security code + property identifier.

For each item the following fields are held:

Field | Type | Description
m_strSecurityCode | string | Security code
m_nPropertyId | int | Property identifier
m_strValue | string | Value, in string form, as returned by the data feed
m_xloValue | CXlOper | Value in Excel form, after being parsed from a string
m_bHasValue | bool | True if the value is available, false if it is currently unknown
m_timestamp | timestamp | Timestamp of the data value (or 0 if not known)

Holding the parsed value of the data in m_xloValue is a very good idea for improving performance. A single piece of data may be required many times, since Excel’s recalculation engine can frequently recalculate cells that have not changed, and this way it need only be parsed once.

The following thread-safe methods are available for accessing the cache:

  • AddItem
  • RemoveItem
  • UpdateItem
  • GetItem
  • GetValue

The last method, GetValue(), is optimized for minimal data copying, and is intended for use from add-in functions.

CMessageQueue

This simple class implements a thread-safe message queue.

If the data feed is paused, then message queue is activated, and the add-in pushes any new update messages into the queue.

If the feed is restarted, then all the queued messages are processed, and any newly arrived update messages are processed normally.

CFeedHelper

This class contains a few static functions that help with data conversion and validation.

CopyC++
static int CFeedHelper::ValidateProperty(const wchar_t* pszProperty,
    const TCHAR* pszArgumentName = _T("Property"));

ValidateProperty() is a useful method, and is worth examining. It does the following for a Property identifier input to an add-in function:

  1. If the input is an integer, check whether it is a legal numeric property id. If it is not, then throw an exception.
  2. If the input is a string, look it up in the data dictionary. If it is valid, return the numeric property id. If it is not, then throw an exception.
  3. Return the numeric property id.

Conveniently, the method only returns a valid property id. If an exception is thrown, then the add-in function will immediately cease, and will return a useful error message to Excel. This is a useful pattern, and allows you to write simple short code in the add-in function, with no extra error handling overhead; e.g.:

CopyC++
int nPropertyId = CFeedHelper::ValidateProperty(Property);

See Also

Other Resources

XllRtdFeed RTD server
DemoFeed Sample
XllRtdFeedServerProxy.h Reference


ConsoleClient test application

[image]

XLL+ Demo Feed Sample
ConsoleClient test application
See Also Send Feedback

ConsoleClient is a small command-line test program that can communicate with the DEMOFEED data feed server. Start it at the command-line, and enter ? for help.

See Also

Other Resources

Demo Feed server
DemoFeed Sample


Deploying a feed server add-in

[image]

XLL+ Demo Feed Sample
Deploying a feed server add-in
See Also Send Feedback

The implementation of the feed uses Excel's RTD mechanism. An add-in that uses the feed infrastructure therefore has some runtime requirements on any machine where it is to be used.

Requirements

Excel's RTD mechanism is only available in Excel XP upwards (Excel XP/2002, Excel 2003, Excel 2007 and Excel 2010). It cannot be used with Excel 97 or Excel 2000.

Deployment

The model uses a COM module (XllRtdFeed.dll) to support Excel's RTD mechanism. You should deliver the RTD server module XllRtdFeed.dll to the target computer, and register it, e.g.:

REGSVR32 "C:\Programs\InstalledAddins\Shared\XllRtdFeed.dll"

Ensure that you register the correct version of the DLL: on a machine with 64-bit Excel, you should register the 64-bit version of the file, which can be found in redist\x64, whereas on a machine with 32-bit Excel, you should register the 32-bit version of the file, which can be found in redist\win32.

See Also

Other Resources

DemoFeed Sample


ExcepExt Sample

Demonstrates a function extension, which catches a developer-defined exception

Overview

This sample add-in demonstrates how to use a function extension so that all generated functions contain code to catch and handle specific C++ exceptions.

Assume that you are creating XLL+ wrapper functions for a library of functions that may raise exceptions of type MyException. It becomes tedious to write code to catch these in every wrapper function, and convert the exception to an Excel error.

Tis sample project shows how to use an XLL+ function extension to define exception-handling code that will be injected into any XLL+ function that uses the extension.

We start with a global function that converts a caught exception into an Excel error string:

CopyC++
inline void ConvertException(const MyException& e, CXlOper& xloResult)
{
    xloResult = "#ERROR: " + e.getText();
}

Normally we would write code in our XLL+ implementation function to call this conversion function:

CopyC++
CXlOper* MySqrt1_Impl(CXlOper& xloResult, double x)
{
    // End of generated code
//}}XLP_SRC
    try
    {
        xloResult = CalcSquareRoot(x);
    }
    catch(const MyException& e)
    {
        ConvertException(e, xloResult);
    }
    return xloResult.Ret();
}

We can instead choose to inject code into the outer XLL+ functions (in this case MySqrt1_4 and MySqrt1_12) to trap the exception. This has the advantage of remiving the try...catch blocks from the implementation function.

CopyC++
CXlOper* MySqrt1_Impl(CXlOper& xloResult, double x)
{
    // End of generated code
//}}XLP_SRC
    xloResult = CalcSquareRoot(x);
    return xloResult.Ret();
}

The code to be injected into the outer function needs to appear at the end of the exception handling section, as an additional catch statement, just after XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult):

CopyC++
extern "C" __declspec(dllexport)
LPXLOPER12 MySqrt2_12(double x)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MySqrt2_Impl(xloResult, x));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    catch(const MyException& e) {
        ConvertException(e, xloResult);
    }
    return xloResult.Ret12();
}

Requirements

To edit the functions in this add-in, you need to load the extension file MyException.xpe which is located in the sample directory. See Loading an extension file for instructions.

The function extension

The extension is in MyException.xpe. It contains 4 essential items:

  1. A reference to MyException.h, which ensures that the code will be included in any file that uses the extension.
  2. A LocalizedDisplayName element which controls how the extension will appear in the Property Browser.
  3. A LocalizedDescription element which provoides help in the Property Browser.
  4. An Insertion element, which species the code which will be inserted by the extension, and its location, in this case: AfterCatchException. (Note that the code is wrapped in a CDATA element, so that the ampersand character can be used in the inserted code without being escaped.)

Classes and functions used

CXlOper::operator =

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file ExcepExt.sln or the project file ExcepExt.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files ExcepExt.help.xml and ExcepExt.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Function extensions (User Guide) | FunctionExtension element (Reference)


ExUIDynList Sample

Changes the contents of a value list at run-time

Remarks

This project demonstrates how to change the contents of a value list at run-time or at load-time. It contains a single worksheet function and two macro functions.

The worksheet function, MyFunction is an empty function that uses a value list. The value list is set to be exclusive and to be displayed in the Excel Formula Wizard.

The two macros, UseValueList1 and UseValueList2, each load a different value list, calling the function LoadValueList.

LoadValueList contains the interesting code: it loads a set of values, updates the extended user interface by using CXlWizExUIFunctionDescriptor::AddList, and also updates the value list constraint by using CXlValueListConstraint<long>::SetValues.

Note that the initialization of the value list occurs very late in the loading process, during an override of CXllApp::AfterXllOpen.

Classes and functions used

CXlWizExUIListProvider::CXlWizExUIListProvider | CXlWizExUIListProvider::Add | CXlWizExUIFunctionRegistry::GetInstance | CXlWizExUIFunctionRegistry::FindAddFunctionDescriptor | CXlWizExUIFunctionDescriptor::AddList | CXlValueListConstraint<INT_T>::SetValues

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file ExUIDynList.sln or the project file ExUIDynList.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files ExUIDynList.help.xml and ExUIDynList.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


FInspect Sample

Demonstrates how to inspect and display information about functions in an add-in

Overview

This sample add-in shows how to use the CXllFn class to inspect the functions contained in your add-in.

Classes and functions used

CXllApp::GetAllFns | CXllApp::FindFn | CXllFn | CXllFn::GetName | CXllFn::GetHelpText | CXllFn::GetArgumentNames | CXllFn::GetArgumentHelpTexts

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file FInspect.sln or the project file FInspect.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files FInspect.help.xml and FInspect.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


LogDemo Sample

An add-in that writes to a log

Overview

This simple add-in demonstrates the use of the XLL+ logging framework.

If the add-in is opened, the Logging/DoSomething menu is used, and Excel is then closed, something like the following will be written to the log file:

Sat Apr 11 00:13:48  5344 INFO  CLogDemoApp OnXllOpenEx() for C:\logdemo\debug\LogDemo.xll
Sat Apr 11 00:13:51  5344 FATAL Global Something very bad happened
Sat Apr 11 00:13:51  5344 ERROR Global Something quite bad happened
Sat Apr 11 00:13:51  5344 WARN  Global Something unexpected occurred
Sat Apr 11 00:13:51  5344 INFO  Global aNumber=0xff
Sat Apr 11 00:13:51  5344 DEBUG Global aNumber (in decimal)=255
Sat Apr 11 00:13:52  5344 INFO  CLogDemoApp OnXllClose() for C:\logdemo\debug\LogDemo.xll

The log file, LogDemo.log can be found in the user's temporary directory. You can view it on the command line by entering the following: type %TMP%\Logdemo.log The log is also written, in a shorter format, to the Output window of Visual Studio, when debugging.

You can control the level of logging by changing the statements in the log configuration file Logdemo.xll.log.ini. Note that the configuration file is copied to the output directory alongside the XLL file itself, as part of the project's build process.

Features

The sample demonstrates the following tasks:

  • Initializing the logging framework during OnXllOpenEx() by calling XllConfigurator::configure().
  • Emitting log items by calling the logging macros.
  • Controlling the log output by editing the log configuration file, LogDemo.xll.log.ini.

Implementation

The following steps were significant in creating and completing the LogDemo application.

  1. The checkbox "Enable Logging" was ticked in the XLL+ AppWizard.
  2. A static data member of type LoggerPtr was added to the application class CLogDemoApp. This logger was used in some member functions of CLogDemoApp.
  3. Logging macros were added to the XLL add-in functions.

Notes

Some of the events and all of add-in functions in the application contain logging macros at various levels. Change the settings in LogDemo.xll.log.ini to include and exclude various log items.

Classes and functions used

XllConfigurator::configure | Logging macros

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file LogDemo.sln or the project file LogDemo.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files LogDemo.help.xml and LogDemo.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Logging (User Guide)


PartialReg Sample

Demonstrates how to control at run-time which add-in functions are registered and which are not

Overview

This project demonstrates how to control at run-time which add-in functions are registered and which are not. This technique can be used to support different licenses or user classes.

Implementation

The significant part of the application was implemented by adding the following lines to the InitInstance() method:

CopyC++
const TCHAR* apszOptionalFns[] = { ... };

for (int i = 0; apszOptionalFns[i]; i++)
    RemoveFn(apszOptionalFns[i]);

This code removes the specified add-in functions from the list of add-in functions built in AddStaticFns(). These functions will not be registered, and will not be available from Excel.

Classes and functions used

CXllApp::RemoveFn | CWinApp::InitInstance()

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file PartialReg.sln or the project file PartialReg.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files PartialReg.help.xml and PartialReg.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


Profiling Sample

Demonstrates a function extension, which profiles the performance of add-in functions

Overview

This sample add-in demonstrates a simple function extension.

The classes in ProfilingTool.h provide a simple mechanism for measuring the performance of add-in functions. A function that wants to have its performance measured should create a Timer object, e.g.:

CopyC++
Profiling::Timer timer(theProfiler, "SlowFunc2");

When the object goes out of scope it will be destroyed, and the destructor will stop the timer and add the result to the Profiler object.

There are also two functions which report the results of the profiling. GetProfilingResults() returns the accumulated results as an array. ProfilerReport() is a macro which prints the results to the TRACE window, and also copies the results to the clipboard (from which they can be pasted into Excel or into a text file).

Requirements

To edit the functions in this add-in, you need to load the extension file Profiling.xpe which is located in the sample directory. See Loading an extension file for instructions.

The function extension

This is a good opportunity to use a function extension:

  • The code to be added is slightly different for each function - the function's name, as passed to the Timer, is different. Therefore cut/paste is tedious and error-prone. Using a function extension means that the code will be generated, and will not contain errors.
  • When you've finished profiling, you may wish to remove the profiling code from some or all functions. Later, you may wish to switch it back on. The XLL Add-ins Window makes this very easy. Select all the relevant functions in the XLL Add-ins Window and change the value of the Profile property in the Properties Browser.

The extension is in Profiling.xpe. It contains 4 essential items:

  1. A reference to ProfilingTools.h, which ensures that the code will be included in any file that uses the extension.
  2. A LocalizedDisplayName element which controls how the extension will appear in the Property Browser.
  3. A LocalizedDescription element which provoides help in the Property Browser.
  4. An Insertion element, which species the code which will be inserted by the extension, and its location.

Classes and functions used

CXlOper::GetDims | CXlOper::IsMissing | CXlOper::VectorCell | CXlOper::AllocArray | CXlOper::Cell | CXlOper::RetError | CXlOper::Ret

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file Profiling.sln or the project file Profiling.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files Profiling.help.xml and Profiling.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Function extensions (User Guide) | FunctionExtension element (Reference)


Publish Opt-In Demo Sample - PubDevIn

Applies a function filter with an Opt-In policy

Remarks

This project demonstrates how to use a function filter to restrict which add-in functions are made available to users. The project applies an Opt-In policy, so that only add-in functions whose FunctionFilterOptIn property is specifically marked as True will be available to users.

The add-in functions included in the sample fall into 3 groups:

  1. ReadyFn & ReadyFn2 are marked as FunctionFilterOptIn = True
  2. NotReadyFn & NotReadyFn2 are marked as FunctionFilterOptOut = True
  3. OtherFn & OtherFn2 are not marked

Because a function filter is being applied, ReadyFn & ReadyFn2 will be published, but NotReadyFn & NotReadyFn2 will not. Because it is an opt-in filter, OtherFn & OtherFn2, which are not marked, will not be published.

The only code added to the sample to achieve the filtering is the following:

CopyC++
#ifndef _DEBUG
CXllFunctionFilterEventHandlerOptIn theFunctionFilter;
#endif

This code declares a static global instance of CXllFunctionFilterEventHandlerOptIn, which automatically runs the filtering code just before add-in functions are registered with Excel. As a result, any function that is not marked as FunctionFilterOptIn = True will be suppressed.

Note that the code is surrounded by a #ifndef _DEBUG ... #endif block, so that the filter only applies to the Release build. This means that in the Debug build, the developer can continue to work with the functions that are filtered out.

For a discussion of function filtering, see the User Guide topic Publishing and suppressing add-in functions.

Requirements

To edit the functions in this add-in, you need to load the extension file FunctionFilter.xpe which is located in the extensions directory of your XLL+ installation. See Loading an extension file for instructions.

Classes and functions used

CXllFunctionFilter | CXllFunctionFilterEventHandlerOptIn

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file PubDevIn.sln or the project file PubDevIn.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files PubDevIn.help.xml and PubDevIn.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Publish Opt-Out Demo | Publish Run-time Demo | Publishing and suppressing add-in functions (User Guide)


Publish Opt-Out Demo Sample - PubDevOut

Applies a function filter with an Opt-Out policy

Remarks

This project demonstrates how to use a function filter to restrict which add-in functions are made available to users. The project applies an Opt-Out policy, so that only add-in functions whose FunctionFilterOptOut property is specifically marked as True will be hidden from to users.

The add-in functions included in the sample fall into 3 groups:

  1. ReadyFn & ReadyFn2 are marked as FunctionFilterOptIn = True
  2. NotReadyFn & NotReadyFn2 are marked as FunctionFilterOptOut = True
  3. OtherFn & OtherFn2 are not marked

Because a function filter is being applied, ReadyFn & ReadyFn2 will be published, but NotReadyFn & NotReadyFn2 will not. Because it is an opt-out filter, OtherFn & OtherFn2, which are not marked, will be published.

The only code added to the sample to achieve the filtering is the following:

CopyC++
#ifndef _DEBUG
CXllFunctionFilterEventHandlerOptOut theFunctionFilter;
#endif

This code declares a static global instance of CXllFunctionFilterEventHandlerOptOut, which automatically runs the filtering code just before add-in functions are registered with Excel. As a result, any function that is marked as FunctionFilterOptOut = True will be suppressed.

Note that the code is surrounded by a #ifndef _DEBUG ... #endif block, so that the filter only applies to the Release build. This means that in the Debug build, the developer can continue to work with the functions that are filtered out.

For a discussion of function filtering, see the User Guide topic Publishing and suppressing add-in functions.

Requirements

To edit the functions in this add-in, you need to load the extension file FunctionFilter.xpe which is located in the extensions directory of your XLL+ installation. See Loading an extension file for instructions.

Classes and functions used

CXllFunctionFilter | CXllFunctionFilterEventHandlerOptOut

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file PubDevOut.sln or the project file PubDevOut.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files PubDevOut.help.xml and PubDevOut.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Publish Opt-In Demo | Publish Run-time Demo | Publishing and suppressing add-in functions (User Guide)


Publish Run-time Demo Sample - PublishRT

Applies a function filter using a configuration file

Remarks

This project demonstrates how to use a function filter to restrict which add-in functions are made available to users. The project uses a configuration file to apply the policy, so that only add-in functions which are listed in the configuration file with a setting of true or 1 will be made available to users.

The configuration file should have the same root as the add-in itself, and an extension of .functionfilter: PublishRT.functionfilter. The contents of the file, as delivered, are as follows:

ReadyFn 1
ReadyFn2 1
NotReadyFn 0
NotReadyFn2 0

In the configuration file, PublishRT.functionfilter, the functions included fall into 3 groups.

  1. ReadyFn & ReadyFn2 are listed as 1
  2. NotReadyFn & NotReadyFn2 are listed as 0
  3. OtherFn & OtherFn2 are not listed

Because a function filter is being applied, ReadyFn & ReadyFn2 will be published, but NotReadyFn & NotReadyFn2 will not. Because they are not specifically listed, and the configuration file is CXllFunctionFilterLoader::EXPLICIT, OtherFn & OtherFn2 will be published.

The only code added to the sample to achieve the filtering is the following:

CopyC++
#ifndef _DEBUG
CXllFunctionFilterEventHandlerFromFile theFunctionFilter(CXllFunctionFilterLoader::EXPLICIT);
#endif

This code declares a static global instance of CXllFunctionFilterEventHandlerFromFile, which automatically runs the filtering code just before add-in functions are registered with Excel. As a result, the configuration file is loaded and parsed, and any function that is marked as 0 or false will be suppressed.

Note that the code is surrounded by a #ifndef _DEBUG ... #endif block, so that the filter only applies to the Release build. This means that in the Debug build, the developer can continue to work with the functions that are filtered out.

Inspect the build properties of the configuration file, to see that the Custom Build Tool settings have been used to deliver the file from the source directory to the output directory whenever a build occurs.

For a discussion of function filtering, see the User Guide topic Publishing and suppressing add-in functions.

Requirements

To edit the functions in this add-in, you need to load the extension file FunctionFilter.xpe which is located in the extensions directory of your XLL+ installation. See Loading an extension file for instructions.

Classes and functions used

CXllFunctionFilter | CXllFunctionFilterEventHandlerFromFile

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file PublishRT.sln or the project file PublishRT.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files PublishRT.help.xml and PublishRT.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Publish Opt-In Demo | Publish Opt-Out Demo | Publishing and suppressing add-in functions (User Guide)


Serialize Sample

Demonstrates how to serialize Excel native data types to and from streams

Overview

This sample add-in shows how to use the CXlSerialData class or the CXlOStream and CXlIStream classes to serialize and deserialize Excel data types.

Features

The sample displays the following features:

  • During OnXllOpenEx(), a menu is created, and connected to 4 add-in macro functions.
  • The macro functions SaveRange1() and RestoreRange1() respectively save and restore the current selection to and from a file (datafile_1.dat). They use the CXlSerialData class to convert the data to and from a serialized form as an array of bytes; the byte array is saved and restored to and from file using the standard fwrite() and fread() functions.
  • The macro functions SaveRange2() and RestoreRange2() also save and restore the current selection to and from a file (datafile_2.dat), but use the CXlOStream and CXlIStream classes to serialize the data directly to file.

Notes

The following line is added to serialize.cpp, to include the serialization classes.

CopyC++
#include <XlSerialize.h>

Each of the add-in functions is marked as a Macro function using the XLL+ Function Wizard.

Using CXlSerialData

When serializing data using CXlSerialData, the following code is used to serialize the data held in CXlOper xloSelection:

CopyC++
CXlSerialData data(xloSelection);
Alternatively, the following two lines could have been used:
CopyC++
CXlSerialData data;
data.CopyXlOper(xloSelection);
We can get the size and address of the serialized byte array using CXlSerialData::GetCount() and CXlSerialData::GetData(), and use these to save the data to file:
CopyC++
fwrite(data.GetData(), 1, data.GetCount(), fp);

To deserialize the saved data, two steps are required. First we must allocate an object with a big enough buffer to read all the serialized data.

CopyC++
size_t cb = [get data size from file];
CXlSerialData data(cb);
Then, after reading the data from file, we can deserialize it into a CXlOper object:
CopyC++
fread(data.GetDataBuffer(), 1, cb, fp);
CXlOper xloValue;
data.GetXlOper(xloValue);

Using CXlOStream and CXlIStream

When serializing data using CXlOStream, the following code is used to serialize the data held in CXlOper xloSelection:

CopyC++
std::ofstream os(file_name);
CXlOStream xlos(os);
xlos << &xloSelection;
os.close();

To deserialize the saved data, the reverse process is used, with CXlIStream:

CopyC++
std::ifstream is(file_name);
CXlIStream xlis(is);
CXlOper xloValue;
xlis >> xloValue;
is.close();

Classes and functions used

CXlSerialData | CXlSerialData::CXlSerialData | CXlSerialData::GetCount | CXlSerialData::GetData | CXlSerialData::GetDataBuffer | CXlOStream | CXlOStream::CXlOStream | CXlOStream::operator << | CXlIStream | CXlIStream::CXlIStream | CXlIStream::operator >> | CXlSerialData::GetDataBuffer | CXlSerialData::GetDataBuffer | ::XllGetTypedApp | CXlMacros::Selection | CXlOper::Coerce | CXllApp::XlMessageBox | CXlOper::GetActiveCell | CXlOper::GetRef | CXlOper::FromSRef

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file Serialize.sln or the project file Serialize.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files Serialize.help.xml and Serialize.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


SharedHandles Sample

Demonstrates how to share handles between separate add-ins

Overview

This solution contains the code referred to in the User Guide topic Sharing object handles between XLLs. There are two XLL projects in the solution: HandleProvider and HandleConsumer.

Requirements

To edit the functions in this add-in, you need to load the extension file StringHandles.xpe. See Loading an extension file for instructions.

You should also make sure that none of the following extension files is loaded, since the various types of handles are mutually exclusive.

  • RtdHandles.xpe
  • NumericHandles.xpe
  • StringPtrHandles.xpe

Sharing handles

The following steps were required to make handles avaialable across XLL boundaries:

  1. The StringHandles extension was selected for both XLL projects.

  2. In the XLL where the handles are produced, the following line was added before <StringHandles.h> in order to ensure that the function exported_GetCacheInstance() was created and exported.

    CopyC++
    #define NONRTDHANDLES_IMPLEMENT_EXPORT

    The function should be instantiated only once, and similarly the line was included once and only once, in this case within the file HandleProvider.cpp.

  3. In the consumer add-in, some initialization code was added to the OnOpenXLLEx() event handler, which instructed the handle manager to look in a different XLL for certain handle types:

    CopyC++
    BOOL CHandleConsumerApp::OnXllOpenEx()
{
    // Inform the controller that handles for the following object types will
    // be sourced from "HandleProvider.xll"
    psl::HandleCacheInstanceImportManager::RegisterType(L"Thing", _T("HandleProvider.xll"));
    psl::HandleCacheInstanceImportManager::RegisterType(L"test::Thing2", _T("HandleProvider.xll"));
    psl::HandleCacheInstanceImportManager::RegisterType(L"std::map<std::string,std::string>", _T("HandleProvider.xll"));
    return TRUE;
}

  4. The C++ compiler settings in both XLLs were changed to use the shared DLL versions of the Microsoft run-time libraries. For the debug builds that meant selecting Runtime library = "Multi-threaded Debug DLL (/MDd)" in the settings page "C/C++ / Code Generation". For release builds, the setting was: Runtime library = "Multi-threaded DLL (/MD)"

Classes and functions used

HandleCacheInstanceImportManager::RegisterType

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file SharedHandles.sln or the project file SharedHandles.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files SharedHandles.help.xml and SharedHandles.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | Sharing object handles between XLLs (User Guide) | StringHandleDemo sample


TFold Sample

Demonstrates the use of the CXlOper class, in a useful worksheet function that constructs and manipulates arrays

Overview

This sample add-in demonstrates the use of the CXlOper class.

The TFOLD function in the add-in is a very useful utility for creating arrays of cells from individual cells and ranges in worksheets. If you want to use an add-in function that expects arguments to be in a certain shape, you can use TFOLD to create a correctly shaped array on the fly, instead of changing your worksheet to suit the demands of the function.

Using TFOLD and TFOLDT

The TFOLD.XLS demo workbook shows TFOLD and TFOLDT is use.

A very powerful use of TFOLDT is also shown in LabelledArgs.xls, which is part of the LabelledArgs sample.

Optimization

Under Visual Studio .NET 2003, it was necessary to switch off the optimization flag /Ob2 under the Release configuration, and replace it with /Ob1. Using the /Ob2 optimization causes runtime exceptions. This compiler behavior was fixed for Visual Studio 2005, 2008 and 2010, and the standard optimization settings (/O2) can be used.

Classes and functions used

CXlOper::GetDims | CXlOper::IsMissing | CXlOper::VectorCell | CXlOper::AllocArray | CXlOper::Cell | CXlOper::RetError | CXlOper::Ret

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file TFold.sln or the project file TFold.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files TFold.help.xml and TFold.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects | LabelledArgs sample


UseTimer Sample

Demonstrates how to use a timer to execute a macro function at regular intervals

Overview

This sample add-in shows how to use the CXllApp::Excel method to run a macro function at a specific time.

Classes and functions used

CXllApp::Excel | CXlOper::GetActiveCell | CXlOper::SetValue | ::XlNow

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file UseTimer.sln or the project file UseTimer.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files UseTimer.help.xml and UseTimer.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


XlpGenDemo Sample

Demonstrates how to use the XLPGEN.EXE command-line tool

Overview

This sample add-in shows how to use the XLPGEN command-line tool to generate Excel add-in functions from XML definitions.

Sample project

Each sample project is located in a sub-directory of the Samples directory of the XLL+ installation. To use the sample project, open the solution file XlpGenDemo.sln or the project file XlpGenDemo.vcproj.

You can enable debugging under Excel by using the Setup Debugging command in the XLL+ ToolWindow.

When delivered, the help files are excluded from the build. You can enable the help build by selecting the files XlpGenDemo.help.xml and XlpGenDemo.chm in the Solution Explorer, and using the right-click menu to view Properties. Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No". See Generating help in the User Guide for more information.

See Also

List of Sample Projects


Walkthroughs

Walkthroughs give step-by-step instructions for common scenarios, which makes them a good place to start learning about the product or a particular feature area.

Arrays

Adding a vector argument
Describes how to add a one-dimensional array argument (a vector) to an add-in function.
Returning a vector result
Describes how to return a one-dimensional array argument (a vector) from an add-in function.
Adding a matrix argument
Describes how to add a two-dimensional array argument (a matrix) to an add-in function.
Returning a matrix result
Describes how to return a two-dimensional array argument (a matrix) from an add-in function.

Function Wizard Features

Grouping multiple arguments into a single Excel range
Describes how to use the Function Wizard to create an add-in function that accepts and decodes multiple arguments in a single range, so as to reduce the total number of arguments to a function.

.NET Assemblies

Importing a .NET Assembly
Demonstrates how to import a .NET assembly, and automatically generate Excel add-in functions for its methods and properties.
Importing a .NET Assembly using attributes
Demonstrates how to import a .NET assembly, and automatically generate Excel add-in functions for its methods and properties, by using attributes.

Wrapper libraries

Creating a wrapper for an add-in built using XLL+
Describes how to create a wrapper library which lets you call XLL Add-in functions directly from a C# application.

See Also

Samples and Walkthroughs


Arrays

This chapter contains the following topics:

Adding a vector argument
Returning a vector result
Adding a matrix argument
Returning a matrix result


Adding a vector argument

You can use the XLL+ Function Wizard to specify that an argument should contain a vector of a particular type, e.g. a row of strings or a column of dates. This walkthrough demonstrates how to add and use a vector argument in an add-in function.

You can find a copy of all the code used in this walkthrough in the Walkthroughs/VectorFns folder in your XLL+ installation, along with a demonstration spreadsheet, VectorFns.xls.

Creating the project

To create the project using Visual Studio

  1. From the File menu, select New and then Project to open the New Project dialog.
  2. Select the XLL+ 7 Excel Add-in project template from the list of Visual C++ Projects, and enter VectorFns in the Name box. Under Location, enter an appropriate directory in which to create the project.
  3. Accept all the default settings in the XLL+ AppWizard.

For more information about creating projects, see Creating an add-in project in the XLL+ User Guide.

Creating the function

Use the XLL+ Function Wizard to create a new add-in function and to add a vector argument.

Note: If you do not know how to start the Function Wizard, or you cannot find the command to open it, look at Invoke the Function Wizard in the User Guide.

  1. Open the source file VectorFns.cpp and click on the New XLL+ Function menu item or tool-button, to show the New Function dialog, and fill in the name as shown below.

    Name | VectorSum
    Return type | CXlOper
    Category | Math & Trig
    Description | Returns the sum of a vector

  2. Fill in the function's category and description.

    Add a new argument named Input of type Double, by typing into the arguments grid, as shown below.

  3. Click on the Vector tool, to convert the argument to a vector.

  4. The argument is now a vector of type double, as shown below.

    Type | Name | Description
    Double[] | Input | A vector of numbers

    Click on the OK button to close the Function Wizard and save the function.

Inspecting the code

  1. The following code has been added to VectorFns.cpp.

    CopyC++
    CXlOper* VectorSum_Impl(CXlOper& xloResult, const CXlOper* Input_op)
{
    // Input buffers
    std::vector<double> Input;
    // Validate and translate inputs
    XlReadVector(*Input_op, Input, L"Input", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC
    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    return xloResult.Ret();
}

    Let us examine the interesting code.

  2. Note that the argument has been declared as type const CXlOper*. The CXlOper type is usually used to pass vector and matrix values from Excel to add-in functions.

    CopyC++
    CXlOper* VectorSum_Impl(CXlOper& xloResult, const CXlOper* Input_op)

  3. A buffer variable Input is declared. The contents of the COper argument passed by Excel will be extracted and put into Input.

    CopyC++
    std::vector<double> Input;

  4. Code has been generated to read the contents of Input into vecInput.

    CopyC++
    XlReadVector(*Input_op, Input, L"Input", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK);

    Note that if the cell range passed to the function cannot be read for any reason (for example, because a cell contains a string instead of a number) then an exception will be thrown, and no further processing will take place within the function. Instead, control will pass to an outer wrapper function, which will catch the exception, and return it to Excel as an error result.

Completing the function

  1. Add code to implement the function, as shown below:

    CopyC++
    CXlOper* VectorSum_Impl(CXlOper& xloResult, const CXlOper* Input_op)
{
    // Input buffers
    std::vector<double> Input;
    // Validate and translate inputs
    XlReadVector(*Input_op, Input, L"Input", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC

    double dSum = 0.0;
    for (size_t i = 0; i < Input.size(); i++)
        dSum += Input[i];
    xloResult = dSum;
    return xloResult.Ret();
}

Testing the project

  1. Build the project, using the Build/Build Solution menu or Shift+Ctrl+B keyboard short-cut. If you are working with a 64-bit version of Excel, then be sure to select the 64-bit platform x64 before you build.
  2. When the project has been built successfully, use the Debug/Start Debugging menu or F5 keyboard short-cut to run your add-in under Excel.
  3. If Excel puts up any message boxes asking whether you trust the add-in, say yes.
  4. In a spreadsheet, put numbers into cells A1 to A6 and, in cell B1 enter a formula =VectorSum(A1:A6) to return the sum of the numbers in cells A1 to A6.
  5. Replace one of the numbers in cells A1:A6 with a non-numeric, e.g.: Fred. Note that the result is now an error message, such as: #ERROR: Expected number for Input[6]

See Also

XlReadVector method | User guide: Creating a vector argument | Samples and Walkthroughs


Returning a vector result

This walkthrough demonstrates how to use the CXlOper class to return a 1-dimensional array (vector) from an add-in function.

Two such functions are created, which construct the array result in two different ways:

  1. From an STL vector object
  2. From an array of doubles

You can find a copy of all the code used in this walkthrough in the Walkthroughs/VectorRes folder in your XLL+ installation, along with a demonstration spreadsheet, VectorRes.xls.

Creating the project

To create the project using Visual Studio

  1. From the File menu, select New and then Project to open the New Project dialog.
  2. Select the XLL+ 7 Excel Add-in project template from the list of Visual C++ Projects, and enter VectorRes in the Name box. Under Location, enter an appropriate directory in which to create the project.
  3. Accept all the default settings in the XLL+ AppWizard.

For more information about creating projects, see Creating an add-in project in the XLL+ User Guide.

Returning a numeric array using STL vector

Use the XLL+ Function Wizard to create a new add-in function and to add an argument of type unsigned short integer.

Note: If you do not know how to start the Function Wizard, or you cannot find the command to open it, look at Invoke the Function Wizard in the User Guide.

  1. Open the source file VectorRes.cpp and click on the New XLL+ Function menu item or tool-button, to show the New Function dialog, and fill in the name as shown below.

    Name | VectorToArray
    Return type | CXlOper
    Category | User Defined
    Description | Returns a numeric array using an STL vector

  2. Fill in the function's category and description. Note that the return type must be CXlOper

    Add a new argument Count of type Unsigned Short Int by typing into the arguments grid, as shown below. .

    Type | Name | Description
    Unsigned Short Int | Count | Number of items in result

    Click on the OK button to close the Function Wizard and save the function.

  3. The following function has been added to VectorRes.cpp.

    CopyC++
    CXlOper* VectorToArray_Impl(CXlOper& xloResult, unsigned short int Count)
{
    // End of generated code
//}}XLP_SRC
    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    return xloResult.Ret();
}

  4. Our task is going to be to populate xloResult with a numeric vector.

    Add the code below to set up a temporary array of numbers. (In the real world this would be a more useful data set, probably returned by a previously written function.)

    CopyC++
    CXlOper* VectorToArray_Impl(CXlOper& xloResult, unsigned short int Count)
{
    // End of generated code
//}}XLP_SRC

    // Create and populate a vector
    std::vector<double> vec(Count);
    for (USHORT i = 0; i < Count; i++)
        vec[i] = (double)(i+1);

    // Set the value of xloResult
    xloResult = vec;

    // Return contents of xloResult
    return xloResult.Ret();
}

    The important method here is the overloaded assignment operator of the CXlOper class. This populates xloResult with a copy of vec. We then return the contents of xloResult.

Returning a numeric array using an array of doubles

Use the XLL+ Function Wizard to create a new add-in function and to add an argument of type unsigned short integer.

  1. Open the source file VectorRes.cpp and click on the New XLL+ Function menu item or tool-button, to show the New Function dialog, and fill in the name as shown below.

    Name | PointerToArray
    Return type | CXlOper
    Category | User Defined
    Description | Returns a numeric array using a C array of doubles

  2. Fill in the function's category and description.

    Add a new argument Count of type Unsigned Short Int by typing into the arguments grid, as shown below.

    Type | Name | Description
    Unsigned Short Int | Count | Number of items in result

    Click on the OK button to close the Function Wizard and save the function.

  3. The following function has been added to VectorRes.cpp.

    CopyC++
    CXlOper* PointerToArray_Impl(CXlOper& xloResult, unsigned short int Count)
{
    // End of generated code
//}}XLP_SRC
    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    return xloResult.Ret();
}

  4. Our task is going to be to populate xloResult with a numeric vector.

    Add the code below to set up a temporary array of numbers. In the real world this would be a more useful data set, probably returned by a previously written function.

    CopyC++
    CXlOper* PointerToArray_Impl(CXlOper& xloResult, unsigned short int Count)
{
    // End of generated code
//}}XLP_SRC

    // Create and populate a 1-dimensional array of numbers
    double* ad = new double[Count];
    for (USHORT i = 0; i < Count; i++)
        ad[i] = (double)(i+1);

    // Set the value of xloResult
    xloResult.FromDoubleArray(ad, Count);

    // Clean up temporary array
    delete[] ad;

    // Return contents of xloResult
    return xloResult.Ret();
}

    The important function here is FromDoubleArray(). This populates xloResult with a copy of the numeric array ad. We can then safely delete ad, and return the contents of xloResult.

Testing the add-in

  1. Build the project, using the Build/Build Solution menu or Shift+Ctrl+B keyboard short-cut. If you are working with a 64-bit version of Excel, then be sure to select the 64-bit platform x64 before you build.
  2. When the project has been built successfully, use the Debug/Start Debugging menu or F5 keyboard short-cut to run your add-in under Excel.
  3. If Excel puts up any message boxes asking whether you trust the add-in, say yes.

  4. In a worksheet, select a range containing five rows and one column, and type in the formula =PointerToArray(5), as shown below.

    Then press the key combination Shift+Ctrl+Enter to enter the formula as an array formula, as shown below.

See Also

CXlOper::FromDoubleArray method | CXlOper::operator = | Samples and Walkthroughs


Adding a matrix argument

You can use the XLL+ Function Wizard to specify that an argument should contain a two-dimensional array - or matrix - of a particular type. This walkthrough demonstrates how to add and use a matrix argument in an add-in function.

The walkthrough also shows how to specify that a matrix input be square (i.e. have the same number of rows and columns).

You can find a copy of all the code used in this walkthrough in the Walkthroughs/MatrixFns folder in your XLL+ installation, along with a demonstration spreadsheet, MatrixFns.xls.

Creating the project

To create the project using Visual Studio

  1. From the File menu, select New and then Project to open the New Project dialog.
  2. Select the XLL+ 7 Excel Add-in project template from the list of Visual C++ Projects, and enter MatrixFns in the Name box. Under Location, enter an appropriate directory in which to create the project.
  3. Accept all the default settings in the XLL+ AppWizard.

For more information about creating projects, see Creating an add-in project in the XLL+ User Guide.

Creating the function

Use the XLL+ Function Wizard to create a new add-in function and to add a matrix argument.

Note: If you do not know how to start the Function Wizard, or you cannot find the command to open it, look at Invoke the Function Wizard in the User Guide.

  1. Open the source file MatrixFns.cpp and click on the New XLL+ Function menu item or tool-button, to show the New Function dialog, and fill in the name as shown below.

    2. Name | ExtractRow
Return type | CXlOper
Category | Lookup & Reference
Description | Extracts a single row from a matrix

  2. Fill in the function's category and description.

    Add two new arguments by typing into the arguments grid, as shown below.

    Type | Name | Description
    Double[][] | X | Matrix whose row is to be extracted.
    Unsigned Short Int | Row | 1-based index of row.

  3. Select the argument row containing X.

    Click on the Matrix tool, to convert the argument to a matrix.

  4. The argument is now a matrix of type double, as shown below.

  5. Click on the OK button to close the Function Wizard and save the function.

Inspecting the code

  1. The following code has been added to MatrixFns.cpp.

    CopyC++
    CXlOper* ExtractRow_Impl(CXlOper& xloResult, const CXlOper* X_op, unsigned short
    int Row)
{
    // Input buffers
    ple::mtx_ptrs<double> X;
    // Validate and translate inputs
    XlReadMatrix(*X_op, mtx_adapter(X), L"X", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC
    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    return xloResult.Ret();
}

    Let us examine the interesting code.

  2. Note that the matrix argument has been declared as type const CXlOper*. The CXlOper type is usually used to pass vector and matrix values from Excel to add-in functions.

    CopyC++
    CXlOper* ExtractRow_Impl(CXlOper& xloResult, const CXlOper* X_op, unsigned short
    int Row)

  3. A buffer variable X is declared. The contents of the CXlOper argument passed by Excel will be extracted and put into X.

    ple::mtx_ptrs<double> X;

    The container class for the matrix is ple::mtx_ptrs.

    Note: If you wish to use a different container class, for instance a matrix class that is used to pass values to your existing functions, you can use the XLL+ Function Wizard to change the container class.

  4. Code has been generated to read the contents of X_op into X.

    XlReadMatrix(*X_op, mtx_adapter(X), L"X", XLA_TRUNC_ONEMPTY| XLA_TRUNC_ONBLANK);

    Note that if the cell range passed to the function cannot be read for any reason (for example, because a cell contains a string instead of a number) then an exception of type CXlConversionException will be thrown, input validation will cease, and a useful message will be returned to Excel.

Completing the function

  1. Add code to implement the function, as shown below:

    CopyC++
    CXlOper* ExtractRow_Impl(CXlOper& xloResult, const CXlOper* X_op, unsigned short
    int Row)
{
    // Input buffers
    ple::mtx_ptrs<double> X;
    // Validate and translate inputs
    XlReadMatrix(*X_op, mtx_adapter(X), L"X", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC

    // Check the 1-based index
    if (Row < 1 || Row > X.size(0))
        throw CXlOutOfRangeException();
    size_t r = (size_t)(Row - 1);

    // Create a vector to receive the row
    std::vector<double> extract;
    for (size_t i = 0; i < X.size(1); i++)
        extract.push_back(X[r][i]);

    // Return the vector
    xloResult = extract;
    return xloResult.Ret();
}
  2. Note the use of the size() method to get the size of the matrix in each dimension.

  3. Notice how the items in the matrix can be accessed exactly as if the matrix was an array.

    extract.push_back(X[r][i]);

    This behaviour is made possible by the overloaded operator:

    mtx_ptrs<T>::operator const T**() const

Testing the add-in

  1. Build the project, using the Build/Build Solution menu or Shift+Ctrl+B keyboard short-cut. If you are working with a 64-bit version of Excel, then be sure to select the 64-bit platform x64 before you build.
  2. When the project has been built successfully, use the Debug/Start Debugging menu or F5 keyboard short-cut to run your add-in under Excel.
  3. If Excel puts up any message boxes asking whether you trust the add-in, say yes.

  4. Test the function by entering a matrix of numbers, and then using the ExtractRow function to extract one row, as shown below:

    Because ExtractRow is an array formula, you need to type Shift+Ctrl+Enter to enter it. Note the curly braces around the formula, indicating an array formula.

Constraining the matrix to be square

You can use the XLL+ Function Wizard to constrain the input matrix to be square.

  1. In Visual Studio, use the Tools/XLL+ Function Wizard menu to return to ExtractRow.

  2. Select the row containing X and click on the Argument Details tool.

  3. Select the Matrix tab, and click on the drop-down button for Height is equal to. Select "widthOfX".

  4. Press OK to accept the changes to X, and the new constraint will be displayed in the Function Wizard.

Changes to the code

Examine the code in MatrixFns.cpp:

CopyC++
CXlOper* ExtractRow_Impl(CXlOper& xloResult, const CXlOper* X_op, unsigned short
    int Row)
{
    // Input buffers
    ple::mtx_ptrs<double> X;
    // Named bounds
    long widthOfX = -1;
    // Validate and translate inputs
    XlReadMatrix(*X_op, mtx_adapter(X), L"X", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK, &widthOfX, 0, &widthOfX);
    // End of generated code
//}}XLP_SRC

    ...
}

A new local variable, widthOfX has been declared, with an initial value of -1. This is passed to XlReadMatrix() as the expected width of X and also as the expected height of X.

If the height of X is not found to be equal to its width then an exception of type CXlConversionException will be thrown, input validation will stop, and an error message will be returned to Excel, such as:

#ERROR: Expected 4 columns for X

See Also

XlReadMatrix method | User guide: Matrix arguments | mtx_ptrs<T> class | Samples and Walkthroughs


Returning a matrix result

This walkthrough demonstrates how to use the CXlOper class to return a 2-dimensional array (vector) from an add-in function.

Three such functions are created, which construct the array result in three different ways:

  1. From a C++ two-dimensional array class
  2. From an array of pointers to double
  3. "By hand", to create an array of mixed type

You can find a copy of all the code used in this walkthrough in the Walkthroughs/MatrixRes folder in your XLL+ installation, along with a demonstration spreadsheet, MatrixRes.xls.

Creating the project

To create the project using Visual Studio

  1. From the File menu, select New and then Project to open the New Project dialog.
  2. Select the XLL+ 7 Excel Add-in project template from the list of Visual C++ Projects, and enter MatrixRes in the Name box. Under Location, enter an appropriate directory in which to create the project.
  3. Accept all the default settings in the XLL+ AppWizard.

For more information about creating projects, see Creating an add-in project in the XLL+ User Guide.

Returning a numeric array using an array class

Use the XLL+ Function Wizard to create a new add-in function and to add a pair of unsigned short integer arguments.

Note: If you do not know how to start the Function Wizard, or you cannot find the command to open it, look at Invoke the Function Wizard in the User Guide.

  1. Open the source file MatrixRes.cpp and click on the New XLL+ Function menu item or tool-button, to show the New Function dialog, and fill in the name as shown below.

    Name | MatrixClass
    Return type | CXlOper
    Category | User Defined
    Description | Returns an array of the specified size

  2. Fill in the function's category and description.

    Add two new arguments by typing into the arguments grid, as shown below.

    Type | Name | Description
    Unsigned Short Int | Rows | Number of rows to return
    Unsigned Short Int | Columns | Number of columns to return

  3. Click on the OK button to close the Function Wizard and save the function.

  4. The following code has been added to MatrixRes.cpp.

    CopyC++
    CXlOper* MatrixClass_Impl(CXlOper& xloResult, unsigned short int Rows, unsigned
    short int Columns)
{
    // End of generated code
//}}XLP_SRC
    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    return xloResult.Ret();
}

  5. Add some lines of code to (i) check that the array is not empty, (ii) create a matrix object, (iii) populate it and (iv) return its values to Excel.

    CopyC++
    CXlOper* MatrixClass_Impl(CXlOper& xloResult, unsigned short int Rows, unsigned
    short int Columns)
{
    // End of generated code
//}}XLP_SRC

    if (Rows == 0 || Columns == 0)
        throw CXlErrorException(xlerrValue);

    // Create and populate the matrix object
    ple::mtx_ptrs<double> m(Rows, Columns);
    long value = 0;
    for (USHORT i = 0; i < Rows; i++)
        for (USHORT j = 0; j < Columns; j++)
            m[i][j] = (double)++value;

    // Return it to Excel
    xloResult = m;
    return xloResult.Ret();
}

  6. The code to return the matrix is very simple:

    xloResult = m;

    This calls one of the many overloads of the CXlOper = operator which simply copies the matrix into the CXlOper.

Returning a numeric array using an array of pointers

Use the XLL+ Function Wizard to create a new add-in function and to add a pair of unsigned short integer arguments.

Note: If you do not know how to start the Function Wizard, or you cannot find the command to open it, look at Invoke the Function Wizard in the User Guide.

  1. Open the source file MatrixRes.cpp and click on the New XLL+ Function menu item or tool-button, to show the New Function dialog, and fill in the name as shown below. Instruct the Wizard to copy the signature of MatrixClass. This will save you having to fill in the rest of the function's specification.

    Name | NumericArray
    Return type | CXlOper
    Category | User Defined
    Description | Returns an array of the specified size

  2. The function's category, description and arguments will all be filled in.

    Type | Name | Description
    Unsigned Short Int | Rows | Number of rows to return
    Unsigned Short Int | Columns | Number of columns to return

  3. Click on the OK button to close the Function Wizard and save the function.

  4. The following code has been added to MatrixRes.cpp.

    CopyC++
    CXlOper* NumericArray_Impl(CXlOper& xloResult, unsigned short int Rows, unsigned
    short int Columns)
{
    // End of generated code
//}}XLP_SRC
    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    return xloResult.Ret();
}

  5. Add some lines of code to (i) check that the array is not empty, (ii) create a matrix object, (iii) populate it, (iv) return its values to Excel and (v) delete the array.

    CopyC++
    CXlOper* NumericArray_Impl(CXlOper& xloResult, unsigned short int Rows, unsigned
    short int Columns)
{
    // End of generated code
//}}XLP_SRC

    if (Rows == 0 || Columns == 0)
        throw CXlErrorException(xlerrValue);

    // Create and populate the array
    double** aad = new double*[Rows];
    long value = 0;
    for (USHORT i = 0; i < Rows; i++)
    {
        aad[i] = new double[Columns];
        for (USHORT j = 0; j < Columns; j++)
            aad[i][j] = (double)++value;
    }

    // Return it to Excel
    xloResult.FromDoubleArray(aad, Rows, Columns, TRUE);

    // Delete the array
    for (USHORT i = 0; i < Rows; i++)
        delete[] aad[i];
    delete[] aad;

    return xloResult.Ret();
}

  6. The important function here is of course FromDoubleArray(). This populates xloResult with a copy of the numeric array aad. The fourth argument to FromDoubleArray(), BOOL bByRows, is set to TRUE, so that the array is laid out with rows representing the continuous data held in each pointer member of aad[]. To transpose the array, set the argument to FALSE. We can then safely delete aad, and return the contents of xloResult.

Returning a mixed array

Use the XLL+ Function Wizard to create a new add-in function and to add an unsigned short integer arguments.

  1. Activate the source file MatrixRes.cpp and click on the New XLL+ Function menu item or tool-button, to show the New Function dialog, and fill in the name as shown below.

    Name | MixedArray
    Return type | CXlOper
    Category | User Defined
    Description | Returns an array of mixed types

  2. Fill in the function's details and add a new argument Rows of type Unsigned Short Int, by typing into the arguments grid, as shown below. Note that the return type must again be CXlOper.

    Type | Name | Description
    Unsigned Short Int | Rows | Number of rows to return

    Click on the OK button to close the Function Wizard and save the function.

  3. The following function has been added to MatrixRes.cpp.

    CopyC++
    CXlOper* MixedArray_Impl(CXlOper& xloResult, unsigned short int Rows)
{
    // End of generated code
//}}XLP_SRC
    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    return xloResult.Ret();
}

  4. Our task is going to be to populate xloResult with a mixed array.

    Add the code below to set up a two-dimensional array of cells. Each row of cells contains a number and a string.

    CopyC++
    CXlOper* MixedArray_Impl(CXlOper& xloResult, unsigned short int Rows)
{
    // End of generated code
//}}XLP_SRC

    if (Rows == 0)
        throw CXlErrorException(xlerrValue);

    xloResult.AllocArray(Rows, 2);
    for (USHORT i = 0; i < Rows; i++)
    {
        xloResult.Cell(i, 0) = (double)i;
        xloResult.Cell(i, 1) = "A string";
    }
    return xloResult.Ret();
}

    First we test that Rows is non-zero, and fail if it is not.

    Then we use AllocArray() to turn xloResult into an array with Rows rows and 2 columns.

    Next, we populate each row of xloResult, using the Cell() method to access each cell.

    Finally we return the contents of xloResult to Excel, as usual.

Testing the add-in

  1. Build the project, using the Build/Build Solution menu or Shift+Ctrl+B keyboard short-cut. If you are working with a 64-bit version of Excel, then be sure to select the 64-bit platform x64 before you build.
  2. When the project has been built successfully, use the Debug/Start Debugging menu or F5 keyboard short-cut to run your add-in under Excel.
  3. If Excel puts up any message boxes asking whether you trust the add-in, say yes.

  4. In a worksheet, select a range containing two rows and three columns, and type in the formula =NumericArray(2,3), as shown below.

    Then press the key combination Shift+Ctrl+Enter to enter the formula as an array formula.

See Also

CXlOper::FromDoubleArray method | CXlOper::AllocArray method | CXlOper::Cell method | Samples and Walkthroughs


Function Wizard Features

This chapter contains the following topics:

Grouping multiple arguments into a single Excel range


Grouping multiple arguments into a single Excel range

Excel versions before 2007 only accept a limited number of arguments - 30. Therefore, you may sometimes find it convenient to group multiple arguments into a single input range. For instance, if your function accepts 35 arguments, you can group 6 related arguments together and require that they be passed in a single range of size 1 x 6 or 6 x 1.

The Function Wizard lets you specify grouped arguments, and generates code to read them from Excel ranges into local variables.

This walkthrough demonstrates how to create an add-in function that accepts grouped arguments.

Our add-in function will combine Excel's NORMDIST and NORMSDIST built-in functions, by accepting a value, and optionally a range containing a mean and standard deviation. If the range is omitted, then defaults of 0 and 1 will be used for the mean and the standard deviation respectively.

In a real-world example, a function would have dozens of other arguments. Grouping arguments when there is no need to is confusing and irritating for the user. We only do it here for the sake of a simpler example.

This walkthrough also covers two other areas:

  • Optional arguments (with default values).
  • Calling built-in Excel functions.

You can find a copy of all the code used in this walkthrough in the Walkthroughs/GroupedArgs folder in your XLL+ installation, along with a demonstration spreadsheet, GroupedArgs.xls.

Creating the project

To create the project using Visual Studio

  1. From the File menu, select New and then Project to open the New Project dialog.
  2. Select the XLL+ 7 Excel Add-in project template from the list of Visual C++ Projects, and enter GroupedArgs in the Name box. Under Location, enter an appropriate directory in which to create the project.
  3. Accept all the default settings in the XLL+ AppWizard.

For more information about creating projects, see Creating an add-in project in the XLL+ User Guide.

Creating the function

Note: If you do not know how to start the Function Wizard, or you cannot find the command to open it, look at Invoke the Function Wizard in the User Guide.

  1. If you are not already editing GroupedArgs.cpp, open it, using the Visual Studio Solution Explorer.

  2. Use the XLL+ Function Wizard to add a new function, GroupedFn, filling in the function's name as shown below:

    Name | GroupedFn
    Return type | CXlOper
    Category | Statistical
    Description | Function with grouped arguments

  3. Fill in the function's category and description.

    Add three numeric arguments, as shown below:

    Type | Name | Description
    Double | X | is the value for which you want the distribution
    Double | Mean | is the arithmetic mean of the distribution
    Double | StdDev | is the standard deviation of the distribution

  4. Select the row containing Mean, and click on the Argument details button (shown below) or press the Alt+Enter keys.

  5. In the Argument Details window, set Mean to be optional, and to have a default value of 0.0, and click "OK".

  6. Repeat the process with the third argument, StdDev, but with a default value of 1.0.

    The arguments should now appear as follows:

    Type | Name | Description
    Double | X | is the value for which you want the distribution
    Double (=0.0) | Mean | is the arithmetic mean of the distribution
    Double (=1.0) | StdDev | is the standard deviation of the distribution

  7. Select the second argument, Mean, and press Shift + Down-arrow to select both the second and third arguments.

  8. Click on the Group tool-button (shown in red below).

  9. A new argument Group1 has been added to the function, and Mean and StdDev are both within the group.

  10. Change the name of the group to be Distribution.

  11. Scroll right until the Description column is fully visible, and inspect the list of descriptions that drop down when you click on the down-arrow.

    Select the style which best fits the group. If you add new items to the group later, or reorder or edit the existing items, the description will automatically be updated to include the changes.

  12. Click OK to accept the new function and close the Wizard.

Examining the code

  1. The Wizard has added code to GroupedArgs.cpp, as shown below.

    CopyC++
    CXlOper* GroupedFn_Impl(CXlOper& xloResult, double X, const CXlOper*
    Distribution)
{
    // Input buffers
    double Mean;
    double StdDev;
    // Validate and translate inputs
    static CScalarConvertParams<double> Mean__params(L"Mean", XLA_DEFAULT_EMPTY|
        XLA_OPER_IS_GROUP, L"Distribution", 0, (double)0.0);
    XlReadScalar(*Distribution, Mean, Mean__params);
    static CScalarConvertParams<double> StdDev__params(L"StdDev",
        XLA_DEFAULT_EMPTY|XLA_OPER_IS_GROUP, L"Distribution", 1, (double)1.0);
    XlReadScalar(*Distribution, StdDev, StdDev__params);
    // End of generated code
//}}XLP_SRC
    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    return xloResult.Ret();
}

  2. Examine the lines of code that extract the value Mean from the grouped argument Distribution:

    CopyC++
    double Mean;
static CScalarConvertParams<double> Mean__params(L"Mean", XLA_DEFAULT_EMPTY|
    XLA_OPER_IS_GROUP, L"Distribution", 0, (double)0.0);
XlReadScalar(*Distribution, Mean, Mean__params);

    XlReadScalar() is used to extract Mean from the Excel argument Distribution. The two parameters 0, L"Mean" (passed to XlReadScalar in the CScalarConvertParams object) are used to search the Excel array input named Distribution, by order and by name. The flag value XLA_OPER_IS_GROUP instructs XlReadScalar that the argument is a member of a group.

    If the item cannot be found, or is empty, then the default value, 0.0, is used. If the item is found, but cannot be converted to a number, then an exception of type CXlConversionException will be thrown, and input validation will stop immediately.

Adding the code

  1. Add some code to the add-in function to delegate all the work to the Excel built-in function NORMDIST, as shown below:
    CopyC++
    CXlOper* GroupedFn_Impl(CXlOper& xloResult, double X, const CXlOper*
    Distribution)
{
    // Input buffers
    double Mean;
    double StdDev;
    // Validate and translate inputs
    static CScalarConvertParams<double> Mean__params(L"Mean", XLA_DEFAULT_EMPTY|
        XLA_OPER_IS_GROUP, L"Distribution", 0, (double)0.0);
    XlReadScalar(*Distribution, Mean, Mean__params);
    static CScalarConvertParams<double> StdDev__params(L"StdDev",
        XLA_DEFAULT_EMPTY|XLA_OPER_IS_GROUP, L"Distribution", 1, (double)1.0);
    XlReadScalar(*Distribution, StdDev, StdDev__params);
    // End of generated code
//}}XLP_SRC

    // xlfNormdist was looked up in the following XLL+ help topic:
    // Section: Technical Notes
    // Topic  : Excel built-in function numbers (Alphabetical order)
    static int xlfNormdist = 293;

    // Call Excel's built-in function NORMDIST
    xloResult.Excel(xlfNormdist, 4, &CXlOper(X), &CXlOper(Mean),
        &CXlOper(StdDev), &CXlOper(FALSE));

    // Return results of call to NORMDIST
    return xloResult.Ret();
}
  2. Note that for clarity, the function number of the built-in Excel functions is declared as a named static value: static int xlfNormdist = 293; This number was found by looking up the function in the table Excel built-in function numbers.

Testing the add-in

  1. Build the project, using the Build/Build Solution menu or Shift+Ctrl+B keyboard short-cut. If you are working with a 64-bit version of Excel, then be sure to select the 64-bit platform x64 before you build.
  2. When the project has been built successfully, use the Debug/Start Debugging menu or F5 keyboard short-cut to run your add-in under Excel.
  3. If Excel puts up any message boxes asking whether you trust the add-in, say yes.

  4. Set a break-point in your source code on the following line.

    CopyC++
    xloResult.Excel(xlfNormdist, 4, &CXlOper(X), &CXlOper(Mean),
    &CXlOper(StdDev), &CXlOper(FALSE));
  5. In a spreadsheet cell, enter the following formula:
    =GroupedFn(2.3)
  6. Observe that the values of the local variables have been set to their default values.
  7. In a spreadsheet cell, enter the following formula:
    =GroupedFn(2.3,{1,2})
  8. Observe that the values of the local variables Mean and StdDev have been set to 1.0 and 2.0 respectively.
  9. In a spreadsheet cell, enter the following formula:
    =GroupedFn(2.3, {1, "Fred"})
    Note that an informative error message is returned:
    #ERROR: Expected number for Distribution[2] (StdDev)

Extracting the values

In the formulae above, the Distribution argument was entered directly, as a pair of values, e.g. {1,2}. Normally, users would enter the argument as a range of cells. The function XlReadScalar does the work of unwrapping the values from the array argument.

Vector form

The grouped argument Distribution can be a vector containing the required elements in order, e.g.:

or

Labelled form

Alternatively, the grouped argument can contain two columns or rows, with labels in one and matching values in the other:

Note that if labels are used the values can be in any order.

Interactive help

If you build the interactive help for the project, you will see that the following help is available to the user if they click on "Help on this function" in the Excel Formula Wizard.

This sort of help is essential for grouped arguments, which require extra care during input. See Help in the User guide for information on how to generate interactive help for an add-in.

See Also

Excel built-in function numbers | Samples and Walkthroughs


.NET Assemblies

This chapter contains the following topics:

Importing a .NET Assembly
Importing a .NET Assembly using attributes


Importing a .NET Assembly

This walkthrough demonstrates how to import a .NET assembly, and automatically generate Excel add-in functions for its methods and properties.

You can find a copy of all the code used in this walkthrough in the Walkthroughs/NetWrap folder in your XLL+ installation, along with a demonstration spreadsheet, NetWrap.xls.

Run-time requirements

Please note that if you are using Visual Studio 2005, you must have Service Pack 1 installed in order to build a valid XLL.

If the add-in fails to load into Excel at run-time, please see the technical note .NET requirements.

In order to build MyLib.dll, you need the C# project system to be installed on your computer.

Creating the add-in project

  1. From the File menu, select New and then Project to open the New Project dialog.

  2. Select the XLL+ 7 Excel Add-in project template from the list of Visual C++ Projects, and enter NetWrap in the Name box. Under Location, enter an appropriate directory in which to create the project.

  3. Put a tick next to "Create directory for solution", and click OK.

  4. In the "Application Settings" page of the XLL+ AppWizard, put a tick against Common Language Runtime Support (/clr).

  5. Click Finish to create the new add-in project.

For more information about creating projects, see Creating an add-in project in the XLL+ User Guide.

Creating the imported .NET assembly

Now create a new C# project and add it to the solution.

  1. In the Visual Studio Solution Explorer window, right-click and select Add/New Project....

  2. Select the Visual C# project type in the tree on the left-hand side, and select Class Library in the list on the right.

  3. Enter MyLib for the project Name, and accept the default Location. Press OK.

  4. Open the project properties of MyLib, and, in the Build page, towards the bottom of the page, put a tick against XML documentation file.

  5. Open Class1.cs and replace all the code with the code below.

CopyC#
using System;
using System.ComponentModel;

namespace MyLib
{
    /// <summary>
    /// Contains static calls to test parameter &amp; return types
    /// </summary>
    public class TestClass
    {
        /// <summary>
        /// returns the concatenation of the arguments.
        /// </summary>
        /// <param name="a">is a string</param>
        /// <param name="b">is a number</param>
        /// <param name="c">is an integer</param>
        /// <param name="d">is a boolean</param>
        /// <returns></returns>
        public static string T1(string a, double b, int c, bool d)
        {
            return String.Format("a={0};b={1};c={2};d={3}",
                a, b, c, d);
        }
        /// <summary>
        /// returns an array of strings which are concatenations
        /// of the arguments.
        /// </summary>
        /// <param name="a">is a vector of strings</param>
        /// <param name="b">is a vector of numbers. It must be the same length as a.</param>
        /// <param name="c">is a vector of integers. It must be the same length as a.</param>
        /// <param name="d">is a vector of booleans. It must be the same length as a.</param>
        public static string[] T2(string[] a, double[] b,
            int[] c, bool[] d)
        {
            if (a.Length != b.Length)
                throw new ArgumentException(String.Format("Expected {0} items for b", a.Length));
            if (a.Length != c.Length)
                throw new ArgumentException(String.Format("Expected {0} items for c", a.Length));
            if (a.Length != d.Length)
                throw new ArgumentException(String.Format("Expected {0} items for d", a.Length));
            string[] res = new string[a.Length];
            for (int i = 0; i < res.Length; i++)
                res[i] = T1(a[i], b[i], c[i], d[i]);
            return res;
        }
        /// <summary>
        /// is a test function with
        /// irritating
        /// formatting.
        /// </summary>
        /// <param name="a">is partly this,
        /// and partly that</param>
        /// <param name="b">is &gt; <paramref name="a"/></param>
        /// <returns></returns>
        public static int T3(int a, int b)
        {
            return a + b;
        }
        /// <summary>
        /// A test function that adds two numbers, with formatted comments,
        /// some of which
        /// are
        /// on
        /// <i>separate</i>
        /// lines.
        /// </summary>
        /// <param name="a">is the first number</param>
        /// <param name="b">is the second number</param>
        /// <returns>the sum of the numbers</returns>
        public static double T4(double a, double b)
        {
            return a + b;
        }

        [Description("is described in a ComponentModel description.")]
        public static double T5(
            [Description("is a matrix of numbers")] double[,] a,
            [Description("is another matrix of numbers")] double[,] b)
        {
            return 0.0;
        }

        /// <summary>
        /// A publicly visible enumerated type
        /// </summary>
        public enum MyEnum
        {
            Zero,
            One,
            Two,
            Three
        }
        /// <summary>
        /// Returns the value of an enum
        /// </summary>
        /// <param name="e">A value of type MyEnum</param>
        /// <returns>The numeric value of e</returns>
        public static double T6(MyEnum e)
        {
            return (double)(int)e;
        }
        /// <summary>
        /// Returns the length of an array of MyEnum's.
        /// </summary>
        /// <param name="enums">An array of values of type MyEnum</param>
        /// <returns>The length of the array</returns>
        public static int T7(MyEnum[] enums)
        {
            return enums.Length;
        }
        /// <summary>
        /// Returns a value of variable type
        /// </summary>
        /// <param name="type">controls the type of value returned</param>
        /// <returns>an object, which is transformed to the appropriate Excel type by the generated code.</returns>
        public static object T8(int type)
        {
            switch (type)
            {
                case 0:
                    return 123.45;
                case 1:
                    return "A string";
                case 2:
                    return true;
                case 3:
                    return (Decimal)99.99;
                case 10:
                    return new double[] { 1.2, 3.4, 5.6 };
                case 11:
                    return new string[] { "The", "cat", "sat" };
                case 12:
                    return new bool[] { true, false, false, true };
                case 13:
                    return new Decimal[] { (Decimal)10.5, (Decimal)99999.90 };
                case 14:
                    return new object[] { (double)123.45, true, "A string in an array" };
                case 20:
                    {
                        double[,] res = new double[2, 3];
                        res[0, 0] = 0.0;
                        res[0, 1] = 0.1;
                        res[0, 2] = 0.2;
                        res[1, 0] = 1.0;
                        res[1, 1] = 1.1;
                        res[1, 2] = 1.2;
                        return res;
                    }
                case 21:
                    {
                        string[,] res = new string[3, 2];
                        res[0, 0] = "One";
                        res[0, 1] = "Two";
                        res[1, 0] = "Three";
                        res[1, 1] = "Four";
                        res[2, 0] = "Five";
                        res[2, 1] = "Six";
                        return res;
                    }
                case 22:
                    {
                        object[,] res = new object[2, 3];
                        res[0, 0] = 123.45;
                        res[0, 1] = "Two";
                        res[0, 2] = true;
                        res[1, 0] = (Decimal)99.99;
                        res[1, 1] = "Three";
                        res[1, 2] = false;
                        return res;
                    }
            }
            throw new ArgumentException("unexpected value for type", "type");
        }
    }

    /// <summary>
    /// A factory class for creating Things.
    /// </summary>
    public static class Factory
    {
        /// <summary>
        /// Create a Thing using the default key.
        /// </summary>
        /// <returns></returns>
        public static Thing CreateObject()
        {
            return CreateObject(Thing.DefaultKey);
        }
        /// <summary>
        /// Create a Thing using the specified key.
        /// </summary>
        /// <param name="key">is a string key.</param>
        public static Thing CreateObject(string key)
        {
            return new Thing(key);
        }
    }

    /// <summary>
    /// A class with properties and instance methods.
    /// </summary>
    public class Thing : IDisposable
    {
        /// <summary>
        /// The key used if none is supplied.
        /// </summary>
        public const string DefaultKey = "a_default_key";
        private string key;
        /// <summary>
        /// The key to the object
        /// </summary>
        public string Key
        {
            get { return key; }
            set { key = value; }
        }

        /// <summary>
        /// Returns the length of the object's key
        /// </summary>
        /// <returns></returns>
        public int KeyLen()
        {
            return key.Length;
        }

        internal Thing(string key)
        {
            count++;
            System.Diagnostics.Trace.WriteLine(String.Format(
                "Constructing Thing({0}); count = {1}", key, count));
            this.key = key;
        }

        /// <summary>
        /// An indexed property
        /// </summary>
        /// <param name="index">A zero-based index into the key</param>
        /// <returns></returns>
        public string this[int index]
        {
            get
            {
                return key.Substring(index, 1);
            }
        }

        /// <summary>
        /// Compares two Things by value
        /// </summary>
        /// <param name="thing1">First thing</param>
        /// <param name="thing2">Second thing</param>
        /// <returns></returns>
        public static int Compare(Thing thing1, Thing thing2)
        {
            if (thing1 == null)
                return (thing2 == null) ? 0 : -1;
            if (thing2 == null)
                return 1;
            return String.Compare(thing1.Key, thing2.Key);
        }

        /// <summary>
        /// Concatenates the keys of a vector of Things
        /// </summary>
        /// <param name="things">Vector of Things</param>
        /// <returns></returns>
        public static string Combine(Thing[] things)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (Thing t in things)
                sb.Append(t.Key);
            return sb.ToString();
        }

        /// <summary>
        /// Finds the highest-sorted key in a matrix of Things
        /// </summary>
        /// <param name="things">2-dimensional array of things</param>
        /// <returns></returns>
        public static string MaxKey(Thing[,] things)
        {
            string max = "";
            for (int i = 0; i < things.GetLength(0); i++)
            {
                for (int j = 0; j < things.GetLength(1); j++)
                {
                    if (max == ""
                     || String.Compare(things[i, j].Key, max) > 0)
                        max = things[i, j].Key;
                }
            }
            return max;
        }
        /// <summary>
        /// Takes untyped arguments
        /// </summary>
        /// <param name="scalarArg">An untyped value</param>
        /// <param name="vectorArg">A vector of untyped values</param>
        /// <param name="matrixArg">A matrix of untyped values</param>
        /// <returns></returns>
        public static object VarArgTest(object scalarArg, object[] vectorArg, object[,] matrixArg)
        {
            object[] result = new object[vectorArg.Length + 2];
            result[0] = scalarArg;
            Array.Copy(vectorArg, 0, result, 1, vectorArg.Length);
            result[result.Length - 1] = String.Format("{0} x {1}", matrixArg.GetLength(0), matrixArg.GetLength(1));
            for (int i = 0; i < result.Length; i++)
                if (result[i] == null)
                    result[i] = "";
            return result;
        }

        /// <summary>
        /// A public enumeration
        /// </summary>
        public enum Periods
        {
            Monthly = 12,
            Quarterly = 4,
            SemiAnnual = 2,
            Annual = 1
        }
        /// <summary>
        /// Calculates the discount factor for a given period and interest rate
        /// </summary>
        /// <param name="rate">is the interest rate</param>
        /// <param name="period">is a time period</param>
        /// <returns></returns>
        public static double DiscountFactor(double rate, Periods period)
        {
            return Math.Exp((-1.0/((double)(int)period)) * rate);
        }

        /// <summary>
        /// Returns a forex rate for the specified currency
        /// </summary>
        /// <param name="ccy">is an ISO currency code</param>
        /// <returns></returns>
        public static double GetSpotRate(string ccy)
        {
            switch (ccy)
            {
                case "USD": return 1.0;
                case "JPY": return 85.34;
                case "AUD": return 0.8916;
                case "EUR": return 1.2725;
                case "GBP": return 1.5566;
            }
            throw new ArgumentException("Unknown currency");
        }

        /// <summary>
        /// A public shared count of existing objects.
        /// </summary>
        public static int count = 0;
        void IDisposable.Dispose()
        {
            System.Diagnostics.Trace.WriteLine(String.Format(
                "Disposing Thing({0}); count = {1}", key, count));
        }

        /// <summary>
        /// The finalizer, called when the Thing is actually destroyed.
        /// </summary>
        ~Thing()
        {
            count--;
            System.Diagnostics.Trace.WriteLine(String.Format(
                "Finalized Thing({0}); count = {1}", key, count));
        }

    }

}

Add a reference to the assembly

Before we can import the .NET assembly, we must create a reference to it.

  1. In Solution Explorer, find the node for the project NetWrap and right-click it. Select Properties.

  2. In the Project Properties window, select the node "Common Properties/References", and click the "Add New Reference..." button.

  3. You may have to wait a long time for the "Add Reference" window to appear.

  4. In the "Add Reference" window, select the tab "Projects", select "MyLib" in the list, and press OK.

  5. In the Project Properties window, click OK to save your changes.

  6. You should now build the solution (Shift+Ctrl+B), and make sure that both projects built successfully. Make sure that the build is set to either "Win32" or "x64"; avoid "Mixed Platforms". Also, if necessary, use the Build/Configuration Manager... command to open the solution configuration window, and ensure that both projects have a tick in the "Build" column.

Importing the assembly

In these steps you will set up a link between the two project. Once it is done, the build process will include an extra step, which inspects the .NET assembly and generates wrapper add-in functions for all the exported methods and properties. Whenever the .NET assembly is changed, this code will be regenerated during the next build.

  1. Open the main source file of the add-in project, NetWrap.cpp.

  2. Activate the XLL Add-ins tool window (View/Other Windows/XLL Add-ins).

  3. Click on Import Assemblies... in the Tools menu.

  4. In the list of assemblies, put a check against MyLib.

  5. Click on the Edit button, to edit the list of methods that will be exported from MyLib.

Controlling the import

  1. Using the main toolbar of the Import Editor, make sure that the Tree view is active, rather than the List view.

  2. In the tree view on the left of the window, expand the root node "MyLib", and select the type "TestClass". In the property grid, set the Filter value to "StaticMethods", as shown below.

    This will cause all of the public static methods of TestClass to be exported, as shown below.

  3. Select the type "Factory". In the property grid, set the Filter value to "StaticMethods".

  4. Expand the type "Factory", until you can see both of its public methods. Note that both methods have the same name, "CreateObject". C# supports overloading, but Excel does not. So, for at least one of these methods, we need to change the name exported to Excel.

    Select the version of "CreateObject" which has no arguments, and, using the property grid, change its ExportedName to Factory.CreateDefaultObject.

  5. Select the type "Thing", and set its Filter to "StaticMethods, InstanceMethods, InstanceProperties", by checking three boxes in the drop-down box, as shown below.

  6. Expand the type "Thing" until you can see all its methods. Select and expand the "DiscountFactor" method. Select the "period" argument.

    In the property grid, set the ShowValueListInFormulaWizard property to True.

    Because "period" is an Enum, and the ShowValueListInFormulaWizard property has been set, a Value List will be created which will be displayed in the Excel Formula Wizard at run-time:

  7. In the tree view, select and expand the "GetSpotRate" method of the "Thing" class. Select the "ccy" argument.

    In the property grid, set the ShowValueListInFormulaWizard property to True.

    Also in the property grid, select the ValueList property and enter the following value:

    AUD,Australian Dollar;EUR,Euro;GBP,Pound Sterling;JPY,Japanese Yen;USD,US Dollar

    Optionally, you can then press the edit button (...) to show the Value List Editor.

    Press OK to close the Value List Editor.

    At run-time, the value list will be displayed in the Excel Formula Wizard:

  8. Click OK to save your changes in the Import Editor.

  9. Click OK in the Imported Assemblies window to save your changes and return to Visual Studio.

The completed project

If you inspect the add-in project in Solution Explorer, you will see that two new files have been added. In the folder "NetWrap/Imported files" are MyLib.import.xml and MyLib_Wrappers.cpp.

MyLib.import.xml contains instructions for importing the .NET assembly. When it is built, the XLL+ reflection tool, XNREFLECT.EXE, is run, which generates the C++ code for the XLL add-in functions, and write it to MyLib_Wrappers.cpp.

  1. Build the project. If you are working with a 64-bit version of Excel, then be sure to select the 64-bit platform x64 before you build.

    You will observe a new step in the build process, when MyLib_Wrappers.cpp is generated.

  2. Inspect MyLib_Wrappers.cpp. Each of the functions is simply a wrapper for a .NET method, and contains code to validate inputs, translate them to CLR data forms, invoke the .NET method and finally convert the result to Excel data form. If any method throws an exception, it will be caught and reported back to Excel.

  3. Use F5 to run and debug the add-in. Place break-points in the C# code, and you will see that the debugger seamlessly steps between the C++ and C# modules.

See Importing .NET assemblies in the User Guide for more details.

See Also

Importing a .NET Assembly using attributes | Samples and Walkthroughs


Importing a .NET Assembly using attributes

This walkthrough demonstrates how to import a .NET assembly, and automatically generate Excel add-in functions for its methods and properties, by adding XLL export attributes to the .NET code.

You can find a copy of all the code used in this walkthrough in the Walkthroughs/NetWrapAttr folder in your XLL+ installation, along with a demonstration spreadsheet, NetWrapAttr.xls.

Please note that this walkthrough is not available under XLL+ for Visual Studio .NET. XLL+ interacts with .NET using C++/CLI, which is only available under Visual Studio 2005 and above.

Run-time requirements

Please note that if you are using Visual Studio 2005, you must have Service Pack 1 installed in order to build a valid XLL.

If the add-in fails to load into Excel at run-time, please see the technical note .NET requirements.

In order to build MyLib.dll, you need the C# project system to be installed on your computer.

Creating the add-in project

  1. From the File menu, select New and then Project to open the New Project dialog.

  2. Select the XLL+ 7 Excel Add-in project template from the list of Visual C++ Projects, and enter NetWrapAttr in the Name box. Under Location, enter an appropriate directory in which to create the project.

  3. Put a tick next to "Create directory for solution", and click OK.

  4. In the "Application Settings" page of the XLL+ AppWizard, put a tick against Common Language Runtime Support (/clr).

  5. Click Finish to create the new add-in project.

For more information about creating projects, see Creating an add-in project in the XLL+ User Guide.

Creating the imported .NET assembly

Now create a new C# project and add it to the solution.

  1. In the Visual Studio Solution Explorer window, right-click the solution node and select Add/New Project....

  2. Select the Visual C# project type in the tree on the left-hand side, and select Class Library in the list on the right.

  3. Enter MyLib for the project Name, and accept the default Location. Press OK.

  4. Open the project properties of MyLib, and, in the Build page, towards the bottom of the page, put a tick against XML documentation file.

  5. Open Class1.cs and replace all the code with the code below.

CopyC#
using System;
using System.ComponentModel;

namespace MyLib
{
    /// <summary>
    /// Contains static calls to test parameter &amp; return types
    /// </summary>
    public static class TestClass
    {
        /// <summary>
        /// returns the concatenation of the arguments.
        /// </summary>
        /// <param name="a">is a string</param>
        /// <param name="b">is a number</param>
        /// <param name="c">is an integer</param>
        /// <param name="d">is a boolean</param>
        /// <returns></returns>
        public static string T1(string a, double b, int c, bool d)
        {
            return String.Format("a={0};b={1};c={2};d={3}",
                a, b, c, d);
        }
        /// <summary>
        /// returns an array of strings which are concatenations
        /// of the arguments.
        /// </summary>
        /// <param name="a">is a vector of strings</param>
        /// <param name="b">is a vector of numbers. It must be the same length as a.</param>
        /// <param name="c">is a vector of integers. It must be the same length as a.</param>
        /// <param name="d">is a vector of booleans. It must be the same length as a.</param>
        public static string[] T2(string[] a, double[] b, int[] c, bool[] d)
        {
            if (a.Length != b.Length)
                throw new ArgumentException(String.Format("Expected {0} items for b", a.Length));
            if (a.Length != c.Length)
                throw new ArgumentException(String.Format("Expected {0} items for c", a.Length));
            if (a.Length != d.Length)
                throw new ArgumentException(String.Format("Expected {0} items for d", a.Length));
            string[] res = new string[a.Length];
            for (int i = 0; i < res.Length; i++)
                res[i] = T1(a[i], b[i], c[i], d[i]);
            return res;
        }
        /// <summary>
        /// is a test function which adds two integers.
        /// </summary>
        /// <param name="a">is the first integer.</param>
        /// <param name="b">is the second integer.</param>
        /// <returns></returns>
        public static int T3(int a, int b)
        {
            return a + b;
        }

        /// <summary>
        /// This function will not be exported, because it is not marked
        /// with a XllFunction attribute.
        /// </summary>
        /// <param name="a">is an argument</param>
        /// <param name="b">is an argument</param>
        /// <returns>the sum of the inputs</returns>
        public static int DontExportMe(int a, int b)
        {
            return a + b;
        }

        /// <summary>
        /// Returns the type of an argument of unknown type
        /// </summary>
        /// <param name="arg">A value of any type</param>
        /// <returns>The value and type of the input</returns>
        public static string VarTypeScalar(object arg)
        {
            return String.Format("{0} ({1})", arg, arg == null ? "none" : arg.GetType().Name);
        }

        /// <summary>
        /// Returns the types of a vector of values of unknown type
        /// </summary>
        /// <param name="arg">is a vector of values of unknown type</param>
        /// <returns>a vector containing the values and types of the inputs</returns>
        public static string[] VarTypeVector(object[] arg)
        {
            string[] res = new string[arg.Length];
            for (int i = 0; i < arg.Length; i++)
                res[i] = VarTypeScalar(arg[i]);
            return res;
        }

        /// <summary>
        /// Returns the types of a matrix of values of unknown type
        /// </summary>
        /// <param name="arg">is a matrix of values of unknown type</param>
        /// <returns>a matrix containing the values and types of the inputs</returns>
        public static string[,] VarTypeMatrix(object[,] arg)
        {
            string[,] res = new string[arg.GetLength(0), arg.GetLength(1)];
            for (int i = 0; i < arg.GetLength(0); i++)
                for (int j = 0; j < arg.GetLength(1); j++)
                    res[i, j] = VarTypeScalar(arg[i, j]);
            return res;
        }

        /// <summary>
        /// Returns a result of variable type
        /// </summary>
        /// <param name="type">indicates the type of value to return</param>
        /// <returns>a value of variable type</returns>
        public static object VarRet(int type)
        {
            switch (type)
            {
                case 0: return "A string";
                case 1: return true;
                case 2: return (double)123.456;
            }
            throw new ArgumentException("type must be 0, 1 or 2", "type");
        }

        /// <summary>
        /// A public enumeration
        /// </summary>
        public enum Periods
        {
            Monthly = 12,
            Quarterly = 4,
            SemiAnnual = 2,
            Annual = 1
        }
        /// <summary>
        /// Calculates the discount factor for a given period and interest rate
        /// </summary>
        /// <param name="rate">is the interest rate</param>
        /// <param name="period">is a time period</param>
        /// <returns></returns>
        public static double DiscountFactor(double rate, Periods period)
        {
            return Math.Exp((-1.0 / ((double)(int)period)) * rate);
        }
    }
}

Adding attributes to the exported functions

To add attributes to the .NET assembly, follow these steps:

  1. Select the MyLib project in the Solution Explorer, and add a reference to the XLL+ runtime library.

    Right-click MyLib and click on "Add Reference...". Select the "Browse" page and navigate to the bin sub-directory of your XLL+ installation folder, typically [Program Files]\Planatech\XllPlus\7.0\VS8.0\bin. Select Psl.XL7.XnReflect.Runtime.dll and press OK.

  2. In Class1.cs, add the following line to the list of using statements:

    CopyC#
    using System;
using System.ComponentModel;
using XllPlus;

  3. Add a XllClassExport attribute to the class:

    CopyC#
    [XllClassExport(Category=XlCategory.UserDefined, Prefix="Test.")]
public class TestClass
{
    ...

    This attribute will control the category and prefix of all exported methods of the class. Unless otherwise specified, exported functions will be named Test.Function (where Function represents the method name) and will appear in the "User Defined" category in the Excel Formula Wizard.

  4. Add an XllFunction attribute to the method TestClass.T1:

    CopyC#
    [XllFunction]
public static string T1(string a, double b, int c, bool d)
{
    return String.Format("a={0};b={1};c={2};d={3}",
        a, b, c, d);
}

    This attribute will cause the function to be exported, as an Excel add-in function named Test.T1.

  5. Add an XllFunction attribute, with parameters, to the method TestClass.T2:

    CopyC#
    [XllFunction("TestArrays", Prefix="")]
public static string[] T2(string[] a, double[] b,
    int[] c, bool[] d)
{
    ...
}

    This attribute will cause the function to be exported as an Excel add-in function named TestArrays, with no prefix.

  6. Add an XllFunction attribute to the method TestClass.T3:

    CopyC#
    [XllFunction]
public static int T3(int a, int b)
{
    return a + b;
}

    This attribute will cause the function to be exported as an Excel add-in function named TestClass.T3.

  7. Add XllArgument attributes to the arguments of TestClass.T3:

    CopyC#
    [XllFunction]
public static int T3(
    [XllArgument("First", Flags=XlArgumentFlags.Optional, DefaultValue="100")]
    int a,
    [XllArgument("Second", Flags=XlArgumentFlags.Optional, DefaultValue="-99")]
    int b)
{
    return a + b;
}

    These attributes will change the names of the arguments a and b to First and Second respectively. They also provide default values for each argument which will be used if the argument is omitted.

  8. Note that no attribute is specified for the method TestClass.DontExportMe. Consequently, the function is not exported to Excel.

  9. Add XllFunction attributes to the methods TestClass.VarTypeScalar, TestClass.VarTypeVector and TestClass.VarTypeMatrix:

    CopyC#
    [XllFunction]
public static string VarTypeScalar(object arg)
{
    return String.Format("{0} ({1})", arg, arg == null ? "none" : arg.GetType().Name);
}

[XllFunction]
public static string[] VarTypeVector(object[] arg)
{
    ...
}

[XllFunction]
public static string[,] VarTypeMatrix(object[,] arg)
{
    ...
}

    The attribute will cause each of these methods to be exported to Excel. The arguments of each method are object types, and these are treated specially by the code importer; they can contain one or more values of any Excel value type: string, number, boolean or empty. Each cell value will be converted to a value of the appropriate type (System.String, System.Double, System.Boolean or null) before the .NET method is invoked.

  10. Add an XllFunction attribute to the method TestClass.VarRet:

    CopyC#
    [XllFunction]
public static object VarRet(int type)
{
    ...
}

    This attribute will cause the function to be exported as an Excel add-in function named TestClass.VarRet.

  11. Add an XllArgument attribute to the type argument of TestClass.VarRet:

    CopyC#
    [XllFunction]
public static object VarRet(
    [XllArgument(Flags=XlArgumentFlags.ShowValueListInFormulaWizard, ValueList="0,String;1,Boolean;2,Number")]
    int type)
{
    ...
}

    This attribute will add a value list for the argument. The value list will appear in a drop-down list when the function appears in the Excel Formula Wizard:

  12. Add an XllFunction attribute to the method TestClass.DiscountFactor:

    CopyC#
    [XllFunction]
public static double DiscountFactor(double rate, Periods period)
{
    return Math.Exp((-1.0 / ((double)(int)period)) * rate);
}

    This attribute will cause the function to be exported as an Excel add-in function named TestClass.DiscountFactor.

  13. Add an XllArgument attribute to the period argument of TestClass.DiscountFactor:

    CopyC#
    [XllFunction]
public static double DiscountFactor(double rate,
    [XllArgument(Flags = XlArgumentFlags.ShowValueListInFormulaWizard)] Periods period)
{
    return Math.Exp((-1.0 / ((double)(int)period)) * rate);
}

    This attribute will add a value list for the argument. The value list will appear in a drop-down list when the function appears in the Excel Formula Wizard. Because Periods is an Enum type, there is no need to specify the value list: it is generated automatically by the assembly importer.

Add a reference to the assembly

Before we can import the .NET assembly into the XLL+ project, we must create a reference to it.

  1. In Solution Explorer, find the node for the project NetWrapAttr and right-click it. Select Properties.

  2. In the Project Properties window, select the node "Common Properties/References", and click the "Add New Reference..." button.

  3. You may have to wait a long time for the "Add Reference" window to appear.

  4. In the "Add Reference" window, select the tab "Projects", select "MyLib" in the list, and press OK.

  5. In the Project Properties window, click OK to save your changes.

  6. You should now build the solution (Shift+Ctrl+B), and make sure that both projects built successfully. Make sure that the build is set to either "Win32" or "x64"; avoid "Mixed Platforms". Also, if necessary, use the Build/Configuration Manager... command to open the solution configuration window, and ensure that both projects have a tick in the "Build" column.

Importing the assembly

In these steps you will set up a link between the two projects. Once it is done, the build process will include an extra step, which inspects the .NET assembly and generates wrapper add-in functions for all the exported methods and properties. Whenever the .NET assembly is changed, this code will be regenerated during the next build.

  1. Open the main source file of the add-in project, NetWrapAttr.cpp.

  2. Activate the XLL Add-ins tool window (View/Other Windows/XLL Add-ins).

  3. Click on Import Assemblies... in the Tools menu.

  4. In the list of assemblies, put a check against MyLib.

  5. Click OK to save your changes and return to Visual Studio.

The completed project

If you inspect the add-in project in Solution Explorer, you will see that two new files have been added. In the folder "NetWrap/Imported files" are MyLib.import.xml and MyLib_Wrappers.cpp.

MyLib.import.xml contains instructions for importing the .NET assembly. When it is built, the XLL+ reflection tool, XNREFLECT.EXE, is run, which generates the C++ code for the XLL add-in functions, and write it to MyLib_Wrappers.cpp.

  1. Build the project. If you are working with a 64-bit version of Excel, then be sure to select the 64-bit platform x64 before you build.

    You will observe a new step in the build process, when MyLib_Wrappers.cpp is generated.

  2. Inspect MyLib_Wrappers.cpp. Each of the functions is simply a wrapper for a .NET method, and contains code to validate inputs, translate them to CLR data forms, invoke the .NET method and finally convert the result to Excel data form. If any method throws an exception, it will be caught and reported back to Excel.

  3. Use F5 to run and debug the add-in. Place break-points in the C# code, and you will see that the debugger seamlessly steps between the C++ and C# modules.

See Importing .NET assemblies in the User Guide for more details.

See Also

Importing a .NET Assembly | Samples and Walkthroughs


List of Examples

Listed below are all the C++ code sample fragments contained in XLL+ help. They each contain source code that can be pasted straight into an addin-in's source files.

You can also find many complete sample projects in the XllPlus/Samples sub-directory. Most of these are listed here.

CXllApp::GetNextFnAssoc() Example
CXllApp::GetNextFnAssoc, CXllApp::GetFnCount, CXllApp::GetStartFnPosition
CXllApp::PrefixFunctions() Example
CXllApp::PrefixFunctions
CXllApp::SplitSheetName() Example
CXllApp::SplitSheetName
CXlOper::AllocArray() Example
CXlOper::AllocArray, CXlOper::Format, CXlOper::Cell
CXlOper::Cell() Example
CXlOper::Cell, CXlOper::IsArray
CXlOper::Coerce() Example
CXlOper::Coerce, CXlOper::MakeRef
CXlOper::Excel() Example
CXlOper::Excel
CXlOper::FromNumericVector2() Example
CXlOper::FromNumericVector2
CXlOper::FromVector2() Example
CXlOper::FromVector2
CXlOper::GetCaller() Example
CXlOper::GetCaller, CXlOper::IsRef, CXlOper::GetRefItem, CXlOper::AllocArray, CXlRef, CXlRef::Height, CXlRef::Width, CXlOper::Cell
CXlOper::GetCallerDims() Example
CXllApp::GetCallerDims, CXlOper::AllocArray, CXlOper::Cell
CXlOper::GetCount2() Example
CXlOper::GetCount2
CXlOper::GetDims() Example
CXlOper::GetDims, CXlOper::Format
CXlOper::GetHeight() Example
CXlOper::GetHeight, CXlOper::FromInt
CXlOper::GetWidth() Example
CXlOper::GetWidth, CXlOper::FromInt
CXlOper::IsArray() Example
CXlOper::IsArray
CXlOper::IsBool() Example
CXlOper::IsBool
CXlOper::IsDouble() Example
CXlOper::IsDouble
CXlOper::IsEmpty() Example
CXlOper::IsEmpty
CXlOper::IsError() Example
CXlOper::IsError
CXlOper::IsMissing() Example
CXlOper::IsMissing
CXlOper::IsPresent() Example
CXlOper::IsPresent
CXlOper::IsString() Example
CXlOper::IsString
CXlOper::operator [] Example
CXlOper::operator [], CXlOper::GetCount, CXlOper::IsVector
CXlOper::operator BOOL() Example
CXlOper::operator BOOL
CXlOper::operator CString() Example
CXlOper::operator CString
CXlOper::operator double() Example
CXlOper::operator double
CXlOper::SetLongFormula() Example
CXlOper::SetLongFormula
CXlOper::SetLongFormulaIntl() Example
CXlOper::SetLongFormulaIntl
CXlOper::ToBool() Example
CXlOper::ToBool
CXlOper::ToDouble() Example
CXlOper::ToDouble
CXlOper::ToDoubleArray() Examples
CXlOper::ToDoubleArray, CXlOper::IsArray
CXlOper::ToString() Example
CXlOper::ToString
CXlOper::VectorCell() Example
CXlOper::VectorCell, CXlOper::IsVector, CXlOper::GetVectorCount
CXlRef Example
CXlRef
matrix<T>::add_row() Example
matrix<T>::add_row
mtx_ptrs<T> Example
mtx_ptrs<T>, mtx_ptrs<T>::size, mtx_ptrs<T>::operator [] const
MyAddress Example
CXlOper::IsRef, CXlOper::GetSheetName, CXlOper::GetRefCount, CXlOper::GetRefItem, CXlRef::ToString
MyCorrel Example
CXlOper::Ret
MyDaysInFeb Example
CXlOper::IsMissing, CXlOper::IsDouble, CXlOper::operator =
MyDaysInMonth Example
CXlOper::FromDoubleArray
MyMonthsInYear Example
CXlOper::AllocArray, CXlOper::Cell
MySort Example
CXlOper::operator =
MySqrt Example
CXlOper::Ret
MySquare Example
::IMPLEMENT_XLLFN4
MySum Example
CXlOper::GetDims, CXlOper::Cell, CXlOper::IsDouble, CXlOper::ToDouble
MyUpper Example
CXlOper::CXlOper

See Also

Samples and walkthroughs


CXllApp::GetNextFnAssoc() Example

This example returns an array containing a row of data about each function in the add-in library.

CopyC++
//{{XLP_SRC(GetFunctionList)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region GetFunctionList support code
IMPLEMENT_XLLFN4(GetFunctionList, GetFunctionList_4, GetFunctionList_12, "R!",
    "U!", L"GetFunctionList", 0, L"", 0, L"Demo functions", 0, L"Returns a lis"
    L"t of all the functions contained in this add-in", 0, L"", 0, 0, L"{GetFu"
    L"nctionList,,,Returns a list of all the functions contained in this add-i"
    L"n,Demo functions,1,136,U,{},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* GetFunctionList_Impl(CXlOper&);
extern "C" __declspec(dllexport)
LPXLOPER12 GetFunctionList_12()
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(GetFunctionList_Impl(xloResult));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 GetFunctionList_4()
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(GetFunctionList_Impl(xloResult));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* GetFunctionList_Impl(CXlOper& xloResult)
{
    // End of generated code
//}}XLP_SRC

    // Get an in-scope pointer to the application object
    XLL_FIX_STATE;
    CXllApp* papp = XllGetApp();

    // Create the result buffer
    xloResult.AllocArray(papp->GetFnCount(), 7);

    // Iterate through each function
    // Write its properties into a row of the output array
    CXllApp::POSITION pos;
    CString sKey;
    CXllFn* pfn;
    USHORT usRow;
    for ( usRow = 0, pos = papp->GetStartFnPosition(); pos; usRow++)
    {
        papp->GetNextFnAssoc(pos, sKey, pfn);
        xloResult.Cell(usRow, 0) = pfn->m_stName;
        xloResult.Cell(usRow, 1) = pfn->m_stArgNames4;
        xloResult.Cell(usRow, 2) = pfn->m_stCategory4;
        xloResult.Cell(usRow, 3) = pfn->m_stHelpText4;
        xloResult.Cell(usRow, 4) = (double)pfn->m_usType;
        xloResult.Cell(usRow, 5) = pfn->m_stEntryPoint4;
        xloResult.Cell(usRow, 6) = pfn->m_stArgTemplate4;
    }

    // Return the array
    return xloResult.Ret();
}

Uses

CXllApp::GetNextFnAssoc | CXllApp::GetFnCount | CXllApp::GetStartFnPosition


CXllApp::PrefixFunctions() Example

This example causes each function in the XLL to be exported with John Smith's initials as a prefix. Thus his function "Delta" will now be available in Excel as "JSDelta".

Note that only the only change to the boilerplate version of this function (generated by the AppWizard) was the addition of the PrefixFunctions() method.

CopyC++
BOOL CTest1App::InitInstance()
{
    // Call the base class
    if ( !CXllApp::InitInstance() )
        return FALSE;

    // Set the name of the library to the default value
    m_stName = m_pszDefName;

    // Add the statically defined function specifications
    AddStaticFns();

    // Prefix each function with "JS"
    PrefixFunctions("JS");

    return TRUE;
}

Uses

CXllApp::PrefixFunctions


CXllApp::SplitSheetName() Example

This example returns an array containing two cells: the book name and the sheet name contained in the argument FullName.

CopyC++
// Function:    SheetTest
// Purpose:     Split a full sheet name into book and sheet name parts

//{{XLP_SRC(SheetTest)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region SheetTest support code
IMPLEMENT_XLLFN4(SheetTest, SheetTest_4, SheetTest_12, "RC", "UC%", L"SheetTes"
    L"t", 0, L"FullName", 0, L"14", 0, L"Split a full sheet name into book and"
    L" sheet name parts", 0, L"No description provided\0", 0, 0, L"{SheetTest,"
    L",,Split a full sheet name into book and sheet name parts,14,1,132,U,{{0,"
    L"{FullName,String,0,,No description provided,,,,}}},{},3,,0,0,,,,0,0}", 1,
    0, 0)
CXlOper* SheetTest_Impl(CXlOper&, const CXlStringArg&);
extern "C" __declspec(dllexport)
LPXLOPER12 SheetTest_12(const XCHAR* FullName)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    CXlStringArg FullName__port(FullName);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(SheetTest_Impl(xloResult, FullName__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 SheetTest_4(const char* FullName)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    CXlStringArg FullName__port(FullName);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(SheetTest_Impl(xloResult, FullName__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* SheetTest_Impl(CXlOper& xloResult, const CXlStringArg& FullName)
{
    // End of generated code
//}}XLP_SRC

    CString bookName, sheetName;
    CXllApp::SplitSheetName(FullName, bookName, sheetName);

    xloResult.AllocArray(1, 2);
    xloResult.Cell(0, 0) = bookName;
    xloResult.Cell(0, 1) = sheetName;
    return xloResult.Ret();
}

Uses

CXllApp::SplitSheetName


CXlOper::AllocArray() Example

CopyC++
//{{XLP_SRC(AllocArrayEx)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region AllocArrayEx support code
IMPLEMENT_XLLFN4(AllocArrayEx, AllocArrayEx_4, AllocArrayEx_12, "R", "U", L"Al"
    L"locArrayEx", 0, L"", 0, L"Demo functions", 0, L"Returns a mixed array of"
    L" data", 0, L"", 0, 0, L"{AllocArrayEx,,,Returns a mixed array of data,De"
    L"mo functions,1,128,U,{},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* AllocArrayEx_Impl(CXlOper&);
extern "C" __declspec(dllexport)
LPXLOPER12 AllocArrayEx_12()
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(AllocArrayEx_Impl(xloResult));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 AllocArrayEx_4()
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(AllocArrayEx_Impl(xloResult));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* AllocArrayEx_Impl(CXlOper& xloResult)
{
    // End of generated code
//}}XLP_SRC

    // Allocate an array of empty cells
    USHORT cRows = 3, cCols = 2;
    xloResult.AllocArray(cRows, cCols);

    // Set each cell
    for (USHORT i = 0; i < cRows; i++) {
        // Put a number in the first cell
        xloResult.Cell(i, 0) = (double)i;
        // Put a string in the second cell
        CString strFormat;
        strFormat.Format("String %d", i);
        xloResult.Cell(i, 1) = strFormat;
    }

    // Return the array to Excel
    return xloResult.Ret();
}

Uses

CXlOper::AllocArray | CXlOper::Format | CXlOper::Cell


CXlOper::Cell() Example

CopyC++
//{{XLP_SRC(OperCellExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperCellExample support code
IMPLEMENT_XLLFN4(OperCellExample, OperCellExample_4, OperCellExample_12, "RPHH",
    "UQHH", L"OperCellExample", 0, L"Arg1,Row,Column", 0, L"Example", 0, L"Dem"
    L"onstrates COper::Cell", 0, L"Argument 1\0Row of cell to extract\0Column "
    L"of cell to extract\0", 0, 0, L"{OperCellExample,,,Demonstrates COper::Ce"
    L"ll,Example,1,128,U,{{0,{Arg1,Value,0,,Argument 1,,,,}},{0,{Row,Unsigned "
    L"Short Int,0,,Row of cell to extract,,,,}},{0,{Column,Unsigned Short Int,"
    L"0,,Column of cell to extract,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperCellExample_Impl(CXlOper&, const CXlOper*, unsigned short int,
    unsigned short int);
extern "C" __declspec(dllexport)
LPXLOPER12 OperCellExample_12(LPXLOPER12 Arg1, unsigned short int Row, unsigned
    short int Column)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperCellExample_Impl(xloResult, &Arg1__port, Row,
            Column));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperCellExample_4(LPXLOPER4 Arg1, unsigned short int Row, unsigned
    short int Column)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperCellExample_Impl(xloResult, &Arg1__port, Row,
            Column));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperCellExample_Impl(CXlOper& xloResult, const CXlOper* Arg1, unsigned
    short int Row, unsigned short int Column)
{
    // End of generated code
//}}XLP_SRC

    BOOL bOk = TRUE;

    // Check that we are inspecting an array
    bOk = Arg1->IsArray();

    // Check that the zero-based row and column
    // indices are in range
    bOk = bOk && (Row >= 0) && (Column >= 0);
    bOk = bOk && (Row < Arg1->GetHeight())
              && (Column < Arg1->GetWidth());

    // Extract the one interesting cell
    if ( bOk )
        xloResult = Arg1->Cell(Row, Column);
    else
        xloResult = xlerrNA;

    return xloResult.Ret();
}

Uses

CXlOper::Cell | CXlOper::IsArray


CXlOper::Coerce() Example

CopyC++
// Function:    CoerceEx
// Purpose:     Uses CXlOper::Coerce to return the contents of a cell

//{{XLP_SRC(CoerceEx)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region CoerceEx support code
IMPLEMENT_XLLFN4(CoerceEx, CoerceEx_4, CoerceEx_12, "RCA", "UC%A", L"CoerceEx",
    0, L"Address,A1", 0, L"Example", 0, L"Uses CXlOper::Coerce to return the c"
    L"ontents of an address", 0, L"Address of a cell\0TRUE if address is in A1"
    L" format, FALSE if it is in R1C1 format\0", 0, 0, L"{CoerceEx,,,Uses CXlO"
    L"per::Coerce to return the contents of an address,Example,1,128,U,{{0,{Ad"
    L"dress,String,0,,Address of a cell,,,,}},{0,{A1,Boolean,0,,\"TRUE if addr"
    L"ess is in A1 format, FALSE if it is in R1C1 format\",,,,}}},{},3,,0,0,,,"
    L",0,0}", 1, 0, 0)
CXlOper* CoerceEx_Impl(CXlOper&, const CXlStringArg&, BOOL);
extern "C" __declspec(dllexport)
LPXLOPER12 CoerceEx_12(const XCHAR* Address, BOOL A1)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    CXlStringArg Address__port(Address);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(CoerceEx_Impl(xloResult, Address__port, A1));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 CoerceEx_4(const char* Address, BOOL A1)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    CXlStringArg Address__port(Address);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(CoerceEx_Impl(xloResult, Address__port, A1));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* CoerceEx_Impl(CXlOper& xloResult, const CXlStringArg& Address, BOOL A1)
{
    // End of generated code
//}}XLP_SRC

    // Attempt to convert the address to a reference
    CXlOper xloRef;
    if (!xloRef.MakeRef(Address, A1))
        return CXlOper::RetError(xlerrValue);

    // Coerce the reference to a value
    xloResult.Coerce(xloRef);

    return xloResult.Ret();
}

Uses

CXlOper::Coerce | CXlOper::MakeRef


CXlOper::Excel() Example

This example demonstrates a call to the Excel SDK. It uses the xlfDate function to calculate a date in Excel format from a year, month and day.

CopyC++
//{{XLP_SRC(GetDate)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region GetDate support code
IMPLEMENT_XLLFN4(GetDate, GetDate_4, GetDate_12, "R", "U", L"GetDate", 0, L"",
    0, L"Demo functions", 0, L"Returns a date calculated by a call-back to Exc"
    L"el", 0, L"", 0, 0, L"{GetDate,,,Returns a date calculated by a call-back"
    L" to Excel,Demo functions,1,128,U,{},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* GetDate_Impl(CXlOper&);
extern "C" __declspec(dllexport)
LPXLOPER12 GetDate_12()
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(GetDate_Impl(xloResult));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 GetDate_4()
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(GetDate_Impl(xloResult));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* GetDate_Impl(CXlOper& xloResult)
{
    // End of generated code
//}}XLP_SRC

    static int xlfDate = 65;

    CXlOper xloYear(97.0), xloMonth(12.0), xloDay(31.0);
    CXlOper xloDate;

    if (!xloDate.Excel(xlfDate, 3, &xloYear, &xloMonth, &xloDay))
        xloResult = xloDate;
    else
        xloResult = xlerrNA;
    return xloResult.Ret();
}

Uses

CXlOper::Excel


CXlOper::FromNumericVector2() Example

CopyC++
// Function:    IntArray
// Purpose:     Returns an integer array

//{{XLP_SRC(IntArray)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region IntArray support code
IMPLEMENT_XLLFN4(IntArray, IntArray_4, IntArray_12, "RH", "UH", L"IntArray", 0,
    L"Type", 0, L"14", 0, L"Returns an integer array", 0, L"Integer type: 0=sh"
    L"ort;1=USHORT;2=int;3=unsigned int;4=long;5=unsigned long\0", 0, 0, L"{In"
    L"tArray,,,Returns an integer array,14,1,132,U,{{0,{Type,Unsigned Short In"
    L"t,0,,Integer type: 0=short;1=USHORT;2=int;3=unsigned int;4=long;5=unsign"
    L"ed long,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* IntArray_Impl(CXlOper&, unsigned short int);
extern "C" __declspec(dllexport)
LPXLOPER12 IntArray_12(unsigned short int Type)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(IntArray_Impl(xloResult, Type));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 IntArray_4(unsigned short int Type)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(IntArray_Impl(xloResult, Type));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* IntArray_Impl(CXlOper& xloResult, unsigned short int Type)
{
    // End of generated code
//}}XLP_SRC

    switch (Type)
    {
    case 0:
        {
            std::vector<short> v;
            for (short i = -5; i < 5; i++)
                v.push_back(i);
            xloResult.FromNumericVector2(v);
        }
        break;
    case 1:
        {
            std::vector<USHORT> v;
            for (USHORT i = 0; i < 10; i++)
                v.push_back(i);
            xloResult.FromNumericVector2(v);
        }
        break;
    case 2:
        {
            std::vector<int> v;
            for (int i = -5; i < 5; i++)
                v.push_back(i);
            xloResult.FromNumericVector2(v);
        }
        break;
    case 3:
        {
            std::vector<unsigned int> v;
            for (unsigned int i = 0; i < 10; i++)
                v.push_back(i);
            xloResult.FromNumericVector2(v);
        }
        break;
    case 4:
        {
            std::vector<long> v;
            for (long i = -5; i < 5; i++)
                v.push_back(i);
            xloResult.FromNumericVector2(v);
        }
        break;
    case 5:
        {
            std::vector<unsigned long> v;
            for (unsigned long i = 0; i < 10; i++)
                v.push_back(i);
            xloResult.FromNumericVector2(v);
        }
        break;
    default:
        throw CXlErrorException(xlerrValue);
    }
    return xloResult.Ret();
}

Uses

CXlOper::FromNumericVector2


CXlOper::FromVector2() Example

CopyC++
#include <algorithm>

// Function:    XlOperFromVectorEx
// Purpose:     Returns a sorted vector

//{{XLP_SRC(XlOperFromVectorEx)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region XlOperFromVectorEx support code
IMPLEMENT_XLLFN4(XlOperFromVectorEx, XlOperFromVectorEx_4,
    XlOperFromVectorEx_12, "RP", "UQ", L"XlOperFromVectorEx", 0, L"Input", 0,
    L"Demo Functions", 0, L"Returns a sorted vector", 0, L"Vector of numbers\0",
    0, 0, L"{XlOperFromVectorEx,,,Returns a sorted vector,Demo Functions,1,128"
    L",U,{{0,{Input,Double,2097162,,Vector of numbers,,{{{0,},{,}}},,}}},{},3,"
    L",0,0,,,,0,0}", 1, 0, 0)
CXlOper* XlOperFromVectorEx_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 XlOperFromVectorEx_12(LPXLOPER12 Input)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Input__port(Input);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(XlOperFromVectorEx_Impl(xloResult, &Input__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 XlOperFromVectorEx_4(LPXLOPER4 Input)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Input__port(Input);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(XlOperFromVectorEx_Impl(xloResult, &Input__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* XlOperFromVectorEx_Impl(CXlOper& xloResult, const CXlOper* Input)
{
    // Input buffers
    std::vector<double> vecInput;
    // Validate and translate inputs
    XlReadVector(*Input, vecInput, L"Input", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK
        |XLA_BOUND_UBOUND_AUTO, 0, 0);
    // End of generated code
//}}XLP_SRC

    std::sort(vecInput.begin(), vecInput.end());
    xloResult.FromVector2(vecInput);
    return xloResult.Ret();
}

Uses

CXlOper::FromVector2


CXlOper::GetCaller() Example

The following example demonstrates GetCaller. It looks at the size of the range of cells that called the function, and fills them with evenly interpolated values between the start and end values supplied. If it was not called from a cell or cells, but from a command or an event handler, then it gracefully returns #NA.

CopyC++
// Function:    MyFillRange
// Returns:     LPXLOPER
// Description: Return a series interpolated between start and end values

//{{XLP_SRC(MyFillRange)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MyFillRange support code
IMPLEMENT_XLLFN4(MyFillRange, MyFillRange_4, MyFillRange_12, "RBB", "UBB",
    L"MyFillRange", 0, L"Start,End", 0, L"14", 0, L"Return a series interpolat"
    L"ed between start and end values", 0, L"Start value for series\0End value"
    L" for series\0", 0, 0, L"{MyFillRange,,,Return a series interpolated betw"
    L"een start and end values,14,1,128,U,{{0,{Start,Double,0,,Start value for"
    L" series,,,,}},{0,{End,Double,0,,End value for series,,,,}}},{},3,,0,0,,,"
    L",0,0}", 1, 0, 0)
CXlOper* MyFillRange_Impl(CXlOper&, double, double);
extern "C" __declspec(dllexport)
LPXLOPER12 MyFillRange_12(double Start, double End)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyFillRange_Impl(xloResult, Start, End));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 MyFillRange_4(double Start, double End)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyFillRange_Impl(xloResult, Start, End));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* MyFillRange_Impl(CXlOper& xloResult, double Start, double End)
{
    // End of generated code
//}}XLP_SRC

    CXlOper xloCaller;
    double dValue, dInc;
    int nCells;

    // Get caller. Fail if it is not a range of cells
    if ( ( xloCaller.GetCaller() != 0 ) || !xloCaller.IsRef() )
    {
        xloResult = xlerrNA;
        return xloResult.Ret();
    }

    // Get the first (and only) reference from
    // the caller CXlOper
    CXlRef xlrefCaller = xloCaller.GetRefItem(0);

    // Create the result array
    xloResult.AllocArray(xlrefCaller.Height(),
                         xlrefCaller.Width());

    // Fill it with evenly spaced values between
    // Start and End
    nCells = xlrefCaller.Height() * xlrefCaller.Width();
    dInc = (nCells > 1) ? ( (End - Start) / (nCells - 1) )
                        : 0.0;
    dValue = Start;
    for ( int i = 0; i < xlrefCaller.Height(); i++ )
    {
        for ( int j = 0; j < xlrefCaller.Width(); j++ )
        {
            xloResult.Cell(i, j) = dValue;
            dValue += dInc;
        }
    }

    // Return the array, which will be exactly the
    // right size and shape to fill the array formula
    // that called it
    return xloResult.Ret();
}

Uses

CXlOper::GetCaller | CXlOper::IsRef | CXlOper::GetRefItem | CXlOper::AllocArray | CXlRef | CXlRef::Height | CXlRef::Width | CXlOper::Cell


CXlOper::GetCallerDims() Example

The following example demonstrates GetCallerDims. It looks at the size of the range of cells that called the function, and fills them with evenly interpolated values between the start and end values supplied. If it was not called from a cell or cells, but from a command or an event handler, then it gracefully returns #NA.

CopyC++
// Function:    MyFillRange2
// Returns:     LPXLOPER
// Description: Return a series interpolated between start and end values

//{{XLP_SRC(MyFillRange2)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MyFillRange2 support code
IMPLEMENT_XLLFN4(MyFillRange2, MyFillRange2_4, MyFillRange2_12, "RBB", "UBB",
    L"MyFillRange2", 0, L"Start,End", 0, L"14", 0, L"Return a series interpola"
    L"ted between start and end values", 0, L"Start value for series\0End valu"
    L"e for series\0", 0, 0, L"{MyFillRange2,,,Return a series interpolated be"
    L"tween start and end values,14,1,128,U,{{0,{Start,Double,0,,Start value f"
    L"or series,,,,}},{0,{End,Double,0,,End value for series,,,,}}},{},3,,0,0,"
    L",,,0,0}", 1, 0, 0)
CXlOper* MyFillRange2_Impl(CXlOper&, double, double);
extern "C" __declspec(dllexport)
LPXLOPER12 MyFillRange2_12(double Start, double End)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyFillRange2_Impl(xloResult, Start, End));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 MyFillRange2_4(double Start, double End)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyFillRange2_Impl(xloResult, Start, End));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* MyFillRange2_Impl(CXlOper& xloResult, double Start, double End)
{
    // End of generated code
//}}XLP_SRC

    USHORT usRows, usCols;
    double dValue, dInc;
    int nCells;

    // Get dimensions of caller. Fail if it is not a range of cells
    if (!CXllApp::GetCallerDims(usRows, usCols))
        return CXlOper::RetError(xlerrNA);

    // Create the result array
    xloResult.AllocArray(usRows, usCols);

    // Fill it with evenly spaced values between
    // Start and End
    nCells = usRows * usCols;
    dInc = (nCells > 1) ? ( (End - Start) / (nCells - 1) )
                        : 0.0;
    dValue = Start;
    for ( int i = 0; i < usRows; i++ )
    {
        for ( int j = 0; j < usCols; j++ )
        {
            xloResult.Cell(i, j) = dValue;
            dValue += dInc;
        }
    }

    // Return the array, which will be exactly the
    // right size and shape to fill the array formula
    // that called it
    return xloResult.Ret();
}

Uses

CXllApp::GetCallerDims | CXlOper::AllocArray | CXlOper::Cell


CXlOper::GetCount2() Example

CopyC++
//{{XLP_SRC(OperGetCountExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperGetCountExample support code
IMPLEMENT_XLLFN4(OperGetCountExample, OperGetCountExample_4,
    OperGetCountExample_12, "RP", "UQ", L"OperGetCountExample", 0, L"Arg1", 0,
    L"Example", 0, L"Demonstrates COper::GetCount()", 0, L"Argument 1\0", 0, 0,
    L"{OperGetCountExample,,,Demonstrates COper::GetCount(),Example,1,128,U,{{"
    L"0,{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperGetCountExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperGetCountExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperGetCountExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperGetCountExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperGetCountExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperGetCountExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    // Note: there is no long integer type for an XLOPER,
    //       so we convert the count to a double.
    xloResult = (double)Arg1->GetCount2();
    return xloResult.Ret();
}

Uses

CXlOper::GetCount2


CXlOper::GetDims() Example

CopyC++
//{{XLP_SRC(OperGetDimsExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperGetDimsExample support code
IMPLEMENT_XLLFN4(OperGetDimsExample, OperGetDimsExample_4,
    OperGetDimsExample_12, "RP", "UQ", L"OperGetDimsExample", 0, L"Arg1", 0,
    L"Example", 0, L"Demonstrates COper::GetDims()", 0, L"Argument 1\0", 0, 0,
    L"{OperGetDimsExample,,,Demonstrates COper::GetDims(),Example,1,128,U,{{0,"
    L"{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperGetDimsExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperGetDimsExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperGetDimsExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperGetDimsExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperGetDimsExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperGetDimsExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    size_t nRows, nColumns;
    Arg1->GetDims(nRows, nColumns);
    xloResult.Format("%lu rows by %lu columns", nRows, nColumns);
    return xloResult.Ret();
}

Uses

CXlOper::GetDims | CXlOper::Format


CXlOper::GetHeight() Example

CopyC++
//{{XLP_SRC(OperGetHeightExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperGetHeightExample support code
IMPLEMENT_XLLFN4(OperGetHeightExample, OperGetHeightExample_4,
    OperGetHeightExample_12, "RP", "UQ", L"OperGetHeightExample", 0, L"Arg1", 0,
    L"Example", 0, L"Demonstrates COper::GetHeight()", 0, L"Argument 1\0", 0, 0,
    L"{OperGetHeightExample,,,Demonstrates COper::GetHeight(),Example,1,128,U,"
    L"{{0,{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperGetHeightExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperGetHeightExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperGetHeightExample_Impl(xloResult, &Arg1__port
            ));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperGetHeightExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperGetHeightExample_Impl(xloResult, &Arg1__port
            ));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperGetHeightExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    xloResult.FromInt(Arg1->GetHeight());
    return xloResult.Ret();
}

Uses

CXlOper::GetHeight | CXlOper::FromInt


CXlOper::GetWidth() Example

CopyC++
//{{XLP_SRC(OperGetWidthExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperGetWidthExample support code
IMPLEMENT_XLLFN4(OperGetWidthExample, OperGetWidthExample_4,
    OperGetWidthExample_12, "RP", "UQ", L"OperGetWidthExample", 0, L"Arg1", 0,
    L"Example", 0, L"Demonstrates COper::GetWidth()", 0, L"Argument 1\0", 0, 0,
    L"{OperGetWidthExample,,,Demonstrates COper::GetWidth(),Example,1,128,U,{{"
    L"0,{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperGetWidthExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperGetWidthExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperGetWidthExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperGetWidthExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperGetWidthExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperGetWidthExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    xloResult.FromInt(Arg1->GetWidth());
    return xloResult.Ret();
}

Uses

CXlOper::GetWidth | CXlOper::FromInt


CXlOper::IsArray() Example

CopyC++
//{{XLP_SRC(OperIsArrayExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperIsArrayExample support code
IMPLEMENT_XLLFN4(OperIsArrayExample, OperIsArrayExample_4,
    OperIsArrayExample_12, "RP", "UQ", L"OperIsArrayExample", 0, L"Arg1", 0,
    L"Example", 0, L"Demonstrates COper::IsArray()", 0, L"Argument 1\0", 0, 0,
    L"{OperIsArrayExample,,,Demonstrates COper::IsArray(),Example,1,128,U,{{0,"
    L"{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperIsArrayExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperIsArrayExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsArrayExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperIsArrayExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsArrayExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperIsArrayExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    xloResult = Arg1->IsArray();
    return xloResult.Ret();
}

Uses

CXlOper::IsArray


CXlOper::IsBool() Example

CopyC++
//{{XLP_SRC(OperIsBoolExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperIsBoolExample support code
IMPLEMENT_XLLFN4(OperIsBoolExample, OperIsBoolExample_4, OperIsBoolExample_12,
    "RP", "UQ", L"OperIsBoolExample", 0, L"Arg1", 0, L"Example", 0, L"Demonstr"
    L"ates COper::IsBool()", 0, L"Argument 1\0", 0, 0, L"{OperIsBoolExample,,,"
    L"Demonstrates COper::IsBool(),Example,1,128,U,{{0,{Arg1,Value,0,,Argument"
    L" 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperIsBoolExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperIsBoolExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsBoolExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperIsBoolExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsBoolExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperIsBoolExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    xloResult = Arg1->IsBool();
    return xloResult.Ret();
}

Uses

CXlOper::IsBool


CXlOper::IsDouble() Example

CopyC++
//{{XLP_SRC(OperIsDoubleExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperIsDoubleExample support code
IMPLEMENT_XLLFN4(OperIsDoubleExample, OperIsDoubleExample_4,
    OperIsDoubleExample_12, "RP", "UQ", L"OperIsDoubleExample", 0, L"Arg1", 0,
    L"Example", 0, L"Demonstrates COper::IsDouble()", 0, L"Argument 1\0", 0, 0,
    L"{OperIsDoubleExample,,,Demonstrates COper::IsDouble(),Example,1,128,U,{{"
    L"0,{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperIsDoubleExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperIsDoubleExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsDoubleExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperIsDoubleExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsDoubleExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperIsDoubleExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    xloResult = Arg1->IsDouble();
    return xloResult.Ret();
}

Uses

CXlOper::IsDouble


CXlOper::IsEmpty() Example

CopyC++
//{{XLP_SRC(OperIsEmptyExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperIsEmptyExample support code
IMPLEMENT_XLLFN4(OperIsEmptyExample, OperIsEmptyExample_4,
    OperIsEmptyExample_12, "RP", "UQ", L"OperIsEmptyExample", 0, L"Arg1", 0,
    L"Example", 0, L"Demonstrates COper::IsEmpty()", 0, L"Argument 1\0", 0, 0,
    L"{OperIsEmptyExample,,,Demonstrates COper::IsEmpty(),Example,1,128,U,{{0,"
    L"{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperIsEmptyExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperIsEmptyExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsEmptyExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperIsEmptyExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsEmptyExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperIsEmptyExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    xloResult = Arg1->IsEmpty();
    return xloResult.Ret();
}

Uses

CXlOper::IsEmpty


CXlOper::IsError() Example

CopyC++
//{{XLP_SRC(OperIsErrorExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperIsErrorExample support code
IMPLEMENT_XLLFN4(OperIsErrorExample, OperIsErrorExample_4,
    OperIsErrorExample_12, "RP", "UQ", L"OperIsErrorExample", 0, L"Arg1", 0,
    L"Example", 0, L"Demonstrates COper::IsError()", 0, L"Argument 1\0", 0, 0,
    L"{OperIsErrorExample,,,Demonstrates COper::IsError(),Example,1,128,U,{{0,"
    L"{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperIsErrorExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperIsErrorExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsErrorExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperIsErrorExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsErrorExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperIsErrorExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    xloResult = Arg1->IsError();
    return xloResult.Ret();
}

Uses

CXlOper::IsError


CXlOper::IsMissing() Example

CopyC++
//{{XLP_SRC(OperIsMissingExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperIsMissingExample support code
IMPLEMENT_XLLFN4(OperIsMissingExample, OperIsMissingExample_4,
    OperIsMissingExample_12, "RP", "UQ", L"OperIsMissingExample", 0, L"Arg1", 0,
    L"Example", 0, L"Demonstrates COper::IsMissing()", 0, L"Argument 1\0", 0, 0,
    L"{OperIsMissingExample,,,Demonstrates COper::IsMissing(),Example,1,128,U,"
    L"{{0,{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperIsMissingExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperIsMissingExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsMissingExample_Impl(xloResult, &Arg1__port
            ));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperIsMissingExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsMissingExample_Impl(xloResult, &Arg1__port
            ));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperIsMissingExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    xloResult = Arg1->IsMissing();
    return xloResult.Ret();
}

Uses

CXlOper::IsMissing


CXlOper::IsPresent() Example

CopyC++
//{{XLP_SRC(OperIsPresentExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperIsPresentExample support code
IMPLEMENT_XLLFN4(OperIsPresentExample, OperIsPresentExample_4,
    OperIsPresentExample_12, "RP", "UQ", L"OperIsPresentExample", 0, L"Arg1", 0,
    L"Example", 0, L"Demonstrates COper::IsPresent()", 0, L"Argument 1\0", 0, 0,
    L"{OperIsPresentExample,,,Demonstrates COper::IsPresent(),Example,1,128,U,"
    L"{{0,{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperIsPresentExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperIsPresentExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsPresentExample_Impl(xloResult, &Arg1__port
            ));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperIsPresentExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsPresentExample_Impl(xloResult, &Arg1__port
            ));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperIsPresentExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    xloResult = Arg1->IsPresent();
    return xloResult.Ret();
}

Uses

CXlOper::IsPresent


CXlOper::IsString() Example

CopyC++
//{{XLP_SRC(OperIsStringExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperIsStringExample support code
IMPLEMENT_XLLFN4(OperIsStringExample, OperIsStringExample_4,
    OperIsStringExample_12, "RP", "UQ", L"OperIsStringExample", 0, L"Arg1", 0,
    L"Example", 0, L"Demonstrates COper::IsString()", 0, L"Argument 1\0", 0, 0,
    L"{OperIsStringExample,,,Demonstrates COper::IsString(),Example,1,128,U,{{"
    L"0,{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperIsStringExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperIsStringExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsStringExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperIsStringExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperIsStringExample_Impl(xloResult, &Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperIsStringExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    xloResult = Arg1->IsString();
    return xloResult.Ret();
}

Uses

CXlOper::IsString


CXlOper::operator [] Example

CopyC++
//{{XLP_SRC(OperBraceExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperBraceExample support code
IMPLEMENT_XLLFN4(OperBraceExample, OperBraceExample_4, OperBraceExample_12,
    "RPH", "UQH", L"OperBraceExample", 0, L"Vector,Index", 0, L"Example", 0,
    L"Demonstrates the use of COper::operator[ ]", 0, L"Vector argument\0Zero-"
    L"based index into vector\0", 0, 0, L"{OperBraceExample,,,Demonstrates the"
    L" use of COper::operator[ ],Example,1,128,U,{{0,{Vector,Value,0,,Vector a"
    L"rgument,,,,}},{0,{Index,Unsigned Short Int,0,,Zero-based index into vect"
    L"or,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperBraceExample_Impl(CXlOper&, const CXlOper*, unsigned short int);
extern "C" __declspec(dllexport)
LPXLOPER12 OperBraceExample_12(LPXLOPER12 Vector, unsigned short int Index)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Vector__port(Vector);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperBraceExample_Impl(xloResult, &Vector__port,
            Index));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperBraceExample_4(LPXLOPER4 Vector, unsigned short int Index)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Vector__port(Vector);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperBraceExample_Impl(xloResult, &Vector__port,
            Index));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperBraceExample_Impl(CXlOper& xloResult, const CXlOper* Vector,
    unsigned short int Index)
{
    // End of generated code
//}}XLP_SRC

    BOOL bOk = TRUE;

    // Check that Arg1 is a vector, since operator[ ]
    // demands that is a vector, and asserts if it is not.
    bOk = Vector->IsVector();
    // Check that Index is in range
    bOk = bOk && (Index >= 0);
    bOk = bOk && (Index < Vector->GetCount());

    // If all went well, extract the value.
    // Otherwise return an error.
    if ( bOk )
        xloResult = (*Vector)[Index];
    else
        xloResult = xlerrNA;
    return xloResult.Ret();
}

Uses

CXlOper::operator [] | CXlOper::GetCount | CXlOper::IsVector


CXlOper::operator BOOL() Example

CopyC++
//{{XLP_SRC(OperCastToBoolExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperCastToBoolExample support code
IMPLEMENT_XLLFN4(OperCastToBoolExample, OperCastToBoolExample_4,
    OperCastToBoolExample_12, "RP", "UQ", L"OperCastToBoolExample", 0, L"Arg1",
    0, L"Example", 0, L"Demonstrates casting a COper to a BOOL", 0, L"Argument"
    L" 1\0", 0, 0, L"{OperCastToBoolExample,,,Demonstrates casting a COper to "
    L"a BOOL,Example,1,128,U,{{0,{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,"
    L",0,0}", 1, 0, 0)
CXlOper* OperCastToBoolExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperCastToBoolExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperCastToBoolExample_Impl(xloResult, &Arg1__port
            ));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperCastToBoolExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperCastToBoolExample_Impl(xloResult, &Arg1__port
            ));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperCastToBoolExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    BOOL bOk = TRUE;
    COper& opArg1 = *(COper*)Arg1;

    // These two lines could have condensed to one:
    // xloResult = (BOOL)opArg1;
    BOOL b = opArg1;
    xloResult = b;

    return xloResult.Ret();
}

Uses

CXlOper::operator BOOL


CXlOper::operator CString() Example

CopyC++
//{{XLP_SRC(OperCastToStringExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperCastToStringExample support code
IMPLEMENT_XLLFN4(OperCastToStringExample, OperCastToStringExample,
    OperCastToStringExample_12, "RP", "UQ", L"OperCastToStringExample", 0,
    L"Arg1", 0, L"Example", 0, L"Demonstrates casting a COper to a CString", 0,
    L"Argument 1\0", 0, 0, L"{OperCastToStringExample,OperCastToStringExample,"
    L",Demonstrates casting a COper to a CString,Example,1,128,U,{{0,{Arg1,Val"
    L"ue,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperCastToStringExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperCastToStringExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperCastToStringExample_Impl(xloResult, &
            Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperCastToStringExample(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperCastToStringExample_Impl(xloResult, &
            Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperCastToStringExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    BOOL bOk = TRUE;

    // These two lines could have condensed to one:
    // xloResult = (CString)opArg1;
    CString s = *Arg1;
    xloResult = s;

    return xloResult.Ret();
}

Uses

CXlOper::operator CString


CXlOper::operator double() Example

CopyC++
//{{XLP_SRC(OperCastToDoubleExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperCastToDoubleExample support code
IMPLEMENT_XLLFN4(OperCastToDoubleExample, OperCastToDoubleExample_4,
    OperCastToDoubleExample_12, "RP", "UQ", L"OperCastToDoubleExample", 0,
    L"Arg1", 0, L"Example", 0, L"Demonstrates casting a COper to a double", 0,
    L"Argument 1\0", 0, 0, L"{OperCastToDoubleExample,,,Demonstrates casting a"
    L" COper to a double,Example,1,128,U,{{0,{Arg1,Value,0,,Argument 1,,,,}}},"
    L"{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperCastToDoubleExample_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperCastToDoubleExample_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperCastToDoubleExample_Impl(xloResult, &
            Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperCastToDoubleExample_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperCastToDoubleExample_Impl(xloResult, &
            Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperCastToDoubleExample_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    BOOL bOk = TRUE;

    // These two lines could have condensed to one:
    // xloResult = (double)opArg1;
    double d = *Arg1;
    xloResult = d;

    return xloResult.Ret();
}

Uses

CXlOper::operator double


CXlOper::SetLongFormula() Example

CopyC++
// Function:    SetLongFormula
// Purpose:     Paste a long formula to the current cell

//{{XLP_SRC(SetLongFormula)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region SetLongFormula support code
IMPLEMENT_XLLFN4(SetLongFormula, SetLongFormula_4, SetLongFormula_12, "A", "A",
    L"SetLongFormula", 0, L"", 0, L"14", 0, L"Paste a long formula to the curr"
    L"ent cell", 0, L"", 0, 0, L"{SetLongFormula,,,Paste a long formula to the"
    L" current cell,14,2,132,A,{},{},3,,0,0,,,,0,0}", 2, 0, 0)
BOOL SetLongFormula_Impl();
extern "C" __declspec(dllexport)
BOOL SetLongFormula_12()
{
    XLL_FIX_STATE;
    return SetLongFormula_Impl();
}
extern "C" __declspec(dllexport)
BOOL SetLongFormula_4()
{
    XLL_FIX_STATE;
    return SetLongFormula_Impl();
}

#pragma endregion

BOOL SetLongFormula_Impl()
{
    // End of generated code
//}}XLP_SRC

    // Build a long formula:
    // ="abcde..."&"abcde..."&...

    int nChars = 200;
    int nRepeats = 4;

    char achVal1[1024];
    int i;
    for (i = 0; i < nChars; i++)
        achVal1[i] = 'A' + (i % 26);
    achVal1[i] = 0;

    CString strVal2 = "";
    for (i = 0; i < nRepeats; i++)
        strVal2 += ((i > 0) ? "&" : "") + CString("\"") + achVal1 + "\"";

    CString strFormula = "=" + strVal2;

    // Report length of formula
    CString strMsg;
    strMsg.Format("Formula Length = %d", strFormula.GetLength());
    CXllApp::XlMessageBox(strMsg, XlMessageBoxTypeInformation);

    // Apply formula to active cell
    CXlOper xloActive;
    if (xloActive.GetActiveCell()
     && xloActive.SetLongFormula(strFormula))
    {
        return TRUE;
    }
    else
    {
        CXllApp::XlMessageBox("Failed to set long formula", XlMessageBoxTypeExclamation);
        return FALSE;
    }
}

Uses

CXlOper::SetLongFormula


CXlOper::SetLongFormulaIntl() Example

CopyC++
// Function:    SetLongFormulaIntl
// Purpose:     Paste a long formula to the current cell

//{{XLP_SRC(SetLongFormulaIntl)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region SetLongFormulaIntl support code
IMPLEMENT_XLLFN4(SetLongFormulaIntl, SetLongFormulaIntl_4,
    SetLongFormulaIntl_12, "A", "A", L"SetLongFormulaIntl", 0, L"", 0, L"14", 0,
    L"Paste a long formula to the current cell", 0, L"", 0, 0, L"{SetLongFormu"
    L"laIntl,,,Paste a long formula to the current cell,14,2,132,A,{},{},3,,0,"
    L"0,,,,0,0}", 2, 0, 0)
BOOL SetLongFormulaIntl_Impl();
extern "C" __declspec(dllexport)
BOOL SetLongFormulaIntl_12()
{
    XLL_FIX_STATE;
    return SetLongFormulaIntl_Impl();
}
extern "C" __declspec(dllexport)
BOOL SetLongFormulaIntl_4()
{
    XLL_FIX_STATE;
    return SetLongFormulaIntl_Impl();
}

#pragma endregion

BOOL SetLongFormulaIntl_Impl()
{
    // End of generated code
//}}XLP_SRC

    // Build a long formula:
    // =LEFT("abcde..."&"abcde..."&...,200)

    // Note that "LEFT" is in always in English, and that the
    // argument separator is always a comma (US English settings).

    int nChars = 200;
    int nRepeats = 4;

    char achVal1[1024];
    int i;
    for (i = 0; i < nChars; i++)
        achVal1[i] = 'A' + (i % 26);
    achVal1[i] = 0;
    CString strVal2 = "";
    for (i = 0; i < nRepeats; i++)
        strVal2 += ((i > 0) ? "&" : "") + CString("\"") + achVal1 + "\"";
    CString strFormula = "=LEFT(" + strVal2 + ", 200)";

    // Report formula length
    CString strMsg;
    strMsg.Format("Formula length = %d", strFormula.GetLength());
    CXllApp::XlMessageBox(strMsg, XlMessageBoxTypeInformation);

    CXlOper xloActive;
    if (xloActive.GetActiveCell()
     && xloActive.SetLongFormula(strFormula))
    {
        return TRUE;
    }
    else
    {
        CXllApp::XlMessageBox("Failed to set long formula", XlMessageBoxTypeExclamation);
        return FALSE;
    }
}

Uses

CXlOper::SetLongFormulaIntl


CXlOper::ToBool() Example

CopyC++
//{{XLP_SRC(OperToBoolExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperToBoolExample support code
IMPLEMENT_XLLFN4(OperToBoolExample, OperToBoolExample_4, OperToBoolExample_12,
    "RPA", "UQA", L"OperToBoolExample", 0, L"Arg1,Strict", 0, L"Example", 0,
    L"Demonstrates COper::ToBool()", 0, L"Argument 1\0If True, then do not att"
    L"empt to convert\0", 0, 0, L"{OperToBoolExample,,,Demonstrates COper::ToB"
    L"ool(),Example,1,128,U,{{0,{Arg1,Value,0,,Argument 1,,,,}},{0,{Strict,Boo"
    L"lean,0,,\"If True, then do not attempt to convert\",,,,}}},{},3,,0,0,,,,"
    L"0,0}", 1, 0, 0)
CXlOper* OperToBoolExample_Impl(CXlOper&, const CXlOper*, BOOL);
extern "C" __declspec(dllexport)
LPXLOPER12 OperToBoolExample_12(LPXLOPER12 Arg1, BOOL Strict)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperToBoolExample_Impl(xloResult, &Arg1__port,
            Strict));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperToBoolExample_4(LPXLOPER4 Arg1, BOOL Strict)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperToBoolExample_Impl(xloResult, &Arg1__port,
            Strict));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperToBoolExample_Impl(CXlOper& xloResult, const CXlOper* Arg1, BOOL
    Strict)
{
    // End of generated code
//}}XLP_SRC

    // Note that ToBool() will throw an Exception (interrupting execution)
    // if Strict is TRUE and Arg1 is not a boolean.

    // This will be caught by the wrapper function, and an error message
    // will be returned to Excel.

    xloResult = Arg1->ToBool(Strict ? true : false);
    return xloResult.Ret();
}

Uses

CXlOper::ToBool


CXlOper::ToDouble() Example

CopyC++
//{{XLP_SRC(OperToDoubleExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperToDoubleExample support code
IMPLEMENT_XLLFN4(OperToDoubleExample, OperToDoubleExample_4,
    OperToDoubleExample_12, "RPA", "UQA", L"OperToDoubleExample", 0, L"Arg1,St"
    L"rict", 0, L"Example", 0, L"Demonstrates COper::ToDouble()", 0, L"Argumen"
    L"t 1\0If True, then do not attempt to convert\0", 0, 0, L"{OperToDoubleEx"
    L"ample,,,Demonstrates COper::ToDouble(),Example,1,128,U,{{0,{Arg1,Value,0"
    L",,Argument 1,,,,}},{0,{Strict,Boolean,0,,\"If True, then do not attempt "
    L"to convert\",,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperToDoubleExample_Impl(CXlOper&, const CXlOper*, BOOL);
extern "C" __declspec(dllexport)
LPXLOPER12 OperToDoubleExample_12(LPXLOPER12 Arg1, BOOL Strict)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperToDoubleExample_Impl(xloResult, &Arg1__port,
            Strict));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperToDoubleExample_4(LPXLOPER4 Arg1, BOOL Strict)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperToDoubleExample_Impl(xloResult, &Arg1__port,
            Strict));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperToDoubleExample_Impl(CXlOper& xloResult, const CXlOper* Arg1, BOOL
    Strict)
{
    // End of generated code
//}}XLP_SRC

    // Note that ToDouble() will throw an Exception (interrupting execution)
    // if Strict is TRUE and Arg1 is not a number.

    // This will be caught by the wrapper function, and an error message
    // will be returned to Excel.

    xloResult = Arg1->ToDouble(Strict ? true : false);
    return xloResult.Ret();
}

Uses

CXlOper::ToDouble


CXlOper::ToDoubleArray() Examples

The first example demonstrates how to copy numeric values from an OPER to a single array of double's. The bByRows flag is set to FALSE, so columns are grouped together into the output array. The bStrict flag is set to FALSE, so non-numeric values are treated as zeroes.

CopyC++
//{{XLP_SRC(OperToDoubleArrayExample1)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperToDoubleArrayExample1 support code
IMPLEMENT_XLLFN4(OperToDoubleArrayExample1, OperToDoubleArrayExample1_4,
    OperToDoubleArrayExample1_12, "RP", "UQ", L"OperToDoubleArrayExample1", 0,
    L"Arg1", 0, L"Example", 0, L"Demonstrates COper::ToDoubleArray() with a si"
    L"ngle array", 0, L"Argument 1\0", 0, 0, L"{OperToDoubleArrayExample1,,,De"
    L"monstrates COper::ToDoubleArray() with a single array,Example,1,128,U,{{"
    L"0,{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperToDoubleArrayExample1_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperToDoubleArrayExample1_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperToDoubleArrayExample1_Impl(xloResult, &
            Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperToDoubleArrayExample1_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperToDoubleArrayExample1_Impl(xloResult, &
            Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperToDoubleArrayExample1_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    BOOL bOk = TRUE;

    USHORT usRows, usCols, i;
    double *pdArray = 0, dTotal = 0.0;

    bOk = Arg1->IsArray();

    if ( bOk )
    {
        // Allocate enough memory, in one continuous block,
        // to hold the results.
        Arg1->GetDims(usRows, usCols);
        pdArray = new double[usRows * usCols];

        // Copy the OPER's contents into an array of double's
        // Columns are kept together (bByRows=FALSE) and
        // non-numeric cell values are treated as zeroes
        // (bStrict=FALSE).
        Arg1->ToDoubleArray(pdArray, usRows, usCols,
                                FALSE, FALSE);

        // Do something useful (!) with the array
        for ( i = 0; i < (usRows * usCols); i++ )
            dTotal += pdArray[i];

        // Clean up
        delete[] pdArray;
    }

    if ( bOk )
        xloResult = dTotal;
    else
        xloResult = xlerrNA;

    return xloResult.Ret();
}

The second example demonstrates how to copy numeric values from an OPER to an array of pointers to double. The bByRows flag is set to FALSE, so columns are grouped together into the output array. The bStrict flag is set to TRUE, so non-numeric values are treated are not tolerated.

CopyC++
//{{XLP_SRC(OperToDoubleArrayExample2)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperToDoubleArrayExample2 support code
IMPLEMENT_XLLFN4(OperToDoubleArrayExample2, OperToDoubleArrayExample2_4,
    OperToDoubleArrayExample2_12, "RP", "UQ", L"OperToDoubleArrayExample2", 0,
    L"Arg1", 0, L"Example", 0, L"Demonstrates COper::ToDoubleArray() with an a"
    L"rray of pointers", 0, L"Argument 1\0", 0, 0, L"{OperToDoubleArrayExample"
    L"2,,,Demonstrates COper::ToDoubleArray() with an array of pointers,Exampl"
    L"e,1,128,U,{{0,{Arg1,Value,0,,Argument 1,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperToDoubleArrayExample2_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 OperToDoubleArrayExample2_12(LPXLOPER12 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperToDoubleArrayExample2_Impl(xloResult, &
            Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperToDoubleArrayExample2_4(LPXLOPER4 Arg1)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperToDoubleArrayExample2_Impl(xloResult, &
            Arg1__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperToDoubleArrayExample2_Impl(CXlOper& xloResult, const CXlOper* Arg1)
{
    // End of generated code
//}}XLP_SRC

    BOOL bOk = TRUE;

    USHORT usRows, usCols, i, j;
    double **ppdArray = 0, dTotal = 0.0;

    bOk = Arg1->IsArray();

    if ( bOk )
    {
        // Allocate enough memory to hold the results,
        // with each column in a block
        Arg1->GetDims(usRows, usCols);
        ppdArray = new double*[usCols];
        for ( j = 0; j < usCols; j++ )
            ppdArray[j] = new double[usRows];

        // Copy the OPER's contents into the arrays of
        // double's. Columns are kept together
        // (bByRows=FALSE) and non-numeric cell values
        // are not tolerated (bStrict=TRUE).
        bOk = Arg1->ToDoubleArray(ppdArray, usRows, usCols,
                                      FALSE, TRUE);
    }

    if ( bOk )
    {
        // Do something useful (!) with the array
        for ( i = 0; i < usRows; i++ )
            for ( j = 0; j < usCols; j++ )
                dTotal += ppdArray[j][i];

        // Clean up
        for ( j = 0; j < usCols; j++ )
            delete[] ppdArray[j];
        delete[] ppdArray;
    }

    if ( bOk )
        xloResult = dTotal;
    else
        xloResult = xlerrNA;

    return xloResult.Ret();
}

Uses

CXlOper::ToDoubleArray | CXlOper::IsArray


CXlOper::ToString() Example

CopyC++
//{{XLP_SRC(OperToStringExample)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region OperToStringExample support code
IMPLEMENT_XLLFN4(OperToStringExample, OperToStringExample_4,
    OperToStringExample_12, "RPA", "UQA", L"OperToStringExample", 0, L"Arg1,St"
    L"rict", 0, L"Example", 0, L"Demonstrates COper::ToString()", 0, L"Argumen"
    L"t 1\0If True, then do not attempt to convert\0", 0, 0, L"{OperToStringEx"
    L"ample,,,Demonstrates COper::ToString(),Example,1,128,U,{{0,{Arg1,Value,0"
    L",,Argument 1,,,,}},{0,{Strict,Boolean,0,,\"If True, then do not attempt "
    L"to convert\",,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* OperToStringExample_Impl(CXlOper&, const CXlOper*, BOOL);
extern "C" __declspec(dllexport)
LPXLOPER12 OperToStringExample_12(LPXLOPER12 Arg1, BOOL Strict)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperToStringExample_Impl(xloResult, &Arg1__port,
            Strict));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 OperToStringExample_4(LPXLOPER4 Arg1, BOOL Strict)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Arg1__port(Arg1);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(OperToStringExample_Impl(xloResult, &Arg1__port,
            Strict));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* OperToStringExample_Impl(CXlOper& xloResult, const CXlOper* Arg1, BOOL
    Strict)
{
    // End of generated code
//}}XLP_SRC

    // Note that ToString() will throw an Exception (interrupting execution)
    // if Strict is TRUE and Arg1 is not a string.

    // This will be caught by the wrapper function, and an error message
    // will be returned to Excel.

    xloResult = Arg1->ToString(Strict ? true : false);
    return xloResult.Ret();
}

Uses

CXlOper::ToString


CXlOper::VectorCell() Example

This example uses CXlOper::IsVector(),
CXlOper::GetVectorCount() and
CXlOper::VectorCell()
to iterate the cells in a CXlOper argument containing a vector.

CopyC++
//{{XLP_SRC(VectorSum)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region VectorSum support code
IMPLEMENT_XLLFN4(VectorSum, VectorSum_4, VectorSum_12, "RP", "UQ", L"VectorSum",
    0, L"Input", 0, L"Demo functions", 0, L"Returns the sum of a vector", 0,
    L"Input vector\0", 0, 0, L"{VectorSum,,,Returns the sum of a vector,Demo f"
    L"unctions,1,128,U,{{0,{Input,Value,0,,Input vector,,,,}}},{},3,,0,0,,,,0,"
    L"0}", 1, 0, 0)
CXlOper* VectorSum_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 VectorSum_12(LPXLOPER12 Input)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Input__port(Input);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(VectorSum_Impl(xloResult, &Input__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 VectorSum_4(LPXLOPER4 Input)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Input__port(Input);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(VectorSum_Impl(xloResult, &Input__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* VectorSum_Impl(CXlOper& xloResult, const CXlOper* Input)
{
    // End of generated code
//}}XLP_SRC

    BOOL bOk = TRUE;

    // This function doesn't work on 2-dimensional arrays
    // so return an error
    if ( !Input->IsVector() )
    {
        xloResult = xlerrValue;
        return xloResult.Ret();
    }

    // Iterate vector's cells, adding up
    // any numeric values
    USHORT i, cCells;
    double dSum = 0.0;
    cCells = (USHORT)Input->GetVectorCount();
    for ( i = 0; i < cCells; i++ )
    {
        if ( Input->VectorCell(i).IsDouble() )
            dSum += (double)Input->VectorCell(i);
    }

    // Return the total
    xloResult = dSum;
    return xloResult.Ret();
}

Uses

CXlOper::VectorCell | CXlOper::IsVector | CXlOper::GetVectorCount


CXlRef Example

This example shows how to use CXlOper::IsRef() and CXlOper::GetRef() to obtain a range reference from a reference-type function argument. The range is inspected and the greater of its width and height is returned.

CopyC++
//{{XLP_SRC(CheckArgSize)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region CheckArgSize support code
IMPLEMENT_XLLFN4(CheckArgSize, CheckArgSize_4, CheckArgSize_12, "RR", "UU",
    L"CheckArgSize", 0, L"Input", 0, L"Demo functions", 0, L"Inspect a XLREF p"
    L"assed from Excel", 0, L"Input reference\0", 0, 0, L"{CheckArgSize,,,Insp"
    L"ect a XLREF passed from Excel,Demo functions,1,128,U,{{0,{Input,Referenc"
    L"e,0,,Input reference,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* CheckArgSize_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 CheckArgSize_12(LPXLOPER12 Input)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Input__port(Input);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(CheckArgSize_Impl(xloResult, &Input__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 CheckArgSize_4(LPXLOPER4 Input)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Input__port(Input);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(CheckArgSize_Impl(xloResult, &Input__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* CheckArgSize_Impl(CXlOper& xloResult, const CXlOper* Input)
{
    // End of generated code
//}}XLP_SRC

    // Assume that function will fail
    xloResult = xlerrNA;

    // Is the argument a reference ?
    if ( Input->IsRef() )
    {
        // Get a pointer to the range
        const CXlRef xlr = Input->GetRef();
        // Return larger of width and height, as a number
        xloResult = (double)((xlr.Width() > xlr.Height())
            ? xlr.Width() : xlr.Height());
    }
    return xloResult.Ret();
}

Uses

CXlRef


matrix<T>::add_row() Example

CopyC++
// Function:    TestMatrixAddRow
// Returns:     LPXLOPER
// Description: Add a row to a matrix

//{{XLP_SRC(TestMatrixAddRow)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region TestMatrixAddRow support code
IMPLEMENT_XLLFN4(TestMatrixAddRow, TestMatrixAddRow_4, TestMatrixAddRow_12,
    "RJ", "UJ", L"TestMatrixAddRow", 0, L"RowsToAdd", 0, L"Example", 0, L"Add "
    L"a row to a matrix", 0, L"Number of rows to add\0", 0, 0, L"{TestMatrixAd"
    L"dRow,,,Add a row to a matrix,Example,1,128,U,{{0,{RowsToAdd,Int,0,,Numbe"
    L"r of rows to add,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* TestMatrixAddRow_Impl(CXlOper&, long);
extern "C" __declspec(dllexport)
LPXLOPER12 TestMatrixAddRow_12(long RowsToAdd)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(TestMatrixAddRow_Impl(xloResult, RowsToAdd));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 TestMatrixAddRow_4(long RowsToAdd)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(TestMatrixAddRow_Impl(xloResult, RowsToAdd));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* TestMatrixAddRow_Impl(CXlOper& xloResult, long RowsToAdd)
{
    // End of generated code
//}}XLP_SRC

    if ( RowsToAdd <= 0 )
        xloResult = xlerrNA;
    else
    {
        // Construct a matrix with 3 columns and no rows
        xlp::matrix<double> mat;
        mat.resize(0, 3);

        // An array of data to be added
        double adNew[3] = { 1.0, 2.0, 3.0 };

        // Add the new row RowsToAdd times
        for ( long i = 0; i < RowsToAdd; i++ )
            mat.add_row(adNew);

        // Copy the results to output
        xloResult = mat;
    }

    return xloResult.Ret();
}

Uses

matrix<T>::add_row


mtx_ptrs<T> Example

CopyC++
// Function:    MatrixAxisMean
// Purpose:     Returns the mean of the values in one axis of a matrix

//{{XLP_SRC(MatrixAxisMean)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MatrixAxisMean support code
IMPLEMENT_XLLFN4(MatrixAxisMean, MatrixAxisMean_4, MatrixAxisMean_12, "RPI",
    "UQI", L"MatrixAxisMean", 0, L"m,axis", 0, L"3", 0, L"Returns the mean of "
    L"the values in one axis of a matrix", 0, L"Square input matrix\0Axis - 0 "
    L"or 1\0", 0, 0, L"{MatrixAxisMean,,,Returns the mean of the values in one"
    L" axis of a matrix,3,1,128,U,{{0,{m,Double,2097162,,Square input matrix,,"
    L"{{{0,},{,}},{{0,},{,}}},,}},{0,{axis,Short Int,0,,Axis - 0 or 1,,,,}}},{"
    L"},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* MatrixAxisMean_Impl(CXlOper&, const CXlOper*, short int);
extern "C" __declspec(dllexport)
LPXLOPER12 MatrixAxisMean_12(LPXLOPER12 m, short int axis)
{
    XLL_FIX_STATE;
    CXlOper xloResult, m__port(m);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MatrixAxisMean_Impl(xloResult, &m__port, axis));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 MatrixAxisMean_4(LPXLOPER4 m, short int axis)
{
    XLL_FIX_STATE;
    CXlOper xloResult, m__port(m);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MatrixAxisMean_Impl(xloResult, &m__port, axis));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* MatrixAxisMean_Impl(CXlOper& xloResult, const CXlOper* m, short int
    axis)
{
    // Input buffers
    ple::mtx_ptrs<double> matm;
    // Validate and translate inputs
    XlReadMatrix(*m, mtx_adapter(matm), L"m", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK|XLA_BOUND_UBOUND_AUTO, 0, 0, 0, 0);
    // End of generated code
//}}XLP_SRC

    // Check that the matrix is square & not empty
    if (matm.size(0) != matm.size(1))
        return CXlOper::RetString("#Error: Expected a square matrix for m");
    if (matm.size(0) == 0)
        return CXlOper::RetString("#Error: Expected a non-empty square matrix for m");

    // Traverse the matrix
    int i, n = (int)matm.size(0);
    double dSum = 0.0;
    for (i = 0; i < n; i++)
        dSum += (axis == 0) ? matm[i][i] : matm[i][n - (1 + i)];
    dSum /= (double)n;

    // Return the result
    xloResult = dSum;
    return xloResult.Ret();
}

Uses

mtx_ptrs<T> | mtx_ptrs<T>::size | mtx_ptrs<T>::operator [] const


MyAddress Example

This example demonstrates how to examine and manipulate Excel cell addresses.

CopyC++
// Function:    MyAddress
// Returns:     LPXLOPER
// Description: Returns the address of the input range

//{{XLP_SRC(MyAddress)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MyAddress support code
IMPLEMENT_XLLFN4(MyAddress, MyAddress_4, MyAddress_12, "RR", "UU", L"MyAddress",
    0, L"Range", 0, L"14", 0, L"Returns the address of the input range", 0,
    L"Input range\0", 0, 0, L"{MyAddress,,,Returns the address of the input ra"
    L"nge,14,1,128,U,{{0,{Range,Reference,0,,Input range,,,,}}},{},3,,0,0,,,,0"
    L",0}", 1, 0, 0)
CXlOper* MyAddress_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 MyAddress_12(LPXLOPER12 Range)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Range__port(Range);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyAddress_Impl(xloResult, &Range__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 MyAddress_4(LPXLOPER4 Range)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Range__port(Range);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyAddress_Impl(xloResult, &Range__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* MyAddress_Impl(CXlOper& xloResult, const CXlOper* Range)
{
    // End of generated code
//}}XLP_SRC

    // Is the argument a reference ?
    if ( Range->IsRef() )
    {
        // Build up the full address of each range
        // eg "[Book1.xls]Sheet1!A1:B1"
        CString sAddress, sSheetName;
        // Start with the sheet name
        sSheetName = Range->GetSheetName() + "!";
        // Count the number of ranges
        WORD cRefs = Range->GetRefCount(), nRef;
        // Add each of the ranges
        for ( nRef = 0; nRef < cRefs; nRef++ )
        {
            // Put a comma between each range
            if ( nRef > 0 )
                sAddress += ",";
            // Append the address of each reference as a string;
            // the TRUE argument to ToString indicates that A1
            // style references should be used, rather than R1C1.
            sAddress += sSheetName
                     + Range->GetRefItem(nRef).ToString(TRUE);
        }
        // Copy the address to the result CXlOper
        xloResult = sAddress;
    }
    // If the argument is not a reference, return #N/A
    else
        xloResult = xlerrNA;

    return xloResult.Ret();
}

Uses

CXlOper::IsRef | CXlOper::GetSheetName | CXlOper::GetRefCount | CXlOper::GetRefItem | CXlRef::ToString


MyCorrel Example

This example demonstrates how to read vector inputs and pass them to a 'real-world' function.

CopyC++
#include <math.h>

// Function:    CalculateCorrel
// Returns:     double
// Description: Calculate the correlation of a series

double CalculateCorrel(int nSamples, const double* pdX,
                       const double* pdY)
{
    int i, j;
    double d, adSum[2], adSum2[2], dSumProd;
    const double* pdIn[2] = { pdX, pdY };
    double adSd[2], dCorrel;

    adSum[0] = adSum[1] = adSum2[0] = adSum2[1] = 0.0;
    dSumProd = 0.0;

    for ( i = 0; i < nSamples; i++ )
    {
        for ( j = 0; j < 2; j++ )
        {
            d = pdIn[j][i];
            adSum[j] += d;
            adSum2[j] += d * d;
        }
        dSumProd += pdIn[0][i] * pdIn[1][i];
    }

    for ( j = 0; j < 2; j++ )
        adSd[j] = sqrt((adSum2[j] - (adSum[j] * adSum[j] / nSamples))
                     / nSamples);

    if ( ( adSd[0] == 0.0 ) && ( adSd[1] == 0.0 ) )
        dCorrel = 1.0;
    else if ( ( adSd[0] == 0.0 ) || ( adSd[1] == 0.0 ) )
        dCorrel = 0.0;
    else
        dCorrel = (dSumProd - ((adSum[0] * adSum[1]) / nSamples))
                / ( nSamples * adSd[0] * adSd[1]);

    return dCorrel;
}

// Function:    MyCorrel
// Returns:     LPXLOPER
// Description: Calculate the correlation of two series

//{{XLP_SRC(MyCorrel)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MyCorrel support code
IMPLEMENT_XLLFN4(MyCorrel, MyCorrel_4, MyCorrel_12, "RPP", "UQQ", L"MyCorrel",
    0, L"X,Y", 0, L"14", 0, L"Calculate the correlation of two series", 0,
    L"First series\0Second series\0", 0, 0, L"{MyCorrel,,,Calculate the correl"
    L"ation of two series,14,1,0,U,{{0,{X,Double,10,,First series,,{{{,},{,siz"
    L"eOfX}}},,}},{0,{Y,Double,10,,Second series,,{{{,},{,sizeOfX}}},,}}},{},3"
    L",,0,0,,,,0,0}", 1, 0, 0)
CXlOper* MyCorrel_Impl(CXlOper&, const CXlOper*, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 MyCorrel_12(LPXLOPER12 X, LPXLOPER12 Y)
{
    XLL_FIX_STATE;
    CXlOper xloResult, X__port(X), Y__port(Y);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyCorrel_Impl(xloResult, &X__port, &Y__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 MyCorrel_4(LPXLOPER4 X, LPXLOPER4 Y)
{
    XLL_FIX_STATE;
    CXlOper xloResult, X__port(X), Y__port(Y);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyCorrel_Impl(xloResult, &X__port, &Y__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* MyCorrel_Impl(CXlOper& xloResult, const CXlOper* X_op, const CXlOper*
    Y_op)
{
    // Input buffers
    std::vector<double> X;
    std::vector<double> Y;
    // Named bounds
    long sizeOfX = -1;
    // Validate and translate inputs
    XlReadVector(*X_op, X, L"X", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK, &sizeOfX);
    XlReadVector(*Y_op, Y, L"Y", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK, &sizeOfX);
    // End of generated code
//}}XLP_SRC

    if (X.size() < 2)
        throw CXlRuntimeException("expeted at least two cells for X");

    // Call the real-world function & return the result
    xloResult = CalculateCorrel((int)X.size(), &X[0], &Y[0]);
    return xloResult.Ret();
}

Uses

CXlOper::Ret


MyDaysInFeb Example

This example demonstrates how to check for the presence or absence of optional arguments.

CopyC++
// Function:    MyDaysInFeb
// Returns:     LPXLOPER
// Description: Return the number of days in February in a year

//{{XLP_SRC(MyDaysInFeb)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MyDaysInFeb support code
IMPLEMENT_XLLFN4(MyDaysInFeb, MyDaysInFeb_4, MyDaysInFeb_12, "RP", "UQ", L"MyD"
    L"aysInFeb", 0, L"Year", 0, L"14", 0, L"Return the number of days in Febru"
    L"ary in a year", 0, L"Optional year as a number (Default = 1997)\0", 0, 0,
    L"{MyDaysInFeb,,,Return the number of days in February in a year,14,1,0,U,"
    L"{{0,{Year,Value,0,,Optional year as a number (Default = 1997),,,,}}},{},"
    L"3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* MyDaysInFeb_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 MyDaysInFeb_12(LPXLOPER12 Year)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Year__port(Year);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyDaysInFeb_Impl(xloResult, &Year__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 MyDaysInFeb_4(LPXLOPER4 Year)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Year__port(Year);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyDaysInFeb_Impl(xloResult, &Year__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* MyDaysInFeb_Impl(CXlOper& xloResult, const CXlOper* Year)
{
    // End of generated code
//}}XLP_SRC

    unsigned short usYear = 0;

    // If argument is missing, use default year value
    if ( Year->IsMissing() )
        usYear = 1997;

    // If argument is a double, use it
    else if ( Year->IsDouble() )
    {
        double dYear = Year->ToDouble();
        if ( dYear < 1904.0 || dYear > 2099.0 )
            xloResult = xlerrValue;
        else
            usYear = (unsigned short)dYear;
    }

    // Any other data type is unacceptable
    else
        xloResult = xlerrValue;

    // Get result if no error
    if ( usYear > 0 )
        xloResult = (double)((usYear % 4 != 0) ? 28 : 29);

    return xloResult.Ret();
}

Uses

CXlOper::IsMissing | CXlOper::IsDouble | CXlOper::operator =


MyDaysInMonth Example

This example shows how to return an array of numbers from an add-in function.

CopyC++
// Function:    MyDaysInMonth
// Returns:     LPXLOPER
// Description: Returns an array of all the days in a given month

//{{XLP_SRC(MyDaysInMonth)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MyDaysInMonth support code
IMPLEMENT_XLLFN4(MyDaysInMonth, MyDaysInMonth_4, MyDaysInMonth_12, "RH", "UH",
    L"MyDaysInMonth", 0, L"Month", 0, L"14", 0, L"Returns an array of all the "
    L"days in a given month", 0, L"Month number (1-12)\0", 0, 0, L"{MyDaysInMo"
    L"nth,,,Returns an array of all the days in a given month,14,1,0,U,{{0,{Mo"
    L"nth,Unsigned Short Int,0,,Month number (1-12),,,,}}},{},3,,0,0,,,,0,0}",
    1, 0, 0)
CXlOper* MyDaysInMonth_Impl(CXlOper&, unsigned short int);
extern "C" __declspec(dllexport)
LPXLOPER12 MyDaysInMonth_12(unsigned short int Month)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyDaysInMonth_Impl(xloResult, Month));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 MyDaysInMonth_4(unsigned short int Month)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyDaysInMonth_Impl(xloResult, Month));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* MyDaysInMonth_Impl(CXlOper& xloResult, unsigned short int Month)
{
    // End of generated code
//}}XLP_SRC

    if ( Month < 1 || Month > 12 )
        xloResult = xlerrValue;
    else
    {
        // How many days in the month ?
        int cDays;
        switch ( Month ) {
        case 2:
            cDays = 28;
            break;
        case 4: case 6: case 9: case 11:
            cDays = 30;
            break;
        default:
            cDays = 31;
            break;
        }

        // Allocate and fill array
        double* adDays = new double[cDays];
        for ( int i = 0; i < cDays; i++ )
            adDays[i] = (double)(i + 1);

        // Apply to xloResult
        xloResult.FromDoubleArray(adDays, cDays);

        // Clean up array
        delete[] adDays;
    }

    return xloResult.Ret();
}

Uses

CXlOper::FromDoubleArray


MyMonthsInYear Example

This example shows how to return an array of mixed types from an add-in function.

CopyC++
// Function:    MyMonthsInYear
// Returns:     LPXLOPER
// Description: Return array describing each month in a given year

//{{XLP_SRC(MyMonthsInYear)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MyMonthsInYear support code
IMPLEMENT_XLLFN4(MyMonthsInYear, MyMonthsInYear_4, MyMonthsInYear_12, "RH",
    "UH", L"MyMonthsInYear", 0, L"Year", 0, L"14", 0, L"Return array describin"
    L"g each month in a given year", 0, L"Year as a number (eg 2005)\0", 0, 0,
    L"{MyMonthsInYear,,,Return array describing each month in a given year,14,"
    L"1,0,U,{{0,{Year,Unsigned Short Int,0,,Year as a number (eg 2005),,,,}}},"
    L"{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* MyMonthsInYear_Impl(CXlOper&, unsigned short int);
extern "C" __declspec(dllexport)
LPXLOPER12 MyMonthsInYear_12(unsigned short int Year)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyMonthsInYear_Impl(xloResult, Year));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 MyMonthsInYear_4(unsigned short int Year)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyMonthsInYear_Impl(xloResult, Year));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* MyMonthsInYear_Impl(CXlOper& xloResult, unsigned short int Year)
{
    // End of generated code
//}}XLP_SRC

    if ( Year < 1901 || Year > 2099 )
        xloResult = xlerrValue;
    else
    {
        static LPCSTR apszMonths[12] = {
            "Jan", "Feb", "Mar", "Apr",
            "May", "Jun", "Jul", "Aug",
            "Sep", "Oct", "Nov", "Dec"
        };

        // Allocate the result array
        xloResult.AllocArray(12, 3);

        // Fill each row
        for ( unsigned short i = 0; i < 12; i++ )
        {
            // Put month number in first column
            xloResult.Cell(i, 0) = (double)(i + 1);
            // Put short month name in second column
            xloResult.Cell(i, 1) = apszMonths[i];
            // Put length of month in third column
            int cDays;
            switch ( i + 1 ) {
            case 2:
                cDays = (Year % 4 != 0) ? 28 : 29;
                break;
            case 4: case 6: case 9: case 11:
                cDays = 30;
                break;
            default:
                cDays = 31;
                break;
            }
            xloResult.Cell(i, 2) = (double)cDays;
        }
    }

    return xloResult.Ret();
}

Uses

CXlOper::AllocArray | CXlOper::Cell


MySort Example

This example demonstrates how to transform Excel data to an STL vector and back again.

CopyC++
// Function:    MySort
// Returns:     LPXLOPER
// Description: Sort a vector of numeric values

#include <vector>
#include <algorithm>
using namespace std;

//{{XLP_SRC(MySort)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MySort support code
IMPLEMENT_XLLFN4(MySort, MySort_4, MySort_12, "RP", "UQ", L"MySort", 0, L"Inpu"
    L"t", 0, L"14", 0, L"Sort a vector of numeric values", 0, L"Numeric vector"
    L"\0", 0, 0, L"{MySort,,,Sort a vector of numeric values,14,1,0,U,{{0,{Inp"
    L"ut,Double,10,,Numeric vector,,{{{,},{,}}},,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* MySort_Impl(CXlOper&, const CXlOper*);
extern "C" __declspec(dllexport)
LPXLOPER12 MySort_12(LPXLOPER12 Input)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Input__port(Input);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MySort_Impl(xloResult, &Input__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 MySort_4(LPXLOPER4 Input)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Input__port(Input);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MySort_Impl(xloResult, &Input__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* MySort_Impl(CXlOper& xloResult, const CXlOper* Input_op)
{
    // Input buffers
    std::vector<double> Input;
    // Validate and translate inputs
    XlReadVector(*Input_op, Input, L"Input", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK
        );
    // End of generated code
//}}XLP_SRC

    sort(Input.begin(), Input.end());
    xloResult = Input;
    return xloResult.Ret();
}

Uses

CXlOper::operator =


MySqrt Example

This example shows how to optionally return an error.

CopyC++
// Function:    MySqrt
// Returns:     LPXLOPER
// Description: Returns the square root of the input

//{{XLP_SRC(MySqrt)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MySqrt support code
IMPLEMENT_XLLFN4(MySqrt, MySqrt_4, MySqrt_12, "RB", "UB", L"MySqrt", 0, L"Inpu"
    L"t", 0, L"14", 0, L"Returns the square root of the input", 0, L"Number wh"
    L"ose square root is to be returned\0", 0, 0, L"{MySqrt,,,Returns the squa"
    L"re root of the input,14,1,0,U,{{0,{Input,Double,0,,Number whose square r"
    L"oot is to be returned,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* MySqrt_Impl(CXlOper&, double);
extern "C" __declspec(dllexport)
LPXLOPER12 MySqrt_12(double Input)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MySqrt_Impl(xloResult, Input));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 MySqrt_4(double Input)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MySqrt_Impl(xloResult, Input));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* MySqrt_Impl(CXlOper& xloResult, double Input)
{
    // End of generated code
//}}XLP_SRC

    if (Input < 0.0)
        throw CXlErrorException(xlerrValue);
    xloResult = sqrt(Input);
    return xloResult.Ret();
}

Uses

CXlOper::Ret


MySquare Example

This example shows a very basic add-in function.

CopyC++
// Function:    MySquare
// Returns:     double
// Description: Returns the square of the input

//{{XLP_SRC(MySquare)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MySquare support code
IMPLEMENT_XLLFN4(MySquare, MySquare_4, MySquare_12, "BB", "BB", L"MySquare", 0,
    L"Input", 0, L"14", 0, L"Returns the square of the input", 0, L"Number who"
    L"se square is to be returned\0", 0, 0, L"{MySquare,,,Returns the square o"
    L"f the input,14,1,128,B,{{0,{Input,Double,0,,Number whose square is to be"
    L" returned,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
double MySquare_Impl(double);
extern "C" __declspec(dllexport)
double MySquare_12(double Input)
{
    XLL_FIX_STATE;
    return MySquare_Impl(Input);
}
extern "C" __declspec(dllexport)
double MySquare_4(double Input)
{
    XLL_FIX_STATE;
    return MySquare_Impl(Input);
}

#pragma endregion

double MySquare_Impl(double Input)
{
    // End of generated code
//}}XLP_SRC

    return Input * Input;
}

Uses

::IMPLEMENT_XLLFN4


MySum Example

This example demonstrates how to iterate over array inputs.

CopyC++
// Function:    MySum
// Returns:     double
// Description: Returns the sum of numeric cells in the input range

//{{XLP_SRC(MySum)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MySum support code
IMPLEMENT_XLLFN4(MySum, MySum_4, MySum_12, "BP", "BQ", L"MySum", 0, L"Input", 0,
    L"14", 0, L"Returns the sum of numeric cells in the input range", 0, L"Inp"
    L"ut range\0", 0, 0, L"{MySum,,,Returns the sum of numeric cells in the in"
    L"put range,14,1,0,B,{{0,{Input,Value,0,,Input range,,,,}}},{},3,,0,0,,,,0"
    L",0}", 1, 0, 0)
double MySum_Impl(const CXlOper*);
extern "C" __declspec(dllexport)
double MySum_12(LPXLOPER12 Input)
{
    XLL_FIX_STATE;
    CXlOper Input__port(Input);
    return MySum_Impl(&Input__port);
}
extern "C" __declspec(dllexport)
double MySum_4(LPXLOPER4 Input)
{
    XLL_FIX_STATE;
    CXlOper Input__port(Input);
    return MySum_Impl(&Input__port);
}

#pragma endregion

double MySum_Impl(const CXlOper* Input)
{
    // End of generated code
//}}XLP_SRC

    // Initialise total
    double dSum = 0.0;

    // Get the size of the array
    unsigned short cRows, cCols;
    Input->GetDims(cRows, cCols);

    // Iterate through array, summing the values of cells
    for ( unsigned short i = 0; i < cRows; i++ )
    {
        for ( unsigned short j = 0; j < cCols; j++ )
        {
            CXlConstCell opItem = Input->Cell(i, j);
            if ( opItem.IsDouble() )
                dSum += opItem.ToDouble();
        }
    }

    return dSum;
}

Uses

CXlOper::GetDims | CXlOper::Cell | CXlOper::IsDouble | CXlOper::ToDouble


MyUpper Example

This example shows how create a CXlOper return value from a string.

CopyC++
// Function:    MyUpper
// Returns:     LPXLOPER
// Description: Returns the input string converted to upper-case

//{{XLP_SRC(MyUpper)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MyUpper support code
IMPLEMENT_XLLFN4(MyUpper, MyUpper_4, MyUpper_12, "RC", "UC%", L"MyUpper", 0,
    L"Input", 0, L"14", 0, L"Returns the input string converted to upper-case",
    0, L"Input string\0", 0, 0, L"{MyUpper,,,Returns the input string converte"
    L"d to upper-case,14,1,128,U,{{0,{Input,String,0,,Input string,,,,}}},{},3"
    L",,0,0,,,,0,0}", 1, 0, 0)
CXlOper* MyUpper_Impl(CXlOper&, const CXlStringArg&);
extern "C" __declspec(dllexport)
LPXLOPER12 MyUpper_12(const XCHAR* Input)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    CXlStringArg Input__port(Input);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyUpper_Impl(xloResult, Input__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 MyUpper_4(const char* Input)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    CXlStringArg Input__port(Input);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(MyUpper_Impl(xloResult, Input__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* MyUpper_Impl(CXlOper& xloResult, const CXlStringArg& Input)
{
    // End of generated code
//}}XLP_SRC

    CString stIn(Input);
    stIn.MakeUpper();
    xloResult = stIn;
    return xloResult.Ret();
}

Uses

CXlOper::CXlOper


XLL+ User Guide

Welcome to the XLL+ User Guide.

This is a guide to building Excel add-ins with the XLL+ toolkit. Through the use of tutorial examples, it shows each of the steps for creating an Excel add-in library.

Quick start
 | Quick start | A very short introduction to using XLL+
Getting started
 | Creating a project | How to create a new MS Developer Studio project for an Excel add-in library
 | Writing an add-in function | How to use the XLL+ Function Wizard to create an Excel add-in function
 | Testing your add-in function | How to run and debug your add-in function in Excel
 | Handling errors | How to return a different data type from a function, depending on whether the function succeeded or failed.
Basic features
 | Vector arguments | How to read one-dimensional arguments
 | Modifying an add-in function | How to use the XLL+ Function Wizard to modify an Excel add-in function, and regenerate the code
 | Optional arguments | How to test for a missing argument, and use a default if it is omitted
 | XLL Add-ins window | How to use the XLL Add-ins window to edit your add-in functions directly from Visual Studio
 | Matrix arguments | How to read two-dimensional arguments
 | Other matrix types | How to use different containers and layouts for two-dimensional data
 | Array results | How to return one- and two-dimensional results to Excel
 | String arguments | How to handle string (text) arguments
 | Value lists | How to handle enumerated (enum) arguments
 | Returning integer values | How to return an integer value as the result of an add-in function.
 | Upgrading | How to use the Upgrade Wizard to upgrade a project built with a previous version of XLL+; changes required for existing code
 | Deployment of XLLs | What you need to do to get your add-ins working on other machines
Intermediate features
 | Excel Formula Wizard | How to support the Excel Formula Wizard
 | Extending the Excel Formula Wizard | How to add drop-down lists and popup windows to the Excel Formula Wizard
 | Languages other than English | How to display messages in languages other than English
 | Help | How to generate a help file and link it to Excel's Formula Wizard
 | Exception handling | How XLL+ handles exceptions, and how to change the default behavior; how to trap C Run-time exceptions; how to raise exceptions in add-in functions
 | Macro functions | How to write add-in functions that make changes to workbooks
 | Global objects and data | How to write store global data, share it between threads, and handle initialization and termination
 | The Ribbon | How to add new controls to Excel's Ribbon so that users can run your macro add-in functions
 | Menus and toolbars | How to add new menus and toolbars to Excel so that users can invoke your add-in functions
 | Utility classes | A range of helpful classes for dates, cell replacement and serialization
 | Using MFC | How to use the Microsoft Foundation Classes from within an XLL
 | Using .NET | How to use .NET and the Common Language Runtime from within an XLL
 | Importing .NET Assemblies | Automatically generate a set of add-in functions as wrappers for any or all of the methods in a .NET assembly.
 | Sized result arrays | How to return an array result that exactly fits the range from which it was called
Advanced features
 | Handling events | How to write event handlers that will automatically run code when events (such as a workbook opening or recalculating) occur in Excel
 | Volatile functions | How to write add-in functions that will be recalculated whenever Excel recalculates a worksheet
 | Extended types | How to add new scalar data types, such as dates or enumerations
 | Function extensions | How to add new features and generated code to your functions
 | Object handles | How to expose objects in spreadsheets, using "handles"
 | Groups | How to reduce the number of arguments to a function, by grouping arguments together
 | Choices | How to allow an argument to have multiple valid formats, and use only one of them.
 | Function filters | Publishing and suppressing add-in functions: how to filter which functions are made available to users.
 | Favorites | How to save frequently used arguments to your favorites list, for re-use in other functions and libraries
 | International support | How to support users who prefer languages other than your own
 | Asynchronous functions | How to do work in background threads, and have Excel update when you are ready to supply it with new data
 | Queued functions | How to use the new Excel 2010 "Asynchronous function" feature, which allows thread-safe functions to work more efficiently when using a shared resource, such as a data-feed or a database.
 | Logging | How to use the XLL+ logging framework to write diagnostic and other information to log files

Note: In the tutorial steps, you are guided in building an add-in called Tutorial1. You can find all the code for this project, and all the other tutorial projects, under the Samples sub-directory of your XLL+ installation.


Quick start

After you have installed XLL+, follow these instructions for the quickest possible introduction to using XLL+. You can find out more about any of the steps by clicking on the "More..." links.

  1. Start Microsoft Visual Studio.

  2. Open the New Project window and use the XLL+ AppWizard to create a new project of type XLL+ 7 Excel Add-in. Accept all the default choices in the Wizard's pages.

    More on AppWizard...

  3. Open the main (.cpp) source file and use the XLL+ Function Wizard item on the Tools menu to open the create a new add-in function.

    On the Tools menu, click the New XLL+ Function item and then fill in the function's name, and press OK.

    More on creating add-in functions...

  4. In the XLL+ Function Wizard, add the function's description and category, add the names, types and descriptions of your function's arguments, and press OK.

    More on the Function Wizard...

  5. In Visual Studio, add your own code to the skeleton generated by the Wizard, then build and test your project. The code below sets the result of the function to -999.9. As with all the example code in this guide, the code which the developer should add is shown in inverse.

    CopyC++
    CXlOper* HISTVOL_Impl(CXlOper& xloResult, const CXlOper* Prices_op, double
    DaysPerYear)
{
    // Input buffers
    std::vector<double> Prices;
    // Validate and translate inputs
    XlReadVector(*Prices_op, Prices, L"Prices", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC

    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    xloResult = -999.9;

    return xloResult.Ret();
}

    In a real-world example, you would now pass the inputs to a useful function, and return the result, or handle any errors. For example, you might add the try-catch block shown below:

    CopyC++
    CXlOper* HISTVOL_Impl(CXlOper& xloResult, const CXlOper* Prices_op, double
    DaysPerYear)
{
    // Input buffers
    std::vector<double> Prices;
    // Validate and translate inputs
    XlReadVector(*Prices_op, Prices, L"Prices", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC

    try
    {
        xloResult = CalcHistVol(Prices, DaysPerYear);
    }
    catch(...)
    {
        xloResult = xlerrValue;
    }

    return xloResult.Ret();
}

    More on coding add-in functions...

For a more thorough introduction to XLL+, read through the topics in the Getting Started section.

Next: Creating an add-in project >>


Getting Started

This chapter contains the following topics:

Creating an add-in project
Writing an add-in function
Testing your add-in function
Handling errors


Creating an add-in project

Before we can start writing Excel add-ins, we need a Visual Studio project that will contain the make file and all the necessary framework code for an Excel add-in. We can use the XLL+ AppWizard to create a Visual Studio project that contains all the necessary files, and is ready to build and run.

For more details about the XLL+ AppWizard, see XLL+ AppWizard help.

New Project Dialog

In Visual Studio, click on File - New - Project (Shift+Ctrl+N) to bring up the New Project dialog. and select Visual C++ in the "Project types" pane. Out of the list of new project types, select XLL+ 7 Excel Add-in as shown in the picture below.

(It may also be a good idea to clear the check-box marked "Create directory for solution", if you are not intending to add further projects to the solution. If you intend to add additional projects to the solution, then you should leave the box checked.)

Type Tutorial1 in the project name field and click OK.

AppWizard - Overview

Note: The first time that you run the XLL+ AppWizard, you may notice a significant delay while the first page of the AppWizard appears. This is happening because the XLL+ project system is initializing for the first time, and is checking that the installation of XLL+ is complete and correct.

The first page of the XLL+ AppWizard describes the current settings and features for the project. Click Next to make some changes to the settings.

AppWizard - Application Settings

In the Application Settings page, type in XLL+ Tutorial as the XLL friendly name.

(This is the text that will appear in the Excel Tools - Add-Ins dialog. Don't worry if you can't think of the perfect name when you're creating your project - you can always change it later.)

Then click on Finish to accept the defaults.

Now we have created an XLL+ add-in project, we can start adding useful functions to it.

Next: Designing an add-in function >>

See Also

XLL+ AppWizard Help


Writing an add-in function

This chapter contains the following topics:

Designing an add-in function
Define the function
Add an argument
Completing the code


Designing an add-in function

The next step is to add an Excel Add-in function, using the XLL+ Function Wizard. In this example, we're going to write a function to return the cumulative normal (Gaussian) distribution.

Note: Readers familiar with Excel may ask why we are writing a cumulative normal distribution function when Excel already contains the NORMSDIST() function. There are three reasons:
  1. It may be useful to have an add-in function whose formula is precisely the same as that used in code elsewhere, such as in a library, or within other functions. This can make testing more precise and straightforward.
  2. NORMSDIST() is inaccurate at extreme values, and the inverse function NORMSINV() fails beyond 8 standard deviations. In Excel 2003 and 2007, the functions are better implemented than in older versions of Excel, but can still be improved upon.
  3. Most importantly, it makes a good example function.

It is good practise to put all important business functions in separate functions that are not Excel-dependent. If you do this, you will be able to reuse the code unchanged in other environments. That is what we will do here. The code for a stand-alone implementation of the cumulative normal distribution and its inverse is shown below.

Code for stand-alone functions

The Normal() and CumNormal() functions cannot fail, so they simply return their result.

InverseCumNormal() can fail if the input is out of range, so it returns 1 for success and 0 for failure. The inverted value is passed back via the pointer result.

CopyC++
#include <math.h>

// Normal distribution function
double Normal(double x)
{
    #define SQRT2PI 2.50662827463
    return exp(-x * x / 2.0) / SQRT2PI;
}

// Cumulative normal distribution function
double CumNormal(double x)
{
    #define gamma   0.2316419
    #define a1      0.319381530
    #define a2     -0.356563782
    #define a3      1.781477937
    #define a4     -1.821255978
    #define a5      1.330274429

    double k;

    if (x < 0.0 )
    {
        return 1.0 - CumNormal(-x);
    }
    else
    {
        k = 1.0 / (1.0 + gamma * x);
        return 1.0 - Normal(x) * ((((a5 * k + a4) * k + a3) * k + a2) * k + a1) * k;
    }
}

// Inverse cumulative normal function
// Returns 1 for success, 0 for failure
int InverseCumNormal(double u, double* result)
{
    int i;
    double Y, num, den;

    static double p[] = {
        -0.322232431088,
        -1.0,
        -0.342242088547,
        -0.0204231210245,
        -0.0000453642210148
    };
    static double q[] = {
        0.099348462606,
        0.588581570495,
        0.531103462366,
        0.10353775285,
        0.0038560700634
    };

    if (u <= 0.0 || u >= 1.0)
        return 0;

    if (fabs(u - 0.5) < 10e-8) {
        *result = 0.0;
        return 1;
    }

    if (u < 0.5) {
        InverseCumNormal(1.0 - u, result);
        *result *= -1.0;
        return 1;
    }

    Y = sqrt(-log((1.0 - u)*(1.0 - u)));
    num = p[4];
    den = q[4];

    for (i=3; i>=0; i--)
    {
        num = num*Y + p[i];
        den = den * Y + q[i];
    }

    *result = Y + num / den;
    return 1;
}

Adding the stand-alone functions

In Visual Studio, open the file Tutorial1.cpp, and add the code above at the end of the file.

Tip: It is a very bad idea to type in all the code shown above. You can copy it from here and paste into your source file, or you can find all the code for this tutorial in the Samples/Tutorial1 sub-directory.

All the important code is now written. All we need to do is to generate the Excel add-in function, and plug it into a stand-alone function.

Next: Define the function >>


Define the function

The next step is to use the XLL+ Function Wizard to generate the code for the Excel add-in function NORMSDIST2().

Select a source file

Make sure that Developer Studio is open and that Tutorial1 is the active project. Open or activate the file Tutorial1.cpp.

Invoke the Function Wizard

In Visual Studio, use the New XLL+ Function item on the Tools menu to start the Function Wizard.

Enter function name

In the Add New Function dialog, fill in the name, NORMSDIST2.

After you click on OK, the main Function Wizard dialog will appear, so that you can enter the definition of the new add-in function.

Add function details

In the XLL+ Function Wizard, set the following fields

Return type: Double
Category: Statistical
Description: Returns the standard normal cumulative distribution function (has a mean of zero and a standard deviation of one)

What do all these fields mean?

Name

The name you enter here will be used as the name of the function visible in Excel and also as the name of the C++ function that implements the add-in function.

Return type

The type of value that will be returned to Excel by the add-in function. In this case "Double" stands for "double-precision floating-point number".

Category

When the function appears in Excel's Formula Wizard, it will appear under the category you enter here.

Description

This description will appear in Excel's Formula Wizard. It will also be inserted into your C++ code as part of the function's header comment.

Next: Add an argument >>


Add an argument

Add an argument

The next thing we need to do is add an argument. In the first column of the empty row in the arguments grid, select the argument type Double as shown below.

In the second column, type the argument name Z.

Set argument description

Fill in the description column, as follows:

Z is the value for which you want the distribution

The columns describing the argument should now contain the following:

Type: Double
Name: Z
Description: Z is the value for which you want the distribution

We have now finished specifying our add-in function. Click on the OK button to dismiss the Wizard and update the source code.

Next: Completing the code >>


Completing the code

Code generated by the wizard

As you return to Visual Studio, you will see that the wizard has inserted the following source code at the end of your C++ file.

CopyC++
// Function:    NORMSDIST2
// Purpose:     Returns the standard normal cumulative distribution function (has a mean of zero and a standard deviation of one)

//{{XLP_SRC(NORMSDIST2)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region NORMSDIST2 support code
IMPLEMENT_XLLFN4(NORMSDIST2, NORMSDIST2_4, NORMSDIST2_12, "BB", "BB", L"NORMSD"
    L"IST2", 0, L"Z", 0, L"4", 0, L"Returns the standard normal cumulative dis"
    L"tribution function (has a mean of zero and a standard deviation of one)",
    0, L"Z is the value for which you want the distribution\0", 0, 0, L"{NORMS"
    L"DIST2,,,Returns the standard normal cumulative distribution function (ha"
    L"s a mean of zero and a standard deviation of one),4,1,0,B,{{0,{Z,Double,"
    L"0,,Z is the value for which you want the distribution,,,,}}},{},3,,0,0,,"
    L",,0,0}", 1, 0, 0)
double NORMSDIST2_Impl(double);
extern "C" __declspec(dllexport)
double NORMSDIST2_12(double Z)
{
    XLL_FIX_STATE;
    return NORMSDIST2_Impl(Z);
}
extern "C" __declspec(dllexport)
double NORMSDIST2_4(double Z)
{
    XLL_FIX_STATE;
    return NORMSDIST2_Impl(Z);
}

#pragma endregion

double NORMSDIST2_Impl(double Z)
{
    // End of generated code
//}}XLP_SRC
    // TODO - set the return value.
    return 0;
}

In the following sections, we'll examine all this code.

Hidden code

You may find that much of the code is hidden; it sits between #pragma region and #pragma endregion, and the XLL+ Function Wizard has automatically hidden it for you.

You can make it visible by clicking on the little "+" symbol in the left margin. See Hidden regions for more information.

Delimiters

The first thing to notice are the XLP_SRC comments that delimit the generated code:

CopyC++
//{{XLP_SRC(NORMSDIST2)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!
    ...
//}}XLP_SRC

The Function Wizard "owns" all the code between the delimiters. Everything between these comments is liable to be written over if you use the Function Wizard again to change the function in any way. Be very careful to make your changes outside these delimiters.

Macro

The next section of interest is the IMPLEMENT_XLLFN4(...) macro:

CopyC++
IMPLEMENT_XLLFN4(NORMSDIST2, NORMSDIST2_4, NORMSDIST2_12, "BB", "BB", ...

This macro contains all the information you typed into the Function Wizard. At run-time, the XLL+ runtime library will pass all this data to Excel, in order to register your function and to tell Excel about its arguments. (Again, be careful not to alter it yourself.)

If you need to come back to the function later to change it, then the XLL+ Function Wizard will read the macro and construct the function's definition from it.

Wrapper functions

A function that is exported to Excel 2007 must follow different rules to a function exported to Excel 2003 and below. The XLL+ Function Wizard generates two versions of each add-in function, one for Excel 2003 and below (named NORMSDIST2_4) and one for Excel 2007 and above (named NORMSDIST2_12). Both of these functions are wrappers, which call the same common function, NORMSDIST2_Impl.

The next section of code declares the common function, and defines the two wrapper functions.

CopyC++
double NORMSDIST2_Impl(double);

extern "C" __declspec(dllexport)
double NORMSDIST2_12(double Z)
{
    XLL_FIX_STATE;
    return NORMSDIST2_Impl(Z);
}
extern "C" __declspec(dllexport)
double NORMSDIST2_4(double Z)
{
    XLL_FIX_STATE;
    return NORMSDIST2_Impl(Z);
}

Definition of common function

Finally, we have the definition of the common function.

CopyC++
double NORMSDIST2_Impl(double Z)
{
    // End of generated code
//}}XLP_SRC
    // TODO - set the return value.
    return 0;
}

We have a complete skeleton of the function; now we need to add some useful code.

Adding some useful code

Add code to the add-in function to call our stand-alone function, as shown below:

CopyC++
double NORMSDIST2_Impl(double Z)
{
    // End of generated code
//}}XLP_SRC
    return CumNormal(Z);
}

That's the lot. We're now ready to build and test our add-in function.

Next: Building your add-in library >>


Testing your add-in function

This chapter contains the following topics:

Building your add-in library
Testing & debugging in Visual Studio


Building your add-in library

To test the function under the Visual Studio debugger, follow the steps in the following sections.

Note: If you are already familiar with debugging Excel add-ins under Visual Studio, jump to the next chapter.

Build the debug version

If the Debug build is not currently selected, then use Visual Studio's Build - Configuration Manager... menu option and select the Debug configuration, as shown below:

Note: If you are using a 64-bit version of Excel for debugging and testing, then you should also select x64 as the Active solution platform. If you are using a 32-bit version of Excel, then you must select Win32 as the platform.

Then press the Shift+Ctrl+B key combination (or use the Build - Build Solution menu option) to build the project.

Start Excel

Press F5 (or use the Start - Debug menu option) to start Excel.

You may be shown a dialog informing you that you cannot debug Excel.

That's fine; we just want to debug our add-in. Check the box marked "Don't show this dialog again" and click on Yes to continue. That should be last time we see that dialog.

Depending on your security settings, a security dialog may appear.

If it appears, click on "Enable this add-in for this session only" or "Enable Macros".

Tip: This security dialog can get very tedious very quickly. See Security settings for instructions on how to prevent it during development.

Security settings

If the dialogs above did not appear, or if your functions don't appear in Excel, then it's worth checking your security settings at this point: if your macro security level is set to "High", then you will not be able to test your add-in, since Excel will not allow you to open any XLL.

Excel 2010

In Excel 2010, click on the File tab, and then on the button "Options", which appears near the bottom-left of the backstage view.

In the "Excel Options" window, select "Trust Center" from the list on the left, and then click the "Trust Center Settings..." button.

In the "Trust Center" window, select "Macro Settings" from the list on the left, and set the "Macro Settings" level to either of: "Disable all macros with notification" or "Enable all macros (...)".

(Note: While the second choice, "Enable all macros (...)" is very convenient to use, it is not safe unless your computer is running on a safe network, or you never open spreadsheets from external sources.)

Excel 2007

In Excel 2007, click on the Office Button, and then on the button "Excel Options", which appears at the bottom of the menu.

In the "Excel Options" window, select "Trust Center" from the list on the left, and then click the "Trust Center Settings..." button.

In the "Trust Center" window, select "Macro Settings" from the list on the left, and set the "Macro Settings" level to either of: "Disable all macros with notification" or "Enable all macros (...)".

(Note: While the second choice, "Enable all macros (...)" is very convenient to use, it is not safe unless your computer is running on a safe network, or you never open spreadsheets from external sources.)

Excel 2003/XP

In Excel 2003 or Excel XP, use the "Tools/Options..." menu command to display the "Options" window.

In the "Options" window, select the "Security" tab, and then click the "Macro Security..." button.

In the "Security" window, select the "Security Level" tab, and set the level to either "Medium" or "Low".

(Note: While the "Low" setting is very convenient to use, it is not safe unless your computer is running on a safe network, or you never open spreadsheets from external sources.)

Next: Testing & debugging in Visual Studio >>


Testing & debugging in Visual Studio

Open the add-in

As soon as Excel starts, it will attempt to open the Debug build of your add-in. (This is because the XLL+ AppWizard set the "Command Arguments" property of the configuration to "$(TargetDir)/Tutorial1.xll" when the project was created.)

Use the add-in function

In Excel, type a NORMSDIST2(...) formula into a spreadsheet. Under Excel 2007 and above, you'll see your new function appear in the auto-complete list, as shown below:

Once the formula is entered, you'll see the result.

Set a break-point

Switch to Visual Studio - you do not need to close Excel to do so. Select Tutorial1.cpp and use the F9 key (or the right-mouse menu) to add a break-point to the add-in function, as shown below.

Force a recalculation

Force a formula cell to recalculate. The easiest way to this is to go to the cell you want to recalculate (in this case, cell B1) and click on the F2 key then the Enter key. (Alternatively, you can simply change the value in cell A1.)

After you press Enter, Excel will call the add-in function and the Visual Studio debugger will break at the break-point. You can step through the lines of the function (with F10 and F11) or continue (with F5).

Close Excel and return to Visual Studio. We are now ready to add another add-in function.

Next: Functions with variable return types >>


Handling errors

This chapter contains the following topics:

Functions with variable return types
Returning CXlOper
Inside CXlOper
Error values in Excel
Throwing exceptions


Functions with variable return types

Our first add-in function, NORMSDIST2(), was very simple to implement. Our next example is a little more complex. The inverse function, NORMSINV2(), can fail if the input is not between 0 and 1 (exclusive). In Excel, this failure is represented by the error type #NUM!.

Our next task is to use the XLL+ Function Wizard to generate a function that returns either a number or an error, depending on whether it is successful.

Invoke the Function Wizard

Make sure that Developer Studio is open and that Tutorial1 is the active project. Open or activate the file Tutorial1.cpp.

Use the New XLL+ Function item on the Tools menu to start the Function Wizard.

Enter function details

In the Add New Function dialog, fill in the name, NORMSINV2, and click OK.

In the XLL+ Function Wizard, fill in the category and description of the function as follows:

Return type: CXlOper
Category: Statistical
Description: Returns the inverse of the standard normal cumulative distribution. The distribution has a mean of zero and a standard deviation of one.

Next: Returning CXlOper >>


Returning CXlOper

CXlOper return type

When the Function Wizard appears, it will (as usual) have the default return type CXlOper. Leave this value as it is. CXlOper is a special Excel data type that is capable of containing many different types of value.

Add the argument

In the arguments grid, add the argument as follows:

Name: Probability
Type: Double
Description: Probability is a probability corresponding to the normal distribution, a number between 0 and 1 exclusive

The Wizard should now look like the picture below.

Click on the OK button to dismiss the Wizard and update the source code.

Next: Inside CXlOper >>


Inside CXlOper

Code generated by the wizard

As you return to Visual Studio, you will see that the wizard has inserted all the source code for NORMSINV2 at the end of your C++ file. The code that is interestingly different from our previous example, NORMSDIST2, is marked below.

CopyC++

CXlOper* NORMSINV2_Impl(CXlOper& xloResult, double Probability)
{
    // End of generated code
//}}XLP_SRC
    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    return xloResult.Ret();
}

Note each of the changed pieces of code:

  1. The function now returns CXlOper*.
  2. An extra argument xloResult is declared, of type CXlOper&. This is used to hold the data (of variable type) that we will return to Excel.
  3. The value xloResult.Ret() is returned by the function.

What is CXlOper ?

CXlOper is a C++ class, which performs many useful tasks when managing data that is to be shared with Excel. It represents a value of variable type. Among the types of value it can hold are:

  • double
  • boolean
  • string
  • error
  • array
  • reference to a range of cells

The CXlOper assigment operator, '=', is overloaded, which means that we can use code like the following to set its values:

CopyC++
CXlOper xloResult;
xloResult = 9.9;        // Set the type to double, and the value to 9.9
xloResult = "abc";      // Set the type to string, and the value to "abc"
xloResult = xlerrValue; // Set the type to error, and the value to #VALUE!

Other assignment operators allow you to set a CXlOper's value to an array.

The CXlOper class is used throughout XLL+ to hold values that are shared with Excel. If you request data from Excel, for example to get the current language settings, it will be returned in a CXlOper.

See CXlOper in the class reference for full details of CXlOper.

Adding some useful code

Add code to the function to call our stand-alone function, as shown below:

CopyC++
CXlOper* NORMSINV2_Impl(CXlOper& xloResult, double Probability)
{
//}}XLP_SRC

    double Z;
    if (InverseCumNormal(Probability, &Z))
        xloResult = Z;
    else
        xloResult = xlerrNum;
    return xloResult.Ret();
}

Depending on whether InverseCumNormal() succeeds we will either set CXlOper to contain the result of the calculation, or set it to contain the error code xlerrNum.

xlerrNum appears in Excel as #NUM!. For a full list of error codes, see Error codes.

Why xloResult.Ret() ?

xloResult is a local variable, and therefore goes out of scope at the end of the function in which it is declared. This means that its destructor will be called, and its value will be destroyed, and will therefore not be available to Excel. The Ret() method deals with this problem. It carries out three steps:

  1. Transfer the value in the CXlOper to a static buffer.
  2. Mark the data as belonging to the XLL, so that Excel will ensure that a callback in the XLL is used to destroy it later.
  3. Returns a pointer to the static buffer that now contains the data.

All this work is essential but dull, and is completely handled by the Ret() method, so that you need not concern yourself with it further.

Our second add-in function is now complete and we're ready to build and test it.

Next: Error values in Excel >>


Error values in Excel

Once you've rebuilt the add-in (Shift+Ctrl+B in VS 2005), you can test it in Excel as shown below.

Notice how #NUM! is returned if Probability is out of range.

Accuracy of NORMSINV2

The cumulative distribution algorithms supplied here for the examples are not very accurate. They are better than those supplied in older versions of Excel, but not as good as the algorithms used in Excel 2003 onwards.

For a much better algorithm, look at the excellent QuantLib library at http://quantlib.org, in particular at the InverseCumulativeNormal class, which uses both Acklam's approximation and Halley's method to produce a number that is consistently better than the built-in Excel function, NORMSINV. (You should #define REFINE_TO_FULL_MACHINE_PRECISION_USING_HALLEYS_METHOD in normaldistribution.cpp to get the best accuracy available.)

Next: Throwing exceptions >>


Throwing exceptions

Another useful technique for handling errors is to throw an exception of type CXlErrorException. This has the same effect as setting xloResult to an error value, and allows more natural C++ program flow.

For the previous example, throwing an exception would result in code like this:

CopyC++
CXlOper* NORMSINV2_Impl(CXlOper& xloResult, double Probability)
{
    CXlOper xloResult;
//}}XLP_SRC

    double Z;
    if (!InverseCumNormal(Probability, &Z))
        throw CXlErrorException(xlerrNum);
    xloResult = Z;
    return xloResult.Ret();
}

Particularly when there are many possible avenues to failure, this approach leads to more transparent and reliable code.

Next: A function with a vector argument >>


Basic Features

This chapter contains the following topics:

Vector arguments
Modifying an add-in function
Optional arguments
XLL Add-ins Window
Two-dimensional arguments
Other matrix types
Array results
Strings
Value lists
Returning integer values
Upgrading from a previous version of XLL+
Deployment of XLLs


Vector arguments

This chapter contains the following topics:

A function with a vector argument
Creating a vector argument
Understanding the vector code
Input error handling


A function with a vector argument

The arguments we have used so far have been simple scalar values. Most add-in functions also need to be able to handle array values. In the following sections we are going to use the Function Wizard to create a function with a vector input.

Historical volatility function

We are going to add a function to calculate the historical volatility of a series of daily prices. The function will be implemented as a stand-alone pure C++ function, with no awareness of Excel.

Add the following code to Tutorial1.cpp:

CopyC++
// Calculates historical volatility of daily price data
// May throw an exception (as text)
double CalcHistVol(const std::vector<double>& values, double dDaysInYear)
{
    if (values.size() < 2)
        throw "too few points";

    // Calculate the returns
    std::vector<double> returns(values.size() - 1);
    for (size_t i = 0; i < returns.size(); i++) {
        double dDen = values[i];
        if (dDen == 0.0)
            throw "zero value";
        double dRatio = values[i + 1] / dDen;
        if (dRatio < 0.0)
            throw "negative value";
        returns[i] = log(dRatio);
    }

    // Calculate the standard deviation of the returns
    double dSum = 0.0, dSumSq = 0.0, dSD;
    for (size_t i = 0; i < returns.size(); i++) {
        double ret = returns[i];
        dSum += ret;
        dSumSq += ret * ret;
    }
    dSD = sqrt((dSumSq - (dSum * dSum / (double)returns.size()))
             / ((double)returns.size()));

    // Calculate the historic volatility
    if (dDaysInYear <= 0.0)
        throw "DaysInYear must be positive";
    return dSD * sqrt(dDaysInYear);
}

The function returns the historical volatility of the series if it succeeds. Otherwise, it throws an exception.

Next: Creating a vector argument >>


Creating a vector argument

Create a new function

Use the New Function tool to create a new add-in function. Fill in the name, category and description of the function as follows:

Name: HISTVOL
Return type: CXlOper
Category: Statistical
Description: Returns the historical volatility of a series of daily prices

Add a vector argument

In the Function Wizard arguments grid add a new argument Prices, and then click on the vector tool-button, as indicated below.

This will change the argument to a vector. Finally, change the description of Prices to:

Series of daily prices
The argument's columns should now read as follows:

Name: Prices
Type: Double[]
Description: Series of daily prices

After you add the argument, the Function Wizard should look like this:

Click on the OK button to dismiss the Wizard and update the source code.

Next: Understanding the vector code >>


Understanding the vector code

The new function will have been inserted into your code. The interesting code in the common function is marked below:

CopyC++
CXlOper* HISTVOL_Impl(CXlOper& xloResult, const CXlOper* Prices_op)
{
    // Input buffers
    std::vector<double> Prices;
    // Validate and translate inputs
    XlReadVector(*Prices_op, Prices, L"Prices", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC
    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    return xloResult.Ret();
}

As you can see, the Wizard has generated more code this time. Let us examine the new features.

CXlOper type argument

The argument type has been declared as const CXlOper*. In the last example, NORMSINV2, we used CXlOper to return data to Excel. Here, Excel is using CXlOper to pass data to our add-in function.

Because CXlOper is a generic type, we cannot know in advance what it will contain. The user may pass a single value instead of a series, or a string value, or they may omit the value altogether. Whatever the user specifies, Excel will pass it straight on to our function. It is the responsibility of the add-in function to ensure that the argument contains the expected type of data. The Wizard generates code to handle this.

STL vector

An STL vector of doubles, Prices, has been declared. This will be used as a convenient variable-size buffer for the data passed from Excel in the CXlOper Prices_op.

Note: The best thing about using an STL vector is that we don't have to worry about memory cleanup. As soon as Prices goes out of scope (i.e. at the end of the function), all its memory will be released. We do not have to remember to use free() or delete.

Input checking

The function is going to have do some processing of input to a more useful form. In particular, the data in Prices_op has to be extracted from the CXlOper and put into an array of doubles.

CopyC++
std::vector<double> Prices;
XlReadVector(*Prices_op, Prices, L"Prices");

The template method XlReadVector() is used to do the data extraction. If the extraction fails for any reason, then an exception of type CXlRuntimeException will be thrown, containing details of why the conversion failed. For example, if the third cell in Prices contains the text "Cheese", the exception will contain the following message:

Expected number for Prices[3]
Note: The message does not need to be in English. Depending on the current Windows language, the message may be localized. See International support for details.

Early exit

If the extraction process has failed, and an exception is thrown, the function will immediately stop, and the exception will be caught and handled by the wrapper function, HISTVOL_4 or HISTVOL_12.

CopyC++
extern "C" __declspec(dllexport)
LPXLOPER12 HISTVOL_12(LPXLOPER12 Prices)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Prices__port(Prices);
    try {
        xloResult.HandleResult(HISTVOL_Impl(xloResult, &Prices__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    return xloResult.Ret12();
}

The exception is handed to the application-level method, CXllApp::DisplayException(), which will deal with it in a standard way. (You can override DisplayException() in your add-in if you wish.) The standard behaviour is to display a text string, e.g.:

#ERROR: Expected number for Prices[3]

If it succeeds, then we can be confident that the vector Prices is now populated with an array of numeric values, and we can safely call our implementation function, CalcHistVol().

Truncating the input

The call to XlReadVector(...) also does some other useful work. If the user has left some of the cells at the end of the input range empty, XlReadVector() will truncate them, rather than putting null values into Price.

Adding some useful code

Add code to the function to call our stand-alone function, as shown below:

CopyC++
CXlOper* HISTVOL_Impl(CXlOper& xloResult, const CXlOper* Prices_op)
{
    // Input buffers
    std::vector<double> Prices;
    // Validate and translate inputs
    XlReadVector(*Prices_op, Prices, L"Prices", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC
    try
    {
        xloResult = CalcHistVol(Prices, 250.0);
    }
    catch(const char*)
    {
        xloResult = xlerrNum;
    }
    return xloResult.Ret();
}

Depending on whether CalcHistVol() succeeds, we will either set CXlOper to contain the result of the calculation, or set it to contain the error code xlerrNum, indicating that the inputs were out of range is some way.

Our add-in function is now complete and we're ready to build and test it.

Next: Input error handling >>


Input error handling

Once you've rebuilt the add-in (Shift+Ctrl+B in Visual Studio), you can test it in Excel as shown below.

Notice that the function returns an informative error string if the Prices argument is not well-formed.

Notice also how #NUM! is returned if the calculation fails (in this case because of a zero price) even though the data is well-formed.

Next: Modifying an add-in function with the Wizard >>


Modifying an add-in function

This chapter contains the following topics:

Modifying an add-in function with the Wizard
Changes to the generated code


Modifying an add-in function with the Wizard

It isn't always possible to get the function definition right the first time around. You may need to go back and change details of a function's specification. For example, you may want to:

  • Add another argument
  • Remove an argument
  • Change the order of arguments
  • Make an argument optional
  • Change the name or description of an argument

The Function Wizard can do all of these tasks and many more. The Function Wizard can read the code that it generates, so that you can edit a definition you have previously created.

Adding another argument

Let's revisit our historical volatility calculator, and let the user specify the number of business days in a year. In our first implementation, we hard-coded this to 250.

Launch the Function Wizard

To fix the problem, we need to revisit the function definition using the Function Wizard. In Visual Studio, put the cursor somewhere in the body of the HISTVOL() function and click on the Tools/XLL+ Function Wizard tool.

Select HISTVOL

The Function Wizard will appear, with the HISTVOL function definition displayed. If another function is displayed instead, use the File/Select Function tool-button or menu to select HISTVOL, as shown below

You can now make any changes you need to the function and, when you press OK, the code in your source file will be regenerated.

Note: only code between the //{{XLP_SRC delimiters will be overwritten. Any code which you have added outside the delimiters will be unaffected.

Add a new argument

In the arguments grid, go to the Name column of the last line and type in the name of the argument, DaysPerYear.

Fill in the argument's columns as follows:

Name: DaysPerYear
Type: Double
Description: Number of samples per year

After you add the argument, the Function Wizard should look like this:

Click on the OK button to dismiss the Wizard and update the source code.

Next: Changes to the generated code >>


Changes to the generated code

When you return to your source code, you will see that some of the generated code has been changed.

CopyC++
CXlOper* HISTVOL_Impl(CXlOper& xloResult, const CXlOper* Prices_op, doubleDaysPerYear)
{
    // Input buffers
    std::vector<double> Prices;
    // Validate and translate inputs
    XlReadVector(*Prices_op, Prices, L"Prices", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC
    try
    {
        xloResult = CalcHistVol(Prices, 250.0);
    }
    catch(const char*)
    {
        xloResult = xlerrNum;
    }
    return xloResult.Ret();
}

Notice that your code outside the //{{XLP_SRC delimiters is unchanged; all the changes occur within the delimiters, in the portion of the code that is "owned" by the XLL+ Function Wizard.

Make one more change to the function, to pass the new argument to our CalcHistVol(), as shown below:

CopyC++
CXlOper* HISTVOL_Impl(CXlOper& xloResult, const CXlOper* Prices_op, double
    DaysPerYear)
{
    ...

    try
    {
        xloResult = CalcHistVol(Prices, DaysPerYear);
    }
    catch(const char*)
    {
        xloResult = xlerrNum;
    }
    return xloResult.Ret();
}

The new release of the function is now complete, and ready for building and testing.

A cautionary note

Existing users of the function will be inconvenienced by this change, since they will now get a #NUM! error in all their existing spreadsheets.

In the next chapter, we will revisit this function, and replace DaysPerYear with an optional argument, which, if omitted, will be defaulted to 250. That way, the existing users are unaffected, and new users can choose to specify the days per year or to omit it, as they prefer.

Next: Adding an optional argument >>


Optional arguments

This chapter contains the following topics:

Adding an optional argument
Creating optional arguments
Reading an optional argument
More on optional arguments


Adding an optional argument

The need for optional arguments

At the end of the last section, it was noted that changing the interface of our HISTVOL add-in function was inconvenient for existing users of the function. Existing spreadsheets which used the function would be broken.

The old release of HISTVOL only expected one argument, but the new one expects two, a series and a number. If a numeric argument is omitted, as will be the case with all cells which use the old release of HISTVOL, then Excel passes the value zero instead. We need to do something to make sure that the existing cells get the same result as they received using the old release.

We have two choices for implementing optional arguments:

  1. Rely on Excel to set the value to zero. We will need to add code to change the value of DaysPerYear to 250 if (and only if) it is equal to zero. This is an acceptable solution in this case, because zero is an illegal value for this argument.
  2. Use the XLL+ Function Wizard to write code that will test the input and set it to the default value if it is missing.

Using zero as a default

The first method is very easy to implement. You could just add a test to our latest implementation, as follows:

CopyC++
CXlOper* HISTVOL_Impl(CXlOper& xloResult, const CXlOper* Prices_op, double
    DaysPerYear)
{
    // Input buffers
    std::vector<double> Prices;
    // Validate and translate inputs
    XlReadVector(*Prices_op, Prices, L"Prices", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC
    if (DaysPerYear == 0.0)
        DaysPerYear = 250.0;
    try
    {
        xloResult = CalcHistVol(Prices, DaysPerYear);
    }
    catch(const char*)
    {
        xloResult = xlerrNum;
    }
    return xloResult.Ret();
}

However, in some cases, this is not an acceptable solution. It may be that zero is a perfectly legal value, or that zero is not the default value.

Next: Creating optional arguments >>


Creating optional arguments

In the previous section we took advantage of the fact that Excel passes zero for missing numeric arguments. Now we're going to use a more powerful technique for optional arguments: using the Function Wizard to change the argument type.

Change the argument type

Use the Tools/XLL+ Function Wizard menu to launch the Function Wizard. As before, make sure HISTVOL is selected.

In the arguments grid, go to the line containing DaysPerYear, and click on the Details tool-button, shown in red below.

This will bring up the Argument Details dialog. Put a check in the Optional checkbox.

This will enable the Default value groupbox. Enter 250.0 for the default value, as shown above, and click OK to save your changes.

Tip: To bring up the Argument Details dialog, you can also use the Argument/Details menu, or press Alt+Enter, or right-click the argument and use the context menu.

After you change the argument type, the Function Wizard should look like this:

Note that the Type column is now a little more interesting, and summarises everything the wizard knows about the argument thus: Double (=250.0)

Click on the OK button to dismiss the Wizard and update the source code.

Next: Reading an optional argument >>


Reading an optional argument

The source code has now been modified.

CopyC++
CXlOper* HISTVOL_Impl(CXlOper& xloResult, const CXlOper* Prices_op, const
    CXlOper* DaysPerYear_op)
{
    // Input buffers
    std::vector<double> Prices;
    double DaysPerYear;
    // Validate and translate inputs
    XlReadVector(*Prices_op, Prices, L"Prices", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK);
    XlReadScalar(*DaysPerYear_op, DaysPerYear, L"DaysPerYear",
    XLA_DEFAULT_EMPTY, 250.0);
    // End of generated code
//}}XLP_SRC
    try
    {
        xloResult = CalcHistVol(Prices, DaysPerYear);
    }
    catch(const char*)
    {
        xloResult = xlerrNum;
    }
    return xloResult.Ret();
}
  1. The argument type DaysPerYear has changed type (to const CXlOper*) and name (to DaysPerYear_op).
  2. A new local variable double DaysPerYear, has been declared.
  3. Some lines have been generated to populate DaysPerYear from DaysPerYear_op.

All the work is done by XlReadScalar, using the value (250.0) that we specified in the Function Wizard.

  • If the input DaysPerYear_op contains a numeric value, then it will be converted to a double and put into the local variable DaysPerYear.
  • If the input is empty or missing, then the default value (250.0) will be applied to DaysPerYear.
  • If the input is present, and the value cannot be converted to a double, then an exception of type CXlRuntimeException will be thrown, and the function will exit immediately. The exception will contain a message such as "Expected number for DaysPerYear".

There is no need to change your code; the Function Wizard's changes will do all the work.

This technique can also be used to read in optional boolean, integer and string values, or for values of any type, including extended types.

Next: More on optional arguments >>


More on optional arguments

You can do more with the optional argument settings.

Blank fields

You may find it useful to use the default value for more than just a missing or empty argument. A common technique in Excel is to use the IF function to populate a cell, e.g.:

=IF(A1=0.0,"",A1)

In this case, the cell will not be empty, but will contain a blank string, which is not the same thing. In the Argument Details dialog, use the checkboxes in the Default value groupbox to adjust how these cells are treated.

Argument grid

You can see more information about optional arguments in the Argument grid if you wish. Use the View/Columns/Optional and View/Columns/Default value menu commands to show or hide columns containing the details of an optional argument.

You can also see a list of available columns if you right-click on the header row of the Argument grid.

Once you change the column setting, you will be able to see and edit details of each argument, as shown below.

Next: The XLL Add-ins ToolWindow >>


XLL Add-ins Window

This chapter contains the following topics:

The XLL Add-ins ToolWindow
Showing the XLL Add-ins Window
Other XLL Add-ins Window functionality


The XLL Add-ins ToolWindow

Introducing the XLL Add-ins Window

The XLL Add-ins Window is a ToolWindow that lives inside the Visual Studio workspace, usually on the same tab as the Solution Explorer window. It shows you all the XLL Add-in functions in the current source file. You don't need to pop up the XLL+ Function Wizard to see or edit your functions.

The picture below shows the current contents of tutorial1.cpp at this point in the tutorial. If you select one of the functions in the top half of the window, its arguments will be listed in the lower half.

Viewing and editing in the Properties window

If you select a function or an argument in the Add-ins window, you can see all its details in the Visual Studio Properties window.

Hint: If you can't see the Properties window at the moment, select a function or argument in the Add-ins window and press ALT+Enter.

As you can see in the picture below, you can use the Properties window to view and to edit the properties of an add-in function directly.

If you select an argument in the Add-ins window, then you can use the Properties window to directly edit the argument.

Navigating with the Add-ins window

The Add-ins window is a useful guide to the contents of your source file. The code generated for each add-in function is quite large, and that can make it hard to find the code you need to work with. The Add-ins window will take you directly to the right part of the function you wish to edit.

Either use the Go to function tool located in the window's toolbar, or click the function with the right mouse and use the context menu.

Next: Showing the XLL Add-ins Window >>


Showing the XLL Add-ins Window

Showing the XLL Add-ins window

In Visual Studio, if the XLL Add-ins window is not visible, you can use the View/Other Windows/XLL Add-ins menu to show it.

Positioning the Add-ins window

By default, the Add-ins window will appear on the same tab as the Solution Explorer. This is usually the most convenient place to keep it. It is a good idea it not share a tab with the Properties window, since the Add-ins Window and the Visual Studio Properties window work together closely.

A typical layout for the Add-ins window and the Properties window is shown below.

Next: Other XLL Add-ins Window functionality >>


Other XLL Add-ins Window functionality

Editing multiple functions

You can select multiple functions in the XLL Add-ins window and edit them in the Properties window at the same time. So, for example, if you wanted to change the Category of all of the add-in functions in a file, you would select them all in the Add-ins window and set the Category property in the Properties window.

Other tools

Some of the tools available in the XLL Add-ins window are listed below.

New function | Create a new add-in function
Design | Edit an add-in function in the XLL+ Function Wizard
Go to function | Go to the writable portion of the selected add-in function.
Preview Formula Wizard | Show a preview of how your function will appear in the Excel Formula Wizard.
New macro | Create a new macro function
Generate Help | Generates a help file (in CHM format) which will appear in Excel if the user requests "Help on this function".
Upgrade Project to XLL+ 6 | Upgrades the project file and all existing add-in functions from XLL+ 5 or below to the new format of XLL+ version 6.
XLL+ Options | Shows the Options Page for XLL+, which lets you change various system settings for all XLL+ projects.

Use the Design tool to show a function in the XLL+ Function Wizard. Alternatively, you can just double-click the function in the list.

You can use the New Function tool to add a new function.

You can use the New Macro tool to add a new macro function.

Next: Matrix arguments >>


Two-dimensional arguments

This chapter contains the following topics:

Matrix arguments
Two-dimensional linear interpolation function
Copy/Paste with arguments
Creating a matrix argument
Using matrix data
Constraining array sizes


Matrix arguments

Passing 2-dimensional arrays to C/C++ functions

This topic shows you how to read 2-dimensional arrays from Excel, and pass them on to C/C++ functions.

There is no standard way to pass 2-dimensional data to a C/C++ function. With 1-dimensional data (vectors) it is simple: pass a pointer to the array, and the size of the array. (Or, in STL conventions, pass iterators for the start and end of the array.)

To pass a matrix to a C/C++ function, there are several options. You may be expected to keep all the data in a single continuous block, or you may be expected to pass an array of pointers, each of which points to an array. In addition, the data may be arranged row-wise or column-wise.

The imtx<T> template class

Since there is no STL container for 2-dimensional data, the class library contains the imtx<T> interface and related template classes.

Note: Unlike the other classes in the library, it follows STL conventions, using lower case and underscores. The other classes in the library all follow Microsoft C++ conventions (mixed case, class names preceded by 'C', member variables prefixed by 'm_' and their type).

The imtx classes handle all the data storage issues referred to above, and cooperate with the STL vector class to help you pass data to C/C++ functions easily.

Other matrix classes

Any other matrix class can be handled by providing an adapter class. Examples are provided for the boost::multi_array class and for the deprecated xlp::matrix<T> class. For details of adapter classes, see Adapter classes for imtx<T>.

The matrix<T> template class

The matrix<T> class was provided as standard in early versions of XLL+. This class is now deprecated and has been replaced by the imtx<T> classes. Any code that uses the class will continue to work, because of the adapter class provided.

Next: Two-dimensional linear interpolation function >>


Two-dimensional linear interpolation function

The function LinearInterp2D() implements linear interpolation on a two-dimensional surface.

LinearInterp2D()'s matrix argument aadZ is passed as an array of pointers to one-dimensional arrays of doubles. Each of these arrays of doubles represents one column of data. LinearInterp2D() returns 1 if it succeeds, 0 if it fails.

Add the code to the end of Tutorial1.cpp.

CopyC++
static int FindInterpPoints(int cPoints, double* adValues, double dInterp, int* cc);

// Interpolate in a 2 dimensional array
// Returns 1 for success, 0 for failure
int LinearInterp2D(int cX, double* adX, int cY, double *adY, double** aadZ,
                   double dXInterp, double dYInterp, double* pdZInterp)
{
    int ccX[2], ccY[2], i;
    double adZInterpX[2];

    // Find the right poionts to use for interpolation
    if (!FindInterpPoints(cX, adX, dXInterp, ccX))
        return 0;
    if (!FindInterpPoints(cY, adY, dYInterp, ccY))
        return 0;

    // Interpolate in the X dimension
    for (i = 0; i < 2; i++) {
        if (ccX[0] == ccX[1])
            adZInterpX[i] = aadZ[ccY[i]][ccX[0]];
        else
            adZInterpX[i] = aadZ[ccY[i]][ccX[0]]
                          + ( ( aadZ[ccY[i]][ccX[1]] - aadZ[ccY[i]][ccX[0]] )
                            * ( dXInterp - adX[ccX[0]] )
                            / ( adX[ccX[1]] - adX[ccX[0]] ) );
    }

    // Interpolate in the Y dimension
    if (ccY[0] == ccY[1])
        *pdZInterp = adZInterpX[0];
    else
        *pdZInterp = adZInterpX[0]
                   + ( ( adZInterpX[1] - adZInterpX[0] )
                     * ( dYInterp - adY[ccY[0]] )
                     / ( adY[ccY[1]] - adY[ccY[0]] ) );
    return 1;
}

// Locate the interpolation points in an ordered unique array
// Puts the coordinates of the two points in cc[]
// Returns 1 for success, 0 for failure
static int FindInterpPoints(int cPoints, double* adValues, double dInterp, int* cc)
{
    int i;

    // Too few points
    if (cPoints < 1)
        return 0;
    // Only one point
    if (cPoints == 1) {
        cc[0] = cc[1] = 0;
        return 1;
    }
    // Only two points
    if (cPoints == 2) {
        cc[0] = 0;
        cc[1] = 1;
        return 1;
    }
    // Find position of dInterp in adValues[]
    for (i = 0; i < cPoints; i++) {
        // Check that adValues[] is strongly ordered
        if (i > 0 && adValues[i] <= adValues[i - 1])
            return 0;
        // Look for an exact match
        if (dInterp == adValues[i]) {
            cc[0] = cc[1] = i;
            return 1;
        }
        // Find upper bound
        if (dInterp < adValues[i]) {
            // Extrapolate left
            if (i == 0) {
                cc[0] = 0;
                cc[1] = 1;
            }
            // Interpolate
            else {
                cc[0] = i - 1;
                cc[1] = i;
            }
            return 1;
        }
    }
    // Extrapolate right
    cc[0] = cPoints - 2;
    cc[1] = cPoints - 1;
    return 1;
}

Next: Copy/Paste with arguments >>


Copy/Paste with arguments

Create the function

Use the New XLL+ Function tool to create a new function. Set the function's properties as follows:

Name: INTERP2D
Return type: CXlOper
Category: Statistical
Description: Interpolate in a two-dimensional array

Add an argument as follows. (Hint: You can use Ctrl+1 to set an argument to be a vector, instead of using the vector tool-button.)

Type: Double[]
Name: X
Description: Ordered vector of X values

Copy the argument

The next argument is very similar, so now is a good time to use the clipboard to copy an argument, and save yourself some typing. Make sure the active cell in the arguments grid is in the row containing X. Click on the Copy Argument tool.

Now we have a copy of the argument in the system clipboard. Next, use the Paste Argument tool to insert a copy of the argument.

This will insert a new argument, X2, after X. You'll need to change the name, and make a slight change to the description.

Edit the argument so that the columns are as follows:

Type: Double[]
Name: Y
Description: Ordered vector of Y values

Next: Creating a matrix argument >>


Creating a matrix argument

Now we are going to use the Function Wizard to create a function with a matrix argument.

Add a matrix argument

Add a new argument Z and use the matrix tool to change it to a 2-dimensional argument. (Alternatively, you can use Ctrl+2 as a short-cut.)

Fill in the fields of Z as follows:

Type: Double[][]
Name: Z
Description: Matrix of Z values

Add the rest of the arguments

Add the remaining arguments, as shown below. You may find it convenient to use the copy and paste argument commands to enter InterpY.

Type: Double
Name: InterpX
Description: X value at interpolation point
Type: Double
Name: InterpY
Description: Y value at interpolation point

When you've finished, the Function Wizard should look like this:

Click on the OK button to dismiss the Wizard and update the source code.

Next: Using matrix data >>


Using matrix data

Code generated by the wizard

Whens you return to Visual Studio, you will see that the wizard has inserted the source code for the new function at the end of your C++ file. The interesting part is shown below.

CopyC++
CXlOper* INTERP2D_Impl(CXlOper& xloResult, const CXlOper* X_op, const CXlOper*
    Y_op, const CXlOper* Z_op, double InterpX, double InterpY)
{
    // Input buffers
    std::vector<double> X;
    std::vector<double> Y;
    ple::mtx_ptrs<double> Z;
    // Validate and translate inputs
    XlReadVector(*X_op, X, L"X", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK);
    XlReadVector(*Y_op, Y, L"Y", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK);
    XlReadMatrix(*Z_op, mtx_adapter(Z), L"Z", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC
    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    return xloResult.Ret();
}

Most of this code is pretty familiar stuff. Let's examine the new code for handling the matrix.

CopyC++
ple::mtx_ptrs<double> Z;
XlReadMatrix(*Z_op, mtx_adapter(Z), L"Z", XLA_TRUNC_ONEMPTY|
    XLA_TRUNC_ONBLANK);

As you may remember, our implementation function, LinearInterp2D(), expects the matrix argument to be passed as an array of pointers to one-dimensional arrays of doubles, where each of the arrays of doubles represents one column of data.

The wizard has generated code that does a number of useful things:

  1. Declares a matrix variable, Z, which will hold the data extracted from the COper. For reasons of efficiency, the matrix is of type mtx_ptrs<T>.
  2. Calls the XlReadMatrix() method, which extracts the values from the CXlOper Z_op, and populates Z. If any of the data in Z is unacceptable, XlReadMatrix() throws an exception.

So, at the end of the Wizard-generated code, we have exactly what we need to call LinearInterp2D():

  • A storage mechanism, Z, for the numeric data passed in the argument Z_op. (This data will automatically be cleaned up at the end of the function, when Z goes out of scope, so we don't have to worry about freeing or deleting it.)
  • X and Y, storage mechanisms (with automatic cleanup) for the adX and adY arguments of LinearInterp2D().

Add your own code

The code we add to the wizard-generated skeleton needs to do two things:

  1. Call LinearInterp2D().
  2. Return either an error code or the calculated result.

Generally, this is all an add-in function does. Most of the time, most of the code is generated by the wizard.

Add the code shown below, which calls LinearInterp2D().

CopyC++
CXlOper* INTERP2D_Impl(CXlOper& xloResult, const CXlOper* X_op, const CXlOper*
    Y_op, const CXlOper* Z_op, double InterpX, double InterpY)
{
    ...
//}}XLP_SRC

    double dInterpZ;
    if (LinearInterp2D((int)X.size(), &X[0], (int)Y.size(), &Y[0], &Z[0],
                       InterpX, InterpY, &dInterpZ))
        xloResult = dInterpZ;
    else
        xloResult = xlerrNum;

    return xloResult.Ret();
}

Next: Constraining array sizes >>


Constraining array sizes

Constraining the size of an argument

The function is now almost complete, and ready for building and testing.

It needs one more piece of work: we need to constrain the size of the matrix Z to be the same width as X and the same height as Y. Our core function, LinearInterp2D() assumes that these constraints have been satisfied.

Launch the Argument Editor for Z. There are several ways to do this:

  1. In the XLL+ ToolWindow, select INTERP2D in the upper half of the window, and double-click on Z in the lower half.
  2. Launch the XLL+ Function Wizard to edit INTERP2D, and select Z. Then click on the Details tool just above the argument grid.
  3. Alternatively, in the XLL+ Function Wizard, select Z and press ALT+Enter.

In the Argument Editor, select the Matrix tab:

In the Constraints group box, use the "Height is equal to" and "Width is equal to" combo-boxes to set the constraints:

Bounding variables

The result of these changes will be to create two new bounding variables, sizeOfX and sizeOfY. These will be set to the sizes of X and Y respectively when X and Y are evaluated. They they will then be checked against the height and width of Z respectively.

CopyC++
// Named bounds
long sizeOfX = -1;
long sizeOfY = -1;
// Validate and translate inputs
XlReadVector(*X_op, X, L"X", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK, &sizeOfX);
XlReadVector(*Y_op, Y, L"Y", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK, &sizeOfY);
XlReadMatrix(*Z_op, mtx_adapter(Z), L"Z", XLA_TRUNC_ONEMPTY|
    XLA_TRUNC_ONBLANK, &sizeOfY, 0, &sizeOfX);

If either constraint fails, then an exception will be thrown, and an appropriate message will be returned to Excel, e.g.: Expected 5 rows for Z.

Displaying the constraints

You can see the constraints displayed in the Function Wizard:

They will also show up in the Properties window when you select X, Y or Z in the ToolWindow:

Validation errors

Build and run the add-in.

Try out the validation code. If you are using English as your language, you can get errors such as the following:

#ERROR: Expected 3 columns in Z
#ERROR: Expected 3 rows in Z
#ERROR: Expected number for Z[1,4]

Next: Matrix containers >>


Other matrix types

This chapter contains the following topics:

Matrix containers
Flat layout
Handling Excel coordinates


Matrix containers

The matrix argument of LinearInterp2D() was required to be an array of pointers to columns. It could have been different; it might have required:

  • An array of pointers to rows.
  • A continuous array of values, arranged with columns together.
  • A continuous array of values, arranged with rows together.
  • An instance of an existing matrix class, such as boost::multi_array.

If you need to, you can read the Excel input directly into any of these forms.

Specifying a different container

In the Matrix tab of the Argument Editor, you can use the Container drop-down to select a different container.

For example, if your core C/C++ expects a continuous single array of values, you can use the ple::mtx_flat<T> class. This class arranges its contents in a single array, so you can pass it directly to a function that expects data arranged in this way.

Or if you have a function that expects an existing matrix class, you can type the name into the Container field.

Specifying storage order

By default, matrices are stored with column as the inner dimension, so that an item can be addressed as X[row][column]. You can change this with the Layout combo on the Matrix tab of the Argument Editor.

Next: Flat layout >>


Flat layout

Matrix argument laid out as a continous array of values

To demonstrate the use of a different matrix layout, we are going to add a function which returns the location of the maximum value within a two-dimensional array. Add the simple function shown below to the end of Tutorial1.cpp:

CopyC++
#include <algorithm>

// Find location of maximum value in adValues
// adValues must be a continuous array, with columns held together
int FindMax(int cCols, int cRows, const double *adValues, int* pnMaxCol,
            int* pnMaxRow)
{
    const double* pdEnd = adValues + (cRows * cCols);
    // Use STL algorithm to find offset of max value
    const double* pdMax = std::max_element(adValues, pdEnd);
    if (pdMax == pdEnd)
        return 0;
    // Translate offset to coords
    *pnMaxRow = (int)((pdMax - adValues) % cRows);
    *pnMaxCol = (int)((pdMax - adValues) / cRows);
    return 1;
}

As you can see, this function takes advantage of the STL max_element algorithm to do all the hard work. The important things to note, as far as our add-in function is concerned, are:

  • the algorithm expects data to be in a continous array of values;
  • we have (arbitrarily) decided that they should be stored with columns held together.

Next, we'll use the XLL+ Function Wizard to apply these layout rules.

Create the function

Using the Function Wizard, add a new function, with properties as shown below:

Name: MAXCOORD
Return type: CXlOper
Category: Statistical
Description: Get the x or y coordinate of the maximum value in an array

Add a Matrix argument

Add the array argument, as follows:

Type: Double[][]
Name: Array
Description: 2-dimensional array of numbers

Set the Matrix layout

Open the Argument Editor for Array, and switch to the Matrix tab.

Set the following fields:

Container: ple::mtx_flat<T>
Layout: Store as [column, row]

Defend against empty arrays

The code in the add-in function may blow up if the array is empty, so defend against this by setting the "Reject empty matrix" flag:

Reject empty matrix: true

If the user enters an empty array, then an exception will be thrown by the validation code, and an error message such as "#ERROR: Expected at least one cell for Array" will be returned. If there is any code that assumes Array to be non-empty, e.g:

CopyC++
CallFunction(&Array[0]);

or

CopyC++
CallFunction(Array.begin());

it will not be called, because the function has already ended.

Click OK to close the Argument Editor.

Add a Boolean argument

In the Function Wizard add a new argument, XCoord, with fields as follows:

Name: XCoord
Type: Boolean
Dimensions: Scalar
Description: True for the x coordinate (column number), false for y (row number)

Note that XCoord is a Boolean argument (i.e. True or False). It will be passed to our add-in function as type BOOL (int), with values TRUE (1) or FALSE (0).

Click on OK to return to Visual Studio and complete the code.

Next: Handling Excel coordinates >>


Handling Excel coordinates

When you return to Visual Studio, code will have been added to Tutorial.cpp.

CopyC++
CXlOper* MAXCOORD_Impl(CXlOper& xloResult, const CXlOper* Array_op, BOOL XCoord)
{
    // Input buffers
    ple::mtx_flat<double> Array;
    // Validate and translate inputs
    XlReadMatrix(*Array_op, mtx_adapter(Array), L"Array", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK|XLA_FLAG_TRANSPOSE);
    // End of generated code
//}}XLP_SRC
    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    return xloResult.Ret();
}

The matrix-reading code differs from that in INTERP2D in two ways:

  1. The matrix used is of type mtx_flat<T>.
  2. The flags argument to XlReadMatrix includes the bit XLA_FLAG_TRANSPOSE.

After XlReadMatrix() has run successfully, the data we need will be in Array, as a continous array of doubles, arranged with columns together, which is what we wanted for our implementation function, FindMax().

Add the code below, to call FindMax():

CopyC++
CXlOper* MAXCOORD_Impl(CXlOper& xloResult, const CXlOper* Array_op, BOOL XCoord)
{
    ...
    // End of generated code
//}}XLP_SRC

    // Note that the "Reject Empty Matrix" flag has been set for Array.
    // We can therefore safely use Array[0] or Array.begin() in the
    // code below.

    int nMaxCol, nMaxRow;
    // Since we have transposed the matrix, by specifying that columns
    // be held together, Array has columns as the outer axis (i.e.
    // size(0)) and rows as the inner axis (i.e. size(1)).
    if (FindMax((int)Array.size(0), (int)Array.size(1),
                &Array[0], // or, if you prefer, Array.begin(),
                &nMaxCol, &nMaxRow))
    {
        int nCoord = XCoord ? nMaxCol : nMaxRow;
        // Add 1 to the coordinate because Excel's coordinates are
        // 1-based while C's are zero-based
        nCoord++;
        // Return a numeric value
        xloResult = (double)nCoord;
    }
    else
        xloResult = xlerrNum;

    return xloResult.Ret();
}

Notice that we add one to any coordinate's representation in Excel because Excel indices are by convention one-based, whereas C indices (being address offsets) are zero-based.

For full details on reading matrix arguments, see XlReadMatrix() in the class reference.

Next: Returning vectors to Excel >>


Array results

This chapter contains the following topics:

Returning vectors to Excel
Array formulae in Excel
Returning matrices to Excel
Arrays of mixed type


Returning vectors to Excel

This topic shows you how to return a 1-dimensional array to Excel. The example is a very simple function for sorting numeric arrays in ascending order.

Use the Function Wizard to create a new function with these properties:

Name: SORTVECTOR
Return type: CXlOper
Category: Lookup & Reference
Description: Sort a vector of numbers in ascending order

Add a single vector argument with the following properties:

Type: Double[]
Name: Vector
Description: Unsorted vector of numbers

Press OK to return to Visual Studio.

Add code so that your add-in function looks like this:

CopyC++
CXlOper* SORTVECTOR_Impl(CXlOper& xloResult, const CXlOper* Vector_op)
{
    // Input buffers
    std::vector<double> Vector;
    // Validate and translate inputs
    XlReadVector(*Vector_op, Vector, L"Vector", XLA_TRUNC_ONEMPTY|
        XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC

    // Use STL algorithm to sort input
    std::sort(Vector.begin(), Vector.end());
    // Copy the sorted vector to xloResult
    xloResult = Vector;

    return xloResult.Ret();
}

Yet another overload of the CXlOper assignment operator is used to copy the STL vector into xloResult:

CopyC++
xloResult = Vector;
The operator creates an array of values within xloResult and populates it with the values in Vector.

This is one of the most pleasingly simple add-in functions in this tutorial. It is not necessarily very useful - a better implementation would sort a 2-dimensional array by a given column or columns, in ascending and descending order - but it is very short, and does a surprising amount of work with only two lines of hand-written code.

Next: Array formulae in Excel >>


Array formulae in Excel

To make use of the SORTVECTOR function, you need to know how to enter array formulae in Excel. If you are already familiar with Excel array formulae, please skip to the next section.

To enter an array formula in Excel, follow these steps:

  1. Select the cells which will jointly contain the array formula.
  2. Type in the cells' formula.
  3. Press Ctrl+Shift+Enter - i.e. hit the Enter key, while holding down the Control and Shift keys.

You can recognize an array formula, because it is shown in Excel surrounded by curly braces {...}.

Note: You do not have to type in the curly braces. Excel adds these for you, if you use Ctrl+Shift+Enter to signify an array formula.

The example below shows the SORTVECTOR function in use in an array formula.

Next: Returning matrices to Excel >>


Returning matrices to Excel

Returning a matrix to Excel is very similar to returning a vector. Add the following stand-alone matrix function to Tutorial1.cpp.

Note: This is a very silly add-in function. Transformations of this kind are far easier to do in Excel itself, especially if you use a mixture of relative and absolute addresses. But it makes a reasonably good example function.
CopyC++
// Multiplication of two vectors to produce a matrix
// aadZ should be an array of cX pointers to columns
void MatrixMultiply(int cX, double* adX, int cY, double* adY, double** aadZ)
{
    int i, j;
    for (i = 0; i < cX; i++) {
        for (j = 0; j < cY; j++) {
            aadZ[i][j] = adX[i] * adY[j];
        }
    }
}

Note that argument aadZ is an array of pointers to columns, and can be addressed as aadZ[column][row].

Use the Function Wizard to create a new function MATRIXMULT:

Name: MATRIXMULT
Return type: CXlOper
Category: Math & Trig
Description: Matrix multiply two vectors

Add two vector arguments, as follows:

Type: Double[]
Name: X
Description: First vector of numbers
Type: Double[]
Name: Y
Description: Second vector of numbers

Modify the generated code so that it looks like this:

CopyC++
CXlOper* MATRIXMULT_Impl(CXlOper& xloResult, const CXlOper* X_op, const CXlOper*
    Y_op)
{
    // Input buffers
    std::vector<double> X;
    std::vector<double> Y;
    // Validate and translate inputs
    XlReadVector(*X_op, X, L"X", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK);
    XlReadVector(*Y_op, Y, L"Y", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC

    // Allocate a matrix with initial size: rows = Y.xsize() and cols = X.size()
    ple::mtx_ptrs<double> matResult(Y.size(), X.size());

    // Pass the input and output arrays to the stand-alone function
    MatrixMultiply((int)Y.size(), &Y[0], (int)X.size(), &X[0], &matResult[0]);
    // If you prefer STL notation, use the following
    //MatrixMultiply(Y.size(), Y.begin(), X.size(), X.begin(), matResult.begin());

    // Populate xloResult with the resulting matrix
    xloResult = matResult;

    return xloResult.Ret();
}

Here we've made use of the mtx_ptrs class to manage the output array. The matrix constructor allocates an appropriate number of rows and columns, which are initially filled with zeroes. Then we use either a pointer to the first array in the matrix (&matResult[0]) or the STL-style matResult.begin() function to get an array of column pointers, as required by MatrixMultiply().

Populating xloResult with the result of MatrixMultiply() is very simple: we use another CXlOper overloaded assignment operator to allocate the output data and to copy in the contents of matResult.

CopyC++
xloResult = matResult;

Returning other matrix types

If you need to return a matrix of another type to Excel, just use an adapter class, so that CXlOper::operator= treats it as a ple::imtx container.

For example, to return a boost matrix to Excel, you might use code such as:

CopyC++
boost::multi_array<double, 2> m;
// ... Fill contents of m ...
xloResult = mtx_adapter(m);
return xloResult.Ret();

If you only have const access to the matrix you wish to return, use a read-only adapter, e.g.:

CopyC++
const boost::multi_array<double, 2>& ref_to_matrix = call_some_function();
xloResult = mtx_const_adapter(m);
return xloResult.Ret();

See mtx_adapter and mtx_const_adapter for more about matrix adapter classes.

Next: Arrays of mixed type >>


Arrays of mixed type

Sometimes your results will not be in ready-made vector or imtx form, and you'll need to use a different technique to populate xloResult.

CXlOper::FromDoubleArray

The simplest method to use is CXlOper::FromDoubleArray(), to populate the xloResult, using an array of values or of pointers to rows/columns of values.

The various different versions of this method are listed below:

  • FromDoubleArray(double *pd, USHORT cPoints)

    Create a one-column array and populate it with the supplied data points.

  • FromDoubleArray(double *pd, USHORT cRows, USHORT cCols, BOOL bByRows)

    Create a two-dimensional array and populate it with the supplied continuous data array. The bByRows argument will decide whether rows (TRUE) or columns (FALSE) are kept together.

  • FromDoubleArray(double **apd, USHORT cRows, USHORT cCols, BOOL bByRows)

    Create a two-dimensional array and populate it with the supplied data, which consists of an array of column or row pointers, depending on the value of bByRows.

CXlOper::AllocArray

A more complex way to populate an array result is by using CXlOper::AllocArray() to create the array, and then CXlOper::Cell() to populate each cell.

While this method involves more programming, it gives you full control over the output, and allows you to have mixed data types in the array.

Say we want to return a mixed array of names and prices:

CopyC++
const char* names[] = { "ACME", "ULTRA", "CHEESECO" };
double prices[] = { 100.0, 1234.5, 0.0 };

xloResult.AllocArray(3, 2);
for (int i = 0; i < 3; i++)
{
    xloResult.Cell(i, 0) = names[i];
    xloResult.Cell(i, 1) = prices[i];
}
return xloResult.Ret();

The result will look like this:

See the CXlOper::AllocArray() example for another example of this technique.

Next: String arguments >>


Strings

This chapter contains the following topics:

String arguments
Portable string types
Unicode strings


String arguments

String types

Excel versions before Excel 2007 pass strings to add-in functions as ANSI strings of 255 characters or less. Excel 2007 (and above) passes Unicode strings of up to 32767 characters.

A portable XLL add-in must therefore be able to handle either type of string.

CXlStringArg class

An add-in function generated by XLL+ uses two diffrent wrapper functions to handle being called from Excel 2003 and below and being called from Excel 2007 and above.

Each of the wrapper functions creates a portable object, of type CXlStringArg, which contains the string argument's value. The CXlStringArg object is passed to the common implementation function.

CXlStringArg is able to provide a Unicode string or an ANSI string, as the developer prefers.

You can use the CXlStringArg object anywhere that your code needs a const char* or const wchar_t* string pointer. The compiler will cast it as required, and the class will convert the data between ANSI and Unicode as required.

Next: Portable string types >>


Portable string types

Unicode

With version 6, XLL+ now fully supports the (16-bit) Unicode character set as well as the standard (8-bit) ANSI character set. Setting the compiler settings appropriately will cause the compiler to use the Unicode or the ANSI versions of functions and classes.

See the Application Wizard help for information on these settings.

Portable types

Wherever possible, the XLL+ libraries and headers use portable string types, which will be of the preferred size depending on the build settings.

The table below lists the portable types used in the XLL+ run-time libraries and headers, along with their meaning under each type of build.

Portable type | Standard build | Unicode build
TCHAR | char | wchar_t
std::tstring | std::string | std::wstring
CString | CStringA | CStringW
LPCTSTR | LPCSTR | LPCWSTR
LPTSTR | LPSTR | LPWSTR
_T("text") | "text" | L"text"

Next: Unicode strings >>


Unicode strings

The XLL+ run-time classes use three types of string:

  1. Strings that are always ANSI (8-bit).
  2. Strings that are always Unicode (16-bit).
  3. Strings that are portable and may be ANSI or Unicode depending on whether _UNICODE is #defined.

Wide strings

The XLL+ classes use exclusively Unicode (or wide) strings in various places where it is necessary in order to properly support Excel 2007.

Uses of wide strings include:

  • Exported names of functions
  • Error messages
  • Argument names and descriptions under Excel 2007

In these cases, if you try to use standard strings or fail to apply the L prefix to literals you will receive a compiler error.

Next: What are value lists? >>


Value lists

This chapter contains the following topics:

What are value lists?
A value list example
Editing value lists


What are value lists?

Frequently an argument must have a value that is a member of a list; very often such a value range is defined as an enum in C++. It is useful to be able to validate an input of this kind before it is used. An informative error message can be returned, to make it easy for the user to correct the value:

#VALUE! Expected one of 0,1,2,3,4,5,6 for DayCount

You can use the XLL+ Function Wizard to generate code for this validation. In the Argument dialog, for integer types, a Value List appears. You can use the page to create a list of acceptable values.

If you tick the box List is Exclusive, then code will be generated to validate the input DayCount; if the value does not match any of the entries in the Values column, then an exception is raised, and an error message is returned to Excel.

There are other benefits to using a Value List. If you tick the box Show list in Formula Wizard, then a drop-down list will appear in the the Excel Formula Wizard, with the descriptions of each of the acceptable values:

This feature makes it much easier for users to quickly learn to use the add-in function.

Also, the list of values will be included in the on-line Help as a table.

Next: A value list example >>


A value list example

This simple example shows a value list in action.

Use the Function Wizard to create a new function with these properties:

Name: DaysInStandardYear
Return type: CXlOper
Category: Date & Time
Description: Returns the number of days in a year, according to the specified day count convention

Add a single scalar argument with the following properties:

Type: Unsigned short int
Name: DayCount
Description: Day count method

Select DayCount in the Argument grid and press Alt+Enter to see the Argument details. Switch to the "Value List" tab, and enter the values below:

Value | Description
0 | 30/360 US
1 | Actual/Actual
2 | Actual/360
3 | Actual/365
4 | 30/360 European
5 | 30/360 Italian
6 | 30/360 German

Tip: You can save some time by copying the text below, and using the Paste button to insert all the rows into the value list at once.

0	30/360 US
1	Actual/Actual
2	Actual/360
3	Actual/365
4	30/360 European
5	30/360 Italian
6	30/360 German

Set the check-boxes above the value list grid as follows:

List is exclusive: Checked
Show list in Formula Wizard: Checked

Press OK twice to return to Visual Studio.

Have a look at some of the code that has been generated. If the code is not visible, expand the hidden region by clicking on the small plus sign next to the text DaysInStandardYear support code.

Constraint object

An object of type CXlValueListConstraint is declared at global scope. This is initialized with the values you entered in the Value List editor.

CopyC++
unsigned short xlvlc__DaysInStandardYear__DayCount__values[] = { 0, 1, 2, 3, 4,
    5, 6 };
CXlValueListConstraint<unsigned short> xlvlc__DaysInStandardYear__DayCount(
    sizeof(xlvlc__DaysInStandardYear__DayCount__values)/sizeof(unsigned short),
    xlvlc__DaysInStandardYear__DayCount__values);

Code is generated within the add-in function to use this constraint object to validate the value of the DayCount input:

CopyC++
CXlOper* DaysInStandardYear_Impl(CXlOper& xloResult, unsigned short int DayCount)
{
    // Validate and translate inputs
    xlvlc__DaysInStandardYear__DayCount.Validate(DayCount, _T("DayCount"));
    // End of generated code
//}}XLP_SRC
    ...
}

If the Validate method fails to match input value against any of the values in the constraint, a exception is thrwon, and an error message is returned to Excel.

Drop-down list in Formula Wizard

The code below creates a drop-down list in the Excel Formula Wizard.

CopyC++
CXlWizExUIArgumentListCreator xweuialc__DaysInStandardYear__0(
    L"DaysInStandardYear", 0, L"0,30/360 US;1,Actual/Actual;2,Actual/360;"
    L"3,Actual/365;4,30/360 European;5,30/360 Italian;6,30/360 German", L',', L';');

See Extending the Excel Formula Wizard for more about the extended user interface.

Complete the code

Add code so that your add-in function looks like this:

CopyC++
CXlOper* DaysInStandardYear_Impl(CXlOper& xloResult, unsigned short int DayCount)
{
    // Validate and translate inputs
    xlvlc__DaysInStandardYear__DayCount.Validate(DayCount, _T("DayCount"));
    // End of generated code
//}}XLP_SRC
    static double adDays[] = { 360.0, 365.25, 360.0, 365.0, 360.0, 360.0, 360.0 };
    xloResult = adDays[DayCount];
    return xloResult.Ret();
}

Note that no further validation of DayCount is required before using it as an index into the array adDays. If the code has passed the Validate method of the constraint object, then we know that the value is safe to use.

Test the function

If you build and open the add-in, you will see that an error message is returned if an unacceptable value for DayCount is entered.

If you open the function in the Excel Formula Wizard, you will find a drop-down box in the DayCount field, which you can use to conveniently select a valid value.

Next: Editing value lists >>


Editing value lists

Creating a value list can take a bit of work, so it's worth noting a couple of ways to make it easier.

Copy/Paste

Use the Copy All button to copy the whole list into Excel and edit it there. Use the Paste button to populate the whole list from an Excel range.

Favorites

Once you've done the work of setting up an argument with a value list, use the Add to favorites command. Then you can add it to other functions in one step, by using the Favorites command.

Showing the Value List column

You can show the value list in the argument grid. Use the View/Columns/Value List menu command to show or hide columns containing the details of an optional argument.

Alternatively, you can also see a list of available columns if you right-click on the header row of the Argument grid.

Once you change the column setting, you will be able to see and edit details of each argument, as shown below.

You can edit the value list directly in the cell, using a comma to separate value/description pairs, and using a semi-colon to separate each pair, e.g.:

0,30/360 US;1,Actual/Actual;2,Actual/360;etc

You can also click the "..." button to pop up an editor window:

Next: Returning integer values >>


Returning integer values

If you want to return an integer value to Excel using a CXlOper, you must first cast it to a double. If you do not, it will be treated as a boolean value.

Within Excel cells, all numeric values are stored as double (i.e. double-precision floating-point number), and the assignment operators for CXlOper reflect this.

Thus, the code below will return the value of result to Excel as a floating-point number.

CopyC++
CXlOper* INTFN_Impl(CXlOper& xloResult, ...)
{
    CXlOper xloResult;
//}}XLP_SRC

    long result = CalculateAnInteger(...);
    xloResult = (double)result;
    return xloResult.Ret(); // Numeric value
}

Without the cast, the code below will return a boolean value, FALSE if result is zero, TRUE otherwise.

CopyC++
CXlOper* INTFN_Impl(CXlOper& xloResult, ...)
{
    CXlOper xloResult;
//}}XLP_SRC

    long result = CalculateAnInteger(...);
    xloResult = result;
    return xloResult.Ret(); // Boolean value - TRUE if result != 0
}

Design note: Although it is possible for a CXlOper to hold an integer value, this type of CXlOper is only used for arguments passed to the Excel API, in order to call Excel built-in functions or macros. A more common use for CXlOper in add-in functions is to store boolean results. Therefore the integer version of the CXlOper assignment operator was originally reserved for boolean, rather than for integer values. This design decision followed from the absence of the keyword bool from early versions of Microsoft's C++ compiler. In order not to break existing code, this decision has not been changed since.

Next: Upgrading from a previous version of XLL+ >>


Upgrading from a previous version of XLL+

Note: The following topics address the issues that arise when upgrading projects built with earlier versions of XLL+. Click here to skip this section.

Older projects

Version 7 of XLL+ contains some significant changes to its internal architecture. In order to support the new features of Excel 2010, a number of changes needed to be made.

If you built an add-in using an older version of XLL+, then it will not compile or link successfully using the XLL+ 7 headers and libraries. However, if you run the XLL+ Upgrade Wizard against your project all the necessary changes will be made to your project to allow it to be built with XLL+ 7.

Upgrade Wizard

There are three steps to upgrading a project built with an older version of XLL+.

  1. Open the project or solution in Visual Studio, and, if the project is under source control, check out the project file and source files.

  2. In the XLL Add-ins window, click on the Upgrade Project to XLL+ 7... command, located on the Tools menu.

  3. Check the upgrade report, and rebuild the project.

Running the Upgrade Wizard is simple. Just click Yes on the confirmation dialog.

When the Wizard has finished running it will open a browser window to display the XLL Plus Upgrade Wizard Report. Examine this to see if any errors were reported.

If all went well, your project is now ready to be rebuilt and run. Your existing add-in functions can take advantage of all the new features of XLL+ 7 and of Excel 2010.

Note: Running the Upgrade Wizard a second time on a project will not harm it. The wizard only changes code and project settings once.

Changes made by the Wizard

The wizard makes changes to the project settings and to the source files that contain XLL+ add-in functions.

A backup directory is created below the project directory, and copies of all changed files are stored there. By copying these files back to the project directory, you can reverse all changes made the Upgrade Wizard.

Project Settings

The following changes are made, if necessary, to the project settings:

Tool | Setting | Change
General | Platform | 64-bit builds are added to the solution and to the project.
C/C++ | Additional Include Directories | The directory containing the XLL+ 7 header files is added, at the start of the list. If a directory containing the XLL+ 6 header files is found, it is removed from the list.
C/C++ | Enable C++ Exceptions | Set to "Yes With SEH Exceptions (/EHa)".
Linker | Additional Library Directories | The directory containing the XLL+ 7 library files is added, at the start of the list. If a directory containing the XLL+ 6 library files is found, it is removed from the list.
Linker | Force Symbol References | For 32-bit builds, the symbol _DllMain@12 is added, at the start of the list. For 64-bit builds, the symbol DllMain is added, at the start of the list.
Resources | Additional Include Directories | The directory containing the XLL+ 7 header files is added, at the start of the list. If a directory containing the XLL+ 6 header files is found, it is removed from the list.
Debug | Command | Set to call the Excel executable file (as specified in the DefaultExcelExe setting).
Debug | Command Arguments | Set to "$(TargetPath)", so that Excel immediately opens the project's XLL file.

Add-in functions

The following changes are made, if necessary, to files containing add-in functions:

Location | Change
IMPLEMENT_XLLFN3 | The macro is replaced by IMPLEMENT_XLLFN4. New arguments supporting Excel 2010 are added, and the pszExt12 argument, which contains a full definition of the add-in function's signature and behavior, is regenerated.

Note that your existing code, outside the //}}XLP_SRC delimiters, is completely unchanged. With the exception of the special cases listed under Breaking changes, it will compile and run immediately, with no changes in behavior.

Report

An upgrade report is generated and saved in the backup directory as UpgradeReport.html. The report contains details of all actions performed by the Wizard.

Next: Deployment of XLLs >>


Deployment of XLLs

An XLL may have dependencies on other DLLs: these must be present on the machine where the XLL is running. If you are going to deliver the XLL add-in to another machine, you must ensure that these DLLs are available.

If a required DLL is not found when an XLL is opened, the user will get an error message such as "This file is not in a recognizable format".

Standard dependencies

In most cases, the required DLLS will already be installed on your target machine, since they are part of a standard Windows XP or Windows Vista installation. A list of the dependencies of each of the standard XLL+ builds can be found in the topic Run-time dependencies in the XLL+ Reference.

Note that all dependencies are on standard Microsoft run-time libraries. Standard XLL+ add-ins have no other DLL dependencies.

Determining dependencies

You can determine the dependencies of your XLL by using the Dependency Walker tool, depends.exe. This can be found in the Common7\Tools\Bin sub-folder of your Visual Studio installation.

Use the tool to inspect your compiled XLL file, and you will see a list of the files on which it depends, along with their versions and locations.

Asynchronous functions

An XLL that uses asynchronous functions requires that the RTD server COM module (XllRtdLink.dll) is installed on the target machine. See Requirements for asynchronous functions for details.

Object handles

An XLL that uses RTD object handles requires that the RTD handle server COM module (RtdHandleServer.dll) is installed on the target machine. See Object handles - Requirements and deployment for details.

.NET

If your XLL uses .NET or the Common Language Runtime, please see the technical note .NET requirements, to be sure that your .NET add-ins load into Excel properly.

Next: Using the Excel Formula Wizard >>


Intermediate Features

This chapter contains the following topics:

Excel Formula Wizard
Extending the Excel Formula Wizard
Languages other than English
Help
Exception handling
Macro functions
Global objects and data
The Office Ribbon
Menus and toolbars
Utility classes
MFC
.NET and the Common Language Runtime
Importing .NET Assemblies
Sized result arrays


Excel Formula Wizard

This chapter contains the following topics:

Using the Excel Formula Wizard
Avoiding the Excel Formula Wizard
Automating the code
Previewing the Excel Formula Wizard


Using the Excel Formula Wizard

The Excel Formula Wizard is a very useful tool for entering formulae with many arguments, or when the user is unfamiliar with the formula.

The Excel user can start the Formula Wizard by clicking on the Formula Wizard tool, shown above, or by typing the name of the function into a cell and then pressing Ctrl+A.

The first page of the wizard shows all the available worksheet functions, listed by category.

The second page of the wizard (sometimes also called the Formula Palette) contains fields for each of the function's arguments. Note that the description for the currently selected argument is displayed below the function's description.

Formula Wizard support in XLL+

  • All the descriptions entered in the XLL+ Function Wizard will appear in the Excel Formula Wizard.
  • You can stop the Formula Wizard from calculating if your function is slow.
  • You can preview how the Formula Wizard will look by using the Formula Wizard Preview tool.
  • You can support multiple languages, so that the descriptions of the funxction and of its arguments will appear in the language of the user. (See International support for details of supporting multiple languages.)
  • You can show a help page about the function, if the user clicks on Help on this function. XLL+ will generate the help file in CHM format, and will include your amendments and insertions. See Help for details.

Next: Avoiding the Excel Formula Wizard >>


Avoiding the Excel Formula Wizard

From the developer's point of view, the most dangerous aspect of the Formula Wizard is the preview result that appears in the palette, as shown below.

If you have a function that takes a long time to calculate, you may want to avoid calculating it for the preview in the Formula Wizard. It will be called every time the user changes an argument field, which is a waste of time until the user has finished filling in all the arguments.

You can use the CXllApp::IsInFormulaWizard() method to find out if the formula is being called from the Formula Wizard.

The example shown below returns #N/A! if the it is being called from the Formula Wizard. This shows up as a blank in the Excel Formula Wizard.

CopyC++
CXlOper* SLOWCALC_Impl(CXlOper& xloResult, double X, double Y)
{
    // End of generated code
//}}XLP_SRC
    if (CXllApp::IsInFormulaWizard())
        xloResult = xlerrNA;
    else
        xloResult = LongSlowFunction(X, Y);
    return xloResult.Ret();
}

Next: Automating the code >>


Automating the code

Using the Function Wizard

An alternative method of implementing the CXllApp::IsInFormulaWizard() method uses the XLL+ Function Wizard.

In the XLL+ Function Wizard, go to the Features tab, and put a check against Do not call in Formula Wizard, as shown below:

This will change your wrapper functions to include code like the following:

CopyC++
extern "C" __declspec(dllexport)
LPXLOPER4 SLOWCALC_4(double X, double Y)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    if (CXllApp::IsInFormulaWizard())
    {
        xloResult = xlerrNA;
        return xloResult.Ret4();
    }
    try {
        xloResult.HandleResult(SLOWCALC_Impl(xloResult, X, Y));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    return xloResult.Ret4();
}

The common function that contains your code, SLOWCALC_Impl(), will never be called. The wrapper function will quit as soon as it discovers that it's being called from the Formula Wizard.

Using the ToolWindow

You can make the same change to your function by using the XLL+ ToolWindow. Select the function to be edited and, in the Properties window, change the value of Do not call in Formula Wizard to True.

Next: Previewing the Excel Formula Wizard >>


Previewing the Excel Formula Wizard

Previewing the Function Wizard

You can use the Preview Formula Wizard tool to see what an add-in function will look like in the Excel Formula Wizard.

The Excel Formula Wizard is quite restrictive about what it will display. Under some circumstances it will display an extra full stop at the end of a description, or it will truncate your text. The preview is very similar to what the user will see in Excel.

To dismiss the preview window, click on the OK or Cancel buttons, or press the Enter or Cancel keys.

Next: Ways to extend the Excel Formula Wizard >>


Extending the Excel Formula Wizard

This chapter contains the following topics:

Ways to extend the Excel Formula Wizard
Drop-down Value Lists
Popup Editors
Advanced Features


Ways to extend the Excel Formula Wizard

Starting in XLL+ version 6.2, add-ins can extend the user interface of the Excel Formula Wizard, to provide a richer and more efficient user experience.

Drop-down lists

A fixed list of values can be provided, and these will be displayed in a drop-down combo-box, along with descriptions of each value.

Popup editors

You can provide a popup editor for an argument. An ellipsis ("...") button will appear in the edit box of the Formula Wizard. When the user clicks it, your popup editor will appear, modally. In the picture below, the popup editor shows a file dialog for a file name argument which should be a file name.

Next: Drop-down Value Lists >>


Drop-down Value Lists

An argument which (i) has a Value List defined and (ii) has the setting Show list in Formula Wizard set will present a drop-down combo box in the Excel Formula Wizard.

The use of drop-down lists in the extended UI is managed by the classes in xlwizexui.h, in particular CXlWizExUIListProvider, and it's helper class CXlWizExUIArgumentListCreator. The XLL+ Function Wizard adds code to create a CXlWizExUIListProvider for each argument that supports a drop-down list.

The topics below contain more details about the use of Value Lists.

Value Lists | Introduction to value lists.
A value list example | A walkthrough showing how to add a value list to an add-in function.
Editing value lists | Tips for working with value lists more effectively.
Dynamic lists | How to change the contents of a value list at run-time.
Changing the keyboard behavior | How to change which keys are assigned to actions in the Formula Wizard.

Next: Popup Editors >>


Popup Editors

An argument which has the setting Show popup in Formula Wizard set will present an ellipsis (...) button in the Excel Formula Wizard.

If the developer provides an object derived from CXlWizExUIPopupProviderBase, then a popup editor will be displayed when the user clicks on the ellipsis button.

CXlWizExUIPopupProviderBase

A class derived from CXlWizExUIPopupProviderBase must provide an implementation of the Edit method, as in the example below.

CopyC++
class CMyPopupProvider : public CXlWizExUIPopupProviderBase
{
public:
    virtual bool Edit(CString& strValue, HWND hwndParent)
    {
        CMyPopupDialog dlg(hwndParent, strValue);
        if (dlg.DoModal() == IDOK)
        {
            strValue = dlg.m_strValue;
            return true;
        }
        return false;
    }
};

The Edit method will be called when the button is pushed. The method should implement the following steps:

  1. Create a dialog and populate it with the current value (strValue).
  2. Display the dialog.
  3. If the user makes a change, update strValue and return true; if the user cancels, return false.

For examples of how to implement a class derived from CXlWizExUIPopupProviderBase, see ExUIPopup sample, ExUIPopupMfc sample and ExUIPopupClr sample.

CXlWizExUIArgumentPopupCreator

Once you have provided a class derived from CXlWizExUIPopupProviderBase, you should use a global instance of CXlWizExUIArgumentPopupCreator to register it.

CopyC++
CXlWizExUIArgumentPopupCreator myPopupCreator(_T("MyFunction"),
    0, new CMyPopupProvider());

The code above attaches an instance of the CMyPopupProvider provider class discussed above to the first argument of the add-in function MyFunction.

Note that you are responsible for constructing the instance of CMyPopupProvider, but the framework is responsible for destroying it. For this reason, if a destructor is provided for your provider class, it must be declared as virtual.

Next: Advanced Features >>


Advanced Features

This topic describes some of the advanced features of the extended user interface.

Changing the keyboard behavior

The default keyboard settings for the extended user interface are summarized below:

 | Drop-down | Popup
Shortcut | Down arrow | Alt+Enter
Behavior | Ignored if the current value is a reference | Always

The developer can change these keyboard settings, by using the XLWIZEXUI_KEYMAPPING structure returned by CXlWizExUIFunctionRegistry::GetKeyMapping(). The code below is called from the OnXllOpenEx() event, and changes the keyboard behavior as follows:

  • The shortcut key for drop-downs is changed to Alt+Down.
  • A drop-down occurs for a keyboard event only if the argument is currently empty.
CopyC++
CXlWizExUIFunctionRegistry* pReg = CXlWizExUIFunctionRegistry::GetInstance();
PXLWIZEXUI_KEYMAPPING pMapping = pReg->GetKeyMapping(XLWIZEXUI_UITYPE_LIST);
pMapping->vk = VK_DOWN;
pMapping->vkModifier = VK_MENU;
pMapping->nBehavior = XLWIZEXUI_KEY_IF_EMPTY;

See CXlWizExUIFunctionRegistry::GetKeyMapping() for more details.

Dynamic lists

You may have lists of values that change over time, particularly lists that are stored in a database.

To change the memebers of a value list at run-time, you need to handle both aspects of a value list's behavior: (i) the drop-down lists in the extended UI and (ii) the input validation provided by the CXlValueListConstraint object.

Changing the items in a drop-down list

You can load a list dynamically by creating a new CXlWizExUIListProvider object, and then calling CXlWizExUIFunctionDescriptor::AddList to register the new list.

CopyC++
// Create a new list provider, and populate it.
CXlWizExUIListProvider* pProvider = new CXlWizExUIListProvider();
for (int i = 0; theList[i].description; i++)
    pProvider->Add(theList[i].value, theList[i].description);

// Get the single instance of the function registry,
// find the affected function,
// and apply the new list provider to the appropriate argument.
CXlWizExUIFunctionRegistry::GetInstance()
    ->FindAddFunctionDescriptor(_T("MyFunction"))
    ->AddList(0, pProvider);

Changing the items in a validation list

You can change the items in a value list used for validation, by calling CXlValueListConstraint::SetValues. Locate the CXlValueListConstraint instance that has been created by the XLL+ Function Wizard, and call SetValue with the new value list.

CopyC++
// Create a list of integer constraint values
std::vector<long> constraintValues;
for (int i = 0; theList[i].description; i++)
    constraintValues.push_back(theList[i].value);

// Apply the new values to the constraint generated by
// the XLL+ Function Wizard
xlvlc__MyFunction__Choice.SetValues(constraintValues.size(),
    &constraintValues[0]);

See the ExUIDynList sample for more details.

Next: Support for languages other than English >>


Languages other than English

This chapter contains the following topics:

Support for languages other than English
Error messages


Support for languages other than English

XLL add-ins built with XLL+ offer support for languages other than English.

Error messages

The error messages returned by XLL+ can be delivered in a selected language, or in the language of the current Excel user. For example, the following error message:

#ERROR: Expected at least 1 value for X

can appear in French:

#ERREUR: Au moins 1 valeur attendue pour X

See Error messages for more information about selecting a language for error messages.

Help files

Help files can be generated in the language of your choice. See Help: Languages other than English for more information.

Categories

The standard function categories of the Excel Formula Wizard, such as "Database", "Information" and "Date & Time" will appear in the language of the user or of the Excel version being used.

Topics

Error messages
Help: Languages other than English
International support

Next: Error messages >>


Error messages

You can choose one of three ways to select the language used for error messages.

  1. Always in English. This is the default behavior of projects generated by the XLL+ AppWizard, and no further action needs to be taken.
  2. Always in a language other than English. You will need to edit the application's resource file to include the message file for your chosen language, instead of the standard English version (xlpres.rc). See Selecting a single language below.
  3. In the language of the user. You will need to edit the application's resource file to include either a list of message files for specific languages or a single message file that includes all available languages. See Selecting multiple languages below.

Message files

Message files are located in the XLL+ include directory, and have names in the form xlpresLLCC, where LL is a language code, e.g. fr for french, and CC is a country code, e.g. fr for France. Thus the message file for French (France) will be xlpresfrfr.rc.

The message file for English (US) is named xlpres.rc, and is used by default in new XLL+ projects.

The message file for your preferred languge may not be available. Visit our web-site at http://www.planatechsolutions.com/xllplus/resources.htm for an up-to-date list of available languages.

If you wish to create your own message file, see the instructions for Creating your own message file below.

Selecting a single language

First, locate the message file for your chosen language.

Next, use Visual Studio to edit the resource file for your application.

  1. Locate the resource file [ProjectName].rc in the "Resource Files" folder in Solution Explorer:

  2. Open the resource file, which will appear in the Resource View:

  3. Select the resource file node, and use the right-mouse menu command "Resource Includes...".

  4. In the Resource Includes window, edit the "Compile-time directives" box to include your chosen message file:

The changes will take effect the next time that you build the project.

Selecting multiple languages

Use Visual Studio to edit your project resource file, following steps 1 to 3 described in "Selecting a single language" above.

For the final step, you can choose to include a specific set of message files, e.g.:

Or you can use the global message file xlpresall.rc to include all available languages:

Creating your own message file

Save a copy of xlpres.rc, with the name for your chosen language and country.

Change the directives shown in bold below to refer to the build setting for your language, by changing to the settings you would find in a newly created resource file for your language, e.g.:

CopyC++
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU)
#ifdef _WIN32
LANGUAGE LANG_GERMAN, SUBLANG_NEUTRAL
#pragma code_page(1252)
#endif //_WIN32

In the STRINGTABLE section, translate the quoted string on each line to your chosen language.

Strings may contain substitution symbols, such as {0} or {1}. These represent sub-strings that will be inserted into the string by the XLL+ run-time libraries. It is essential that all substitution symbols are retained in the translated string, and that no new substitution symbols are added.

A complete list of all messages, along with descriptions of their use and arguments, can be found in the reference guide here.

Next: Generating help >>


Help

This chapter contains the following topics:

Generating help
Help contents
The Help file
Editing the Help file
Adding your own content
Testing the interactive help
Updating the help command line
Languages other than English
Help IDs


Generating help

On-line Help

As part of the build process, XLL+ can produce a compiled help file, in CHM format. This help will appear when the user clicks on "Help on this function" in the Excel Formula Wizard.

The help generator uses the definitions and descriptions of your add-in functions to create the help. You can add your own content to the help topics, and you can override what is displayed in the generated help. All your content is preserved when the help is regenerated.

Requirements

The help generator uses Microsoft HTML Help Compiler 1.4 to build the help file. You can see whether the help compiler has been installed by looking at the XLL+/General options page. In the "Help generator" category, the property HhcExeRealised will show the path to the compiler file HHC.EXE.

The HTML Help Toolkit can be downloaded from Microsoft's web-site at http://msdn2.microsoft.com/en-us/library/ms669985.aspx, using the link "Download Htmlhelp.exe".

Building the Help file

Select the Release configuration, and build the project. (Note: By default, help is generated as part of the Release build, and is not generated under the Debug build.)

As part of the build, the command-line tool BUILDHELP.EXE will be called, which will generate and build all the help files.

Once the generator has finished, it copies the compiled help file (e.g. Tutorial1.chm) to the output directory. This is where the XLL's code expects to find the help file - in the same directory as the XLL file.

The help builder will fail if the Microsoft HTML Help Compiler is not found,with the following error message:

Build help project
Help compiler HHC.EXE was not found
Project : error PRJ0019: A tool returned an error code from "Build help project"

You should either install the HTML Help Compiler or exclude the help files, [ProjectName].help.xml and [ProjectName].chm, from the build.

Building help in the Debug configuration

You can enable the help build in the Debug configuration by selecting the files [ProjectName].help.xml and [ProjectName].chm, and using the right-click menu to view Properties.

Select the page "Configuration Properties/General" and set the "Excluded from build" property to "No".

Next: Help contents >>


Help contents

Inspecting the help file

In the Solution Explorer window, open the generated help file by double-clicking on the file [ProjectName].chm, e.g. Tutorial1.chm, which can be found in the Help Files folder.

The help file contains the following pages:

  • One contents page, listing all the categories of functions contained in the add-in.
  • One category page for each category of function, listing each of the functions in that category.
  • One help page for each function.

The style of each page is very similar to that the help for Excel 2007.

Contents page

This page is, by default, just a list of the categories of the functions contained in the add-in. Your should add your own content, probably including support contact details. We will see in a later topic how to add content to the page, and also how to override the default contents.

Category page

The category page links to each of the relevant functions, along with a summary description of the function.

Function help

The function page shows the syntax and description of a function. Standard paragraphs are added for each argument, describing the expected format. These paragraphs can be suppressed or replaced. You can also add your own content to the help for each function and argument. We will look at this in the next topic.

Next: The Help file >>


The Help file

Locating the Help File

When the add-in project was created, a skeleton help file was added to the project. You can find it in the Solution Explorer in the "Help Files" folder, named Tutorial1.help.xml.

When the help generator builds its help project, it collects together all the add-in functions in all the source files of the current project, along with the definition of the project itself, and writes the definitions to some temporary xml files in the Help sub-directory.

Then the generator merges the contents of the help file Tutorial1.help.xml to create the contents of the help project. Finally, it calls the HTML help compiler (hhc.exe) to build the finished product, Tutorial1.chm.

Contents of the Help File

Open the file Tutorial1.help.xml and have look at it. By default, it contains some suggested content that is commented out. You can use this as a template for your own content.

The root element of the file is always the Help element. This may contain any or all of the following elements:

Element | Description
Project | This contains settings that apply to all pages, and also any additional content you want to appear on the front ("Contents") page.
Section | This element controls one of the Category pages. It contains switches to control the default content of the page, and also any additional content you want to add to the page.
Function | This element controls the help page for one name function. It contains switches to control the default content of the page, It may also contain any additional content you want to add to the function's help, or to the descriptions of its arguments.
AdditionalFile | This element adds one user-supplied HTML file to the help system. You can apply standard formatting to the page, or you can instruct the help generator to copy your file directly without changes.

Next: Editing the Help file >>


Editing the Help file

Editing the User File

The file contains a reference to the help file schema "http://schemas.planatechsolutions.com/xlp/601/help". This schema was installed as part of the XLL+ tool-kit; as a result syntax checking, intellisense and popup help are available in the Visual Studio XML editor.

Intellisense

Intellisense helps a lot with editing an XML file. All the legal options are listed in a dropdown as soon as you start typing, so you don't need to learn the file format.

Syntax checks

Syntax checking is also useful, since it catches any syntax errors right when they occur.

Popup help

Popup help for each element and attribute explains what is required, what is optional, and what is the purpose of the element.

Next: Adding your own content >>


Adding your own content

Project element

First, let us change the front page of the help, by inserting a <Project> element into the help file, Tutorial1.help.xml. Paste the code marked below into the <Help> element:

CopyXML
<Help
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="http://schemas.planatechsolutions.com/xlp/601/help">

  <Project Title="XLL+ Tutorial">
    <Description>
      <p>This add-in contains all the functions from the following
      XLL+ Tutorial sections:
      </p>
      <ul>
        <li>Getting Started</li>
        <li>Basic Features</li>
        <li>Intermediate Features</li>
      </ul>
    </Description>
  </Project>
  ...
</Help>

We've made two changes to the page here:

  1. The main title of the help is now "XLL+ Tutorial".
  2. We've added new content to the Description section of the page. All the HTML within the <Description> element will be inserted into the page just after the standard description.

Function element

Now we will enrich the help for the HISTVOL function. Paste the code marked below into the <Help> element:

CopyXML
<Help ...>
  ...
  <Function ExportedName="HISTVOL">
    <Argument Name="Prices">
      <Description>
        <p>Note that if any of the values in the series are 0 or less,
        then the function will return #NUM!.</p>
      </Description>
    </Argument>
  </Function>
  ...
</Help>

Here we have added an extra paragraph to the description of the Prices argument.

There are many other enhancements we might make to a function's help page, including:

  • Adding text to the function's description.
  • Adding a Remarks section.
  • Adding See Also links to other pages.
  • Suppressing some or all of the standard function or argument descriptions.

Other content

You can also add your own HTML files to the help system, using the AdditionalFile element. See Additional Files in the reference for more information on adding files to a help project.

You can use the Section element to enhance the content of the category pages.

See the Help Generator Reference for a complete list of the grammar of help files. The comments inserted in each new help file contain examples of most of the available elements.

Next: Testing the interactive help >>


Testing the interactive help

Rebuild Help

Save your changes to Tutorial1.help.xml, make sure that the compiled help file Tutorial1.chm is closed, and build the project again.

You may want to inspect the generated help file at this point, to check that your changes have been added to the compiled help file.

Test the help

Follow these steps to see the help in action:

  1. Start Excel.

  2. Using the File/Open... command, open the release build of your XLL.

  3. Type =HISTVOL into a cell, and then press CTRL+A to invoke the Excel Formula Wizard.

  4. Click on the Help on this function link at the bottom left of the Formula Wizard.

  5. Your updated help page for HISTVOL should now appear.

Next: Updating the help command line >>


Updating the help command line

The help command line

The command line that builds the help files is set up when the XLL+ project is created. It includes the names of any source files that contain add-in functions, as well as any extensions used by the add-in functions, e.g.:

"$(Xlp90InstallDir7)bin\BuildHelp.exe" -s "$(ProjectDir)."  -i "$(ProjectName).cpp" -p $(ProjectName) -n true"
"$(Xlp90InstallDir7)bin\BuildHelp.exe" -s "$(ProjectDir)."  -i "$(ProjectName).cpp" -i "AnotherFile.cpp" -p $(ProjectName) -n true -e "RtdHandles.xpe"

For more details about the command line tool that builds help files, see the BuildHelp Utility reference.

Updating the command line

From time to time you may need to update the command line:

  • When you add to the project a new CPP file that contains add-in functions.
  • If you change the name of a file containing add-ins, or remove it from the project.
  • If you use a new XLL+ extension, or stop using using an extension.

You should use the Update Help Command Line command to update the command line. After you run it, the help command line will be updated to include all relevant source files and extensions.

Next: Languages other than English >>


Languages other than English

By default, the help project is generated in English. You can change the language of the help project by setting the value of the Language attribute of the Help element.

You can find a list of the languages supported in the file Localized.xsl, in the bin\xsl sub-directory of your XLL+ installation.

Next: Help IDs >>


Help IDs

An add-in function and its online help page are linked via a numeric Help ID, that is unique within the help file.

These IDs are generated (i) when the help file is built and (ii) at run-time when the XLL is loaded. Usually, the two sets of IDs will match, and no further effort is required to make the function connect to the appropriate help topic.

However, if your add-in uses a filter to select which functions will be registered (as in the PartialReg sample), or if you register add-in functions explicitly at run-time, then you will need to ensure that the Help IDs continue to match by setting a specific (and unique) Help ID for each add-in function.

You can do this for each function in the Properties window, by setting the Help ID property. (Note that a Help ID of 0 is considered to be unassigned.)

A quicker and easier way is to use the Set Help IDs command, which is on the Tools menu of the XLL Add-ins window. This command will create and assign a unique Help ID for all functions in the project which do not currently have a Help ID.

As a result, all of your add-in functions will be permanently tied to their corresponding help topic.

Next: Exceptions >>


Exception handling

This chapter contains the following topics:

Exceptions
Overriding exception-handling behavior
C Runtime Exceptions


Exceptions

Exception handling in add-in functions

The XLL+ Function Wizard creates three C++ functions for each add-in function. One is the wrapper function called by Excel 2003 and below, another is the wrapper function called by Excel 2007 and above, and the third is the common implementation function called by both wrapper functions.

The wrapper functions call the implementation function within a try-catch block, which catches exceptions of type CXlRuntimeException. While validating user input, the implementation function calls a number of XLL+ library functions which may throw exceptions of type CXlRuntimeException.

In the wrapper function the application-level method CXllApp::DisplayException() is called, which converts the caught exception into an error result to be returned to Excel.

The pseudo-code below illustrates this exception flow.

Raising exceptions

If your code raises an exception which is derived from CXlRuntimeException, then you do not need to handle it specially - the wrapper function will handle and translate it for you.

If your code raises exceptions of some other type, then you must catch them. Depending on your preference in programming style, you can deal with them in one of two ways.

  1. Set the value of xloResult to an error value and exit the function.
  2. Throw another exception, of a type derived from CXlRuntimeException. This will be caught by the wrapper function as usual.

Examples of the two techniques are shown below. The first block of code below was used in the HISTVOL add-in function, to trap a C++ exception and translate immediately to #NUM!.

CopyC++
CXlOper* HISTVOL_Impl(CXlOper& xloResult, const CXlOper* Prices_op, const
    CXlOper* DaysPerYear_op)
{
    ...
//}}XLP_SRC
    try
    {
        xloResult = CalcHistVol(Prices, DaysPerYear);
    }
    catch(const char*)
    {
        xloResult = xlerrNum;
    }
    return xloResult.Ret();
}

Another approach could have been used: to catch the error and rethrow it with a rich error message.

CopyC++
CXlOper* HISTVOL_Impl(CXlOper& xloResult, const CXlOper* Prices_op, const
    CXlOper* DaysPerYear_op)
{
    ...
//}}XLP_SRC
    try
    {
        xloResult = CalcHistVol(Prices, DaysPerYear);
    }
    catch(const char* ex)
    {
        throw CXlRuntimeException(ex);
    }
    return xloResult.Ret();
}

With this approach, the error string originally thrown by CalcHistVol() is caught by the wrapper function and passed to CXllApp::DisplayException(), so you get errors such as:

#ERROR: zero value
#ERROR: negative value
#ERROR: too few points

Next: Overriding exception-handling behavior >>

See Also

xlpexcept.h


Overriding exception-handling behavior

You can override the virtual function CXllApp::DisplayException() to change the exception-handling behavior of all functions in the add-in.

Converting strings to error values

In particular, you may wish to convert all instances of a particular class of exception to a particular Excel error value, such as #VALUE!. The library function CXllApp::ConvertTypeToError can be used to do the hard work, along with the XLEXCEPTION_TRANSLATION macro.

CopyC++
XlExceptionTranslation translations[] = {
    XLEXCEPTION_TRANSLATION(CXlConversionException, xlerrValue),
    XLEXCEPTION_TRANSLATION_END
};

void CTutorial1App::DisplayException(CXlOper& xloResult, const CXlRuntimeException& ex)
{
    // Try the conversion list
    if (ConvertTypeToError(translations, xloResult, ex))
        return;
    // Revert to the base class for the standard handler
    CXllApp::DisplayException(xloResult, ex);
}

XLEXCEPTION_TRANSLATION(type, xlerr)

This macro defines a translation pair containing:

  1. the class name of the exception type
  2. the Excel error value to which all conversions of this type will be translated

The macro will cause a compiler error if the class name is misspelt; this behavior is intentional and avoids the possibility of errors that might occur if you merely provide the name of the exception type as a string.

Enable Run-time Type Info

If you use the XLEXCEPTION_TRANSLATION macro, you should ensure that your project has the Enable Run-time Type Info setting set to Yes (/GR). The setting can be found on the C/C++ - Language page of the project settings.

Changing the format

You may want to change the default format of error messages, which is to wrap the exception's error message as follows:

#ERROR: [message]

The code below changes the format to #VALUE! [message].

CopyC++
void CTutorial1App::DisplayException(CXlOper& xloResult, const CXlRuntimeException& ex)
{
    CString fullMessage;
    fullMessage.Format("#VALUE! %s", ex.what());
    xloResult = fullMessage;
}

Next: C Runtime Exceptions >>


C Runtime Exceptions

It is very important that Excel add-in functions do not crash Excel. Many users of Excel expect to keep an instance of Excel running for days at a time. If there are a lot of other add-ins registered, it can often take several minutes for Excel to restart.

If your add-in is calling somebody else's code, you can never be sure that it will behave as it should, particularly if the 3rd-party code is frequently updated. What can you do if a fatal bug is introduced?

One useful way to make an add-in bomb-proof is to catch hardware exceptions. This class of exception includes the following old favourites:

  • Integer divide by zero
  • Access violation

Dangerous code

Let's look at a couple of examples of the sort of code that can bring Excel crashing down. All of the code in this section is from the demo project SafeCode.

Integer divide by zero

Our first example divides by an integer, without first checking that it is non-zero.

CopyC++
long IntAverage(int nCount, long* alItems)
{
    int i;
    long lTotal, lResult;
    for (i = 0, lTotal = 0; i < nCount; i++)
        lTotal += alItems[i];
    // The next line causes a divide/0 error if nCount = 0
    lResult = lTotal / nCount;
    return lResult;
}

If your add-in function calls this code with nCount = 0, Excel will crash immediately. Under the Visual Studio debugger, the following message will appear:

If the bug occurs without the debugger, the following message will appear:

In either case, Excel is toast and will need to be restarted.

Access violation

Another very common error is to write to memory that is not owned by the calling process, particularly at address 0000:0000.

CopyC++
void MakeSeries(double dBase, double dInc, int nOut, double* adOut)
{
    int i;
    // The next line causes an access violation if adOut = 0
    adOut[0] = dBase;
    for (i = 1; i < nOut; i++)
        adOut[i] = adOut[i - 1] + dInc;
}

If your add-in function calls this code with nOut = 0 and adOut = 0, which is a degenerate but perfectly legal case, Excel will crash as in the case of Integer divide by zero, above. The message will be different - "0xC0000005: Access Violation" - but the consequences will be the same.

The way to catch these errors is by using the C Structured Exception Handling (SEH) mechanism provided by Microsoft.

Trapping C Exceptions

By default, the wrapper functions generated by the XLL+ Function Wizard trap C runtime exceptions, and instead throw an exception of type CXlStructuredException. CXlStructuredException is derived from CXlRuntimeException, so the standard exception handling code in the wrapper functions deals with the C++ exception by returning a description to Excel.

CopyC++
extern "C" __declspec(dllexport)
LPXLOPER12 INTAVG_12(LPXLOPER12 Input)
{
    XLL_FIX_STATE;
    CXlOper xloResult, Input__port(Input);
    try {
        CXlStructuredExceptionHandler _seh_;
        xloResult.HandleResult(INTAVG_Impl(xloResult, &Input__port));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    return xloResult.Ret12();
}

In the example above, if a C runtime exception occurs during the call to INTAVG_Impl (where your code lives), then it will be trapped and a C++ exception wil be thrown. The CXlStructuredExceptionHandler instance does the work. In its constructor it plugs itself into the C runtime exception handler, and in its destructor it removes itself.

The error information will be returned to Excel in an error message.

Not trapping C exceptions

You may have code which already deals with these exceptions, in which case you will wish to switch off the default handling of C Runtime Exceptions. You can do this by setting the advanced function property DoNotCatchStructuredExceptions to true.

Next: Introduction to macro functions >>


Macro functions

This chapter contains the following topics:

Introduction to macro functions
Setting cell values
Find/Replace
CXlMacros class
Using references
Setting formulae
Macro helpers


Introduction to macro functions

What are macro functions?

When an add-in function is specified as a worksheet function, it can (as the name implies!) be called from a cell in a worksheet. To comply with the requirements of Excel's recalculation, a worksheet function is forbidden to change values in workbooks or to do a number of other actions such as finding the active cell or worksheet.

A function that acts on a workbook, rather than just returning a value, is called a macro function. It can use the Excel SDK API to manipulate workbooks in a variety of ways, just like a VBA macro. However, a macro written in C++ differs from one written in VBA in two significant ways:

  • C++ macros run significantly faster than VBA macros, especially when setting cell values.
  • VBA macros have access to a much richer programming model, via the Excel automation interface.

Calling a macro function

A macro function can be called in one of three ways:

  1. Through a GUI device, such as a menu or button. Macros called in this way cannot take any arguments.
  2. From VBA, using Application.ExecuteExcel4Macro(MacroName) or Application.Run(MacroName, Arg1, ...).
  3. After being installed as an event-handler.

Note that a macro function cannot be called from a worksheet cell, unless it is also specified to be a worksheet function.

Specifying a macro function

In the Function Wizard, you can specify that a function be a worksheet function, a macro function, or a hidden function, using the Availability option group on the Features tab.

You can also specify the availability of a macro function in the Properties window, by setting the Availability property.

Finally, you can create a macro function in one step using the New Macro command, which is located on the toolbar of the XLL Add-ins window.

Next: Setting cell values >>


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 macro function in one step using the New Macro command, which is located on the toolbar of the XLL Add-ins window.

Name: SETDATE

Add the code

Amend the generated code as shown below.

CopyC++
CXlOper* SETDATE_Impl(CXlOper& xloResult)
{
    // End of generated code
//}}XLP_SRC

    // Make a reference to cell A1
    CXlOper xloRef;
    xloRef.MakeRef("A1");

    // Set the value of cell A1
    xloRef.SetValue(CXlDate::Now());

    return xloResult.Ret();
}

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 "SETDATE", 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 "SETDATE", 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:

    CopyVBA
    Call Application.Run("SETDATE")
Call Application.Run("AnotherMacroFunction", 12.6, "cheese")

Next: Find/Replace >>


Find/Replace

Our next example of a macro function makes use of the CXllFinder class.

Note: the full code for this example can be found in the project FindReplace in the Samples sub-directory.

Create the function

Create a new function FindReplace() as shown below.

Name: FindReplace

Amend the code

Add the following line near the top of tutorial1.cpp:

CopyC++
#include <XllFinder.h>

Amend the generated code as shown below, and build the project.

CopyC++
CXlOper* FindReplace_Impl(CXlOper& xloResult)
{
    // End of generated code
//}}XLP_SRC
    const TCHAR* apszPairs[] = {
        _T("Fred"), _T("Freda"),
        _T("George"), _T("Georgina"),
        0
    };

    // Iterate through each find/replace task
    for (int i = 0; apszPairs[i]; i += 2) {
        // Create a finder
        CXllFinder finder(apszPairs[i], FALSE, TRUE);

        // Alternatively - create a finder for a specific sheet
        //CXllFinder finder(apszPairs[i], FALSE, TRUE, _T("FindReplace.xls"), _T("Sheet2"));

        // Look for each match
        CXlRef xlrFind;
        while (finder.FindNext(xlrFind)) {
            // Inspect the current value
            CXlOper xloValue;
            finder.GetCurrentValue(xloValue);
            TRACE(_T("%s\n"), (LPCTSTR)xloValue.ToString());
            // Change the value in the matched cell
            finder.SetCurrentValue(apszPairs[i + 1]);
        }
    }
    return xloResult.Ret();
}

Run the macro

Build the project, and start Excel.

Type the values "George" and "Fred" into several cells.

Using the Alt-F8 key (or with one of the other methods described in the last topic), run the FindReplace macro. Note that each of the Georges and Freds turn to their feminine equivalents.

Next: CXlMacros class >>


CXlMacros class

The CXlMacros class contains wrapper functions for almost all the built-in Excel macro functions. The wrapper functions take care of converting arguments and results to and from CXlOper objects.

Methods

The built-in Excel macro functions include many useful functions, including:

Method | Description
GetFormula | Returns the contents of a cell as they would appear in the formula bar
Formula | Enters a formula in the active cell or in a reference
FormulaFill | Enters a formula in the range specified or in the current selection
FormulaArray | Enters a formula as an array formula in the range specified or in the current selection
GetActiveWorkbookName | Returns the name of the active workbook
GetActiveWorksheetName | Returns the name of the active worksheet
WorkbookGetWorksheetNames | Returns a list of all the sheets in a workbook

Method names

The names of CXlMacros methods generally reflect their names in the Excel Macro Language (XLM4). This is for the convenience of programmers familiar with the language. If you do not know which is the right method to use, browse the list of methods in CXlMacros methods, and see the detailed examples in the following topics.

Example

See the CallExcel sample for examples of using CXlMacros class.

Next: Using references >>

See Also

CXlMacros class | CallExcel sample


Using references

The CXlOper class can hold data of many different types. One of the most important types it can hold is a reference. This is a reference to a cell, a rectangular range of cells, or to multiple ranges of cells.

SRefs and MRefs

A reference can be held in two forms - single and multiple. A single reference (known as "SRef") holds a reference to a single rectangular range of cells, in the current worksheet. A multiple reference (known as "MRef") holds a reference to one or more rectangular ranges of cells, all of which must be in the same worksheet, which does not have to be the current worksheet.

You should use MRef if the range you are specifying is not guaranteed to be in the current worksheet, or (much more rarely) if you are referring to multiple ranges of cells.

You can convert an SRef to an MRef using CXlOper::ChangeType. This is useful if you need to know which worksheet contains the referenced cells.

Current worksheet

It is worth noting that the current worksheet is not the same as the active worksheet. If an add-in function is called from a worksheet cell, the current worksheet is the sheet that contains the cell currently being calculated. If an add-in function is called as a macro, the the current sheet is the same as the active sheet.

Determining whether a CXlOper is a reference

Use the CXlOper::IsRef method to determine if a CXlOper holds a reference. You can use CXlOper::IsMRef and CXlOper::IsSRef to distinguish between types of reference.

CopyC++
CXlOper xloValue, xloRef;
...
if (xloRef.IsRef())
{
    // If xloRef was not a reference, the next line would fail.
    xloRef.SetValue(xloValue);
}

CXlRef object

If a CXlOper is a reference, then it will contain a valid CXlRef object, which can be accessed using CXlOper::GetRef. Each CXlRef object contains only the coordinates of a rectangular range of cells. It does not contain the name of the sheet containing the range. You can inspect and change the coordinates using CXlRef::Top, CXlRef::Left, CXlRef::Bottom an CXlRef::Right. Note that all coordinates are zero-based.

The code below constructs a reference to the single cell B3 of a sheet in several different ways.

CopyC++
CXlRef xlrA(2, 1);               // Constructor with row (=2) & column (=1) arguments
CXlRef xlrB, xlrC, xlrD;
xlrB.SetRef(2, 1);               // Set top and left. Bottom and right are implied.
xlrC.SetRef(2, 1, 2, 1);         // Set top, left, bottom & right explicitly
xlrD.Left() = xlrD.Right() = 1;
xlrD.Top() = xlrD.Bottom() = 2;

You can convert a CXlRef object to and from a text address using CXlRef::ToString and CXlRef::FromString.

CopyC++
CXlRef xlr(2, 1);
CString strAddressA1 = xlr.ToString(TRUE);    // Contains "B3"
CString strAddressRC = xlr.ToString(FALSE);   // Contains "R3C2"
if (!xlr.FromString("A2"))
    CXllApp::XlMessageBox("Failed to read address", 3);
CString strLocal = xlr.ToString(FALSE, TRUE); // Contains "R3C2" in English,
                                              // "Z3S2" in German, etc

Sheet identifiers

Excel uses a numeric sheet identifier to uniquely identify a worksheet. This sheet ID remains constant as long as the worksheet is open. It does not change even if the worksheet's name is changed, or if the containing workbook's name is changed. However, if a workbook is closed and later reopened, there is no guarantee that the sheet IDs of its worksheets will remain constant.

You can get the sheet ID from a reference using CXlOper::GetSheetId.

CopyC++
CXlOper xloRef;
DWORD sheetID = 0;
...
if (xloRef.IsRef())
    sheetID = xloRef.GetSheetId();

You can convert sheet IDs to names and vice versa using CXllApp::GetSheetName and CXllApp::GetSheetId.

CopyC++
DWORD sheetID = CXllApp::GetSheetId("Book1", "Sheet1");
sheetID = CXllApp::GetSheetId("[Book1]Sheet1");
CString sheetName = CXllApp::GetSheetName(sheetID); // Contains "[Book1]Sheet1"

Creating a reference using CXlRef

There are several ways to create a reference. You can create a reference explicitly from a CXlRef, using CXlOper::FromSRef and CXlOper::FromMRef, or various short-hand equivalents. You can initialize a CXlRef object and create a single reference (SRef) from it by copying.

CopyC++
CXlRef xlr(2, 1);
CXlOper xloRef;
xloRef = xlr;         // xloRef now contains a reference to cell B3 in the current sheet
xloRef.FromSRef(xlr); // Has exactly the same effect as the line above

To create an MRef, you must also supply a sheet ID or a sheet name.

CopyC++
CXlRef xlr(2, 1, 3, 2);
DWORD sheetID = CXllApp::GetSheetId("[Book1]Sheet1");
CXlOper xloRef;
xloRef.FromMRef(&xlr, 1, sheetID);         // xloRef now contains a reference to cells B3:C4
                                           // in sheet [Book1]Sheet1
xloRef.FromMRef(&xlr, 1, "[Book1]Sheet1"); // Has exactly the same effect as the line above

Creating a reference using strings

You can also use strings to create references, via CXlOper::MakeRef and CXlOper::MakeRefIntl.

CopyC++
CXlOper xloRef;
if (!xloRef.MakeRef("A1", TRUE))
    CXllApp::XlMessageBox("Failed to read address", 3);
if (!xloRef.MakeRefIntl("R1C1", FALSE))
    CXllApp::XlMessageBox("Failed to read address", 3);
if (!xloRef.MakeRef("[Book1]Sheet1!A1:C5", TRUE))
    CXllApp::XlMessageBox("Failed to read address", 3);

Note that if no sheet name is provided, then the reference will be to the current worksheet.

Functions that return references

Some Excel API functions also create references.

Method | Description
CXlOper::GetActiveCell | If successful, the calling object will contain a reference to the currently active cell.
CXlMacros::TextRef | Converts a text address to a reference.
CXlMacros::RelRef | Calculates a relative reference from an address and an offset.

References as arguments to add-in functions

You can also pass references as arguments to add-in functions. Specify an argument's type to be CXlOper, and it will be capable of accepting a reference. A CXlOper argument can also contain anything else, so you should check in your code whether the argument actually is a reference, using CXlOper::IsRef.

CopyC++
CXlOper* FillRange_Impl(CXlOper& xloResult, const CXlOper* Range)
{
    // End of generated code
//}}XLP_SRC
    if (Range->IsRef())
    {
        if (Range->GetRef().Width() > 1)
        {
            CXllApp::XlMessageBox("Expected only one column", 3);
        }
        else
        {
            Range->SetValue("Fred");
        }
    }
    return xloResult.Ret();
}

Using references

Several methods of CXlOper are useful only if the CXlOper contains a reference. In addition, many functions of XLL+ classes take references as arguments. Among these are the following:

Method | Description
CXlOper::GetRef | Returns a reference to the CXlRef part of the reference. (If the reference contains multiple ranges, this returns a reference to the first one.)
CXlOper::SetValue | Sets the values of the cells in the reference.
CXlMacros::DeRef | Returns the contents of the cells in the passed reference.
CXlMacros::FormulaFill | Places the passed formula in the cells of the passed reference.

Next: Setting formulae >>


Setting formulae

Setting a cell's formula in Excel can be a surprisingly complex process. This topic addresses each of the complexities in turn, and explains how to handle them as easily as possible.

International issues
A1 versus RC addressing
Absolute and relative addresses
Recommendations

International issues

Different regional settings cause Excel to display formulae in a different way. There are several important differences:

Issue | Description | Affected by
Function names | Excel's built-in functions appear with different names in different languages. | Excel language version
List separators | A function's arguments may be separated by commas, or by semi-colons or by some other punctuation character. | User's regional settings
Decimal points | A number's integral and fractional parts may be separated by a full stop or a comma or by some other punctuation character. | User's regional settings
Array separators | An array value expressed as a list may use semi-colons, commas or some other character to separate rows within the list. | User's regional settings
RC-style addresses | The letters used in RC style addresses vary according to language; thus cell A1 is R1C1 in English and Z1S1 in German. | Excel language version

It should be clear from the above that simply setting a cell's formula to be, for example, =SUM(A1,B1,C1) will not work reliably. There will be at least two problems:

  1. Foreign language versions of Excel use a different name for the SUM function.
  2. A user's regional settings may use a character other than a comma to separate the function's arguments.

In addition, if RC notation (see below) is used, the address is different in different languages: thus =R1C1 will fail in German, which expects =Z1S1.

When working with formulae, there are two different sets of methods you can use.

Local | International | Description
CXlOper::GetFormula | CXlOper::GetFormulaIntl | For a CXlOper containing a reference, gets a cell's formula, as it appears in Excel (local version), or as it would appear in an English language version of Excel with US settings (international version).
CXlOper::SetFormula | CXlOper::SetFormulaIntl | Sets a cell's formula, as it appears in Excel (local version), or as it would appear in an English language version of Excel with US settings (international version).
CXlOper::ConvertFormula | CXlOper::ConvertFormulaIntl | Using a CXlOper containing a reference as a reference point, converts a formula between A1 and RC style addresses and between relative and absolute references.
CXlOper::SetLongFormula | CXlOper::SetLongFormulaIntl | Sets a cell's formula; the formula may contain up to 1024 characters.
CXlOper::MakeRef | CXlOper::MakeRefIntl | Creates a range reference from a string.

The Intl variants are recommended. If you use the Intl variants (GetFormulaIntl etc), you should write all your formulae in English, with US settings (i.e. commas to separate list items and arguments, full stops for decimal points and semi-colons to separate rows in array lists). You can be sure that your code will work regardless of the user's Excel language version or personal regional settings.

On the other hand, if you are going to manipulate formulae using the non-international variants (GetFormula etc), you should use the CXllApp::GetInternational method to retrieve the correct punctuation. See the International sample for an example of this technique.

A1 versus RC addressing

Excel addresses can be expressed in two styles, A1 style and RC style. A1 style uses one or more letters for the column, starting at "A" (column 1) and ending at "IV" (column 256); the letters are followed by an integer for the row (1 to 65536). RC style uses "RrCc" where r is the row number and c is the column number, e.g. "R1024C251". Thus "B3" and "R3C2" can refer to the same cell.

The user can choose either style to be displayed in a workbook (the default is A1). Each style supports both absolute and relative addressing (see below).

If you are generating a formula using code, or parsing an existing formula, it is generally much simpler to use RC style. However, the conversion methods in the XLL+ classes, such as CXlRef::ToString and CXlRef::FromString, support both A1 and RC style, so you can use either style as you prefer.

Note that for Excel versions in languages other than English, the letters "R" and "C" in an RC-style address will be in the local language. For example, the English address "R1C1" will be displayed as "Z1S1" in German. See also International issues above.

Absolute and relative addresses

Both styles (A1 and RC) support both relative and absolute addresses. A1 style addresses are relative by default, and are made absolute by prefixing the row, the coloumn or both with a dollar symbol, e.g. "$A$1". RC style addresses are absolute by default and are made relative by replacing the row or column number with a row or column offset within square braces, e.g.: "R[-1]C[-2]".

CXlMacros::FormulaConvert can be used to convert the references in a formula between absolute and relative addressing.

Recommendations

The following practises are advised when manipulating formulae.

  • Always use the international versions of the formula methods.
  • Use RC format for addresses, both absolute or relative.
  • Set up relative and absolute addresses explicitly, ensuring you use the R[n]C[n] format for relative addresses.
  • Use relative addresses wherever possible: they are much easier for users to manipulate.

You may still choose to use the local versions of formulae when displaying them to users in dialogs etc; it is sensible to avoid local forms otherwise.

Examples

You can find examples of the various ways to set formulae in the SetFormula sample.

Next: Macro helpers >>


Macro helpers

The XLL+ class library contains a number of classes to help with managing Excel's state. These can be used during macro add-in functions to help provide a more pleasant and predictable user experience.

Use CXlSuspendAutoRecalculation, CXlSuspendEcho and CXlSuspendError to improve performance and usability during macros.

Use CXlActiveBookRestorer, CXlActiveSheetRestorer and CXlActiveCellRestorer to restore the active book, sheet and selection after an operation is completed.

Next: Global data overview >>


Global objects and data

This chapter contains the following topics:

Global data overview
Events
Ensuring global data is thread-safe
Results cache


Global data overview

Application level data

An add-in will often need to contain data that has application-level scope. For example, an add-in might have a connection to a database that is only open as long as the add-in is in use.

Or it might keep a cache of the results of long slow calculations, so that if the same calculation is required more than once, the answer will be cost-free after the first call. (See Results cache for a built-in utility that will do this for you.)

CXllApp

XLL+ projects include a single instance of a class descended from CXllApp. This class and all its code is generated initially by the AppWizard when the project is created.

The CXllApp object represents the add-in library. It is in existence for as long as the library is open, and its lifetime ends when the add-in is closed.

It is a convenient place to keep data and objects that must exist at application scope.

Accessing the CXllApp instance

You can get a pointer to your CXllApp instance at any time by calling the
static method CXllApp::Instance()
or the global functions XllGetApp()
and XllGetTypedApp().

Events

CXllApp has a number of events which you can trap by implementing virtual functions. The table below lists the most important events.

Event | Description
OnXllOpenEx | Called by the framework when Excel opens the XLL. The overridden function can return FALSE to halt further loading of the XLL.
OnXllClose | Called by the framework when Excel closes the XLL

You should perform any initialization for your global objects in OnXllOpenEx(), and return FALSE if it fails. Similarly, any termination code should be in OnXllClose().

Adding global data to the application class

The application class is declared in the main header file for the project, e.g. tutorial1.h.

You can add your own data by declaring it as a member variable of the class:

CopyC++
class CTutorial1App : public CXllApp
{
public:
    CTutorial1App();

// Names
public:
    static LPCTSTR m_pszDefName;

// Data
    MyGlobalObject m_thingummy;

// Overrides
    virtual BOOL OnXllOpenEx();
    virtual void OnXllClose();

    ...
};

Keeping global data outside the application class

On the other hand, it may not be convenient to keep the global instance of your object inside the application class, particularly if the same object is used in multiple add-ins, or if the code is provided by a 3rd party.

In this case you can still hook your object up to the XllOpen and XllClose events. See Open & Close events for a discussion of this technique.

Next: Events >>


Events

Handling the XllOpen and XllClose events

A typical use of the XllOpen and XllClose events is to manage security. The user should log in to a system when the XLL is opened, and log out when it is closed. If the login fails, then the XLL should be disabled.

Look at the following code for an example of handling a login.

CopyC++
BOOL CTutorial1App::Authorize()
{
    // Show a login dialog
    int attempts = 3;
    while (true)
    {
        // Put up a dialog
        CXlOper xloLogin;
        BOOL quit = !CXllApp::XlInputBox(xloLogin,
            _T("Please enter a password"), XlInputBoxTypeText,
            _T("Tutorial1"));

        // Check the password
        BOOL ok = !quit && (xloLogin.ToString() == _T("123"));

        // Succeed, try again or give up
        if (ok)
            return TRUE;
        if (quit || --attempts == 0)
        {
            CXllApp::XlMessageBox(_T("Logon for Tutorial1 failed"),
                XlMessageBoxTypeInformation);
            return FALSE;
        }
    }
}

BOOL CTutorial1App::OnXllOpenEx()
{
    if (!Authorize())
        return FALSE;
    // TODO: Allocate any application-level resources
    return TRUE;
}

The login is obviously rather simplistic, but it shows the pattern.

  • Put up a user interface to get user authentication.
  • If the user is authenticated, continue with initialization.
  • If the user is not authenticated, let user try again.
  • If the user chooses not to enter authentication information, or has tried too many times, tell them so, and return FALSE.

If FALSE is returned by OnXllOpenEx(), then the XLL will not be opened and none of its add-in functions and commands will be available.

Note: You should remove the call to Authorize() from OnXllOpenEx() as soon as you've finished testing it. It gets very tedious entering the password every time you open the XLL!

Next: Ensuring global data is thread-safe >>


Ensuring global data is thread-safe

Multi-threaded Excel

One of the more exciting features of Excel 2007 is its ability to calculate on multiple threads at the same time. Excel's calculation engine locates areas of a workbook that have no dependencies on each other, and recalculates each area in isolation from the others, using as many threads as are available.

This is a very powerful improvement, particularly on machines with multi-cored processors or multiple processors.

Multi-threading is also particularly useful if you are passing calculations out to a grid-computing network, even on a machine with a single processor. All the threads that are waiting on the grid will be blocked, and will therefore impose virtually no processing cost. The threads that are calculating locally will have the full power of the CPU(s) to work with.

Thread-safe functions

You can mark your functions as thread-safe using the XLL+ Function Wizard:

Or you can use the Properties window:

Thread-safe global data

If your thread-safe function makes any use of global data then you must ensure that all access to the global data is thread-safe. If necessary, you can use the CXlLockable and CXlLock classes to synchronize access to global classes.

Next: Results cache >>


Results cache

Results cache

Excel often recalculates cells more often than is necessary, recalculating even when none of the inputs to a formula have changed. For slow calculations this can be very inefficient. The results cache allows you to save the results of each invocation of a function, The next time the function is called with the same inputs, the cache can be examined and the existing results can be returned.

There is no coding involved in using a results cache; the XLL+ Function Wizard provides all the code.

Creating a cache

When you create a new application using the XLL+ AppWizard, be sure to check the box "Include a cache for results". Optionally, you can also check "Save the cache to a file", so that the cache will automatically be saved when the XLL is closed and reloaded each time the XLL is opened.

Using the cache for a function

You can mark your functions as cached using the XLL+ Function Wizard:

Or you can use the Properties window:

Code generated for cache

The Function Wizard generates code in the wrapper functions, like the following. Before calling the implementation function it checks the cache, looking for the exact set of inputs. If the check succeeds, then the stored result is returned immediately.

If the result is not found, then the implementation function is called as usual, and the result is added to the cache.

The code changes do not touch the implementation function, where your own code is located. The cache can therefore be switched on or off with no impact on your code.

CopyC++
extern "C" __declspec(dllexport)
LPXLOPER4 SLOWCALC_4(double X, double Y)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    CXlInputKey key("SLOWCALC", &X, true);
    if (XllGetTypedApp()->m_cache.Find(key, xloResult))
        return xloResult.Ret4();
    try {
        xloResult.HandleResult(SLOWCALC_Impl(xloResult, X, Y));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XllGetTypedApp()->m_cache.Add(key, xloResult);
    return xloResult.Ret4();
}

Next: The Ribbon >>


The Office Ribbon

This chapter contains the following topics:

The Ribbon
Editing the Ribbon
Ribbon callbacks
Supporting earlier Excel versions


The Ribbon

The Office Ribbon

Since Excel 2007, the Office Ribbon has become the preferred way of adding your own commands to Excel's user interface. Programatically, the ribbon is much harder work than the old method of adding your own menus and toolbars to the Excel UI. However, the interface is much richer and more powerful than the menu/toolbar UI offered by Excel 2003 and earlier versions, and you can create a much more efficient and intuitive interface for your users.

Adding a ribbon in the XLL+ AppWizard

You can generate all the code required for a ribbon by checking the option Add a group to the ribbon in the XLL+ AppWizard.

Checking this option will cause a number of changes to your project. The most important changes are as follows:

  • An XML file, named [YourAddin].RibbonX is created and added to your project. When the project is built, this file will be embedded in the XLL file as a resource.

  • A virtual function, OnRibbonEvent, is added to your application class. This is the place to put any code that responds to user's ribbon actions or that alters the ribbon's appearance and content at run-time.

For a full list of the ribbon-related changes made to a project by the AppWizard see Adding ribbon support to a project.

The XLL+ Ribbon Manager

The only way to add items to the Office Ribbon is through a COM add-in. It cannot be done through a standard XLL add-in. The toolkit therefore includes a COM add-in, XlpRibbonServer.dll, which manages all the COM extensibility requirements, and routes ribbon events via the XLL, where they can be handled by the OnRibbonEvent() method.

Like other COM modules, the XLL+ Ribbon Manager must be registered before it can be used. On a development machine, the module is registered when the toolkit is installed. For instructions on deploying to users' machines, see the reference section Deploying add-ins that use the Office Ribbon.

Next: Editing the Ribbon >>

See Also

Ribbon Reference


Editing the Ribbon

The ribbon sample code

The AppWizard adds a sample ribbon to your add-in, which will look like this:

The XML in the file [AddinName].RibbonX looks like this:

CopyXML
<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
  <ribbon>
    <tabs>
      <!-- This tab element adds its child groups to the "Add-Ins" tab.     -->
      <!-- To create a new tab element specify the id and label attributes, -->
      <!-- and remove the idMso attribute.                                  -->
      <tab idMso="TabAddIns">
        <!-- This group element creates a new region on the tab specified   -->
        <!-- by its parent element.                                         -->
        <group id="MyAddin_Group" label="My Group"
                             getVisible="GetVisible">
          <!-- This large button displays an image from the resources,      -->
          <!-- whose ID is "LOGO", and a  fixed label. When the button is   -->
          <!-- pressed, the application class event handler function        -->
          <!-- OnRibbonEvent() is called.                                   -->
          <button id="MyAddin_PushButton"
                  size="large"
                  image="LOGO"
                  label="My Button"
                  onAction="OnActionButton" />
        </group>
      </tab>
    </tabs>
  </ribbon>
</customUI>

The virtual function OnRibbonEvent() handles events generated by the ribbon:

CopyC++
CXlOper CMyAddinApp::OnRibbonEvent(const CRibbonEvtParams& e)
{
    CXlOper xloResult = CXllApp::OnRibbonEvent(e);
    switch (e.GetCallback())
    {
    case RIBBONCALLBACK_GETVISIBLE:
        if (e.GetId() == _T("MyAddin_Group"))
            xloResult = true;
        break;
    case RIBBONCALLBACK_ONACTION:
        if (e.GetId() == _T("MyAddin_PushButton"))
        {
            XlMessageBox(_T("Hello from the ribbon!"),
                XlMessageBoxTypeInformation);
        }
        break;
    }
    return xloResult;
}

The event handler code first calls the method of the base class (CXllApp::OnRibbonEvent) to ensure that the return value is of the right type and is a legal value.

Next the callback type is inspected using the CRibbonEvtParams::GetCallback() method. You can find a full list of callback types here: RibbonCallbackTypes.

Note how the unique ID of the pushbutton - "MyAddin_PushButton" - links the XML in the ribbon to the C++ event handler. The ID is extracted from the event parameters using the function CRibbonEvtParams::GetId(). This tells the handler which control generated the event, and the appropriate action is taken.

The handler for the RIBBONCALLBACK_GETVISIBLE event is important. This event is raised by the ribbon manager and passed to the add-in to determine whether the top-level control should be visible. In this case the top-level control is the group MyAddin_Group. As we can see, the add-in simply returns true. However, if the add-in is later removed from the active add-ins list, then the ribbon manager will try, once again, to ask the add-in whether the top-level group should be displayed. Since the add-in has been unloaded, the manager cannot pass the event to the add-in, and instead returns false (the default value). As a result, when the add-in is unloaded, its ribbon controls are automatically hidden.

Editing the XML

If you have the XML schema for the Ribbon UI installed, then you will get Intellisense and contextual help when you edit the .RibbonX file. The file is named CustomUI.xsd and should be installed in the folder [ProgramFiles]\Visual Studio XX\Xml\Schemas. If it is not installed then you can look in one of two places:

  1. You may find the file in the 1033 sub-directory of the Schemas directory. If it is there, you should copy it up the Schemas directory.

  2. The file can be downloaded from Microsoft's web-site using this link: 2007 Office System: XML Schema Reference. Extract the contents and then copy CustomUI.xsd to the Schemas directory.

For more information on coding the XML for ribbons, please consult Microsoft's web-sites. This guide will only discuss the special considerations for coding a ribbon within an XLL+ add-in.

Adding images to the Excel Ribbon

Image files should be in PNG format, and should usually have a transparent background.

Once you have created an image file, add it to the project and then follow the steps below to embed it as a resource.

  1. Open the project's resource file, e.g. MyAddin.rc.

  2. In Resource View, right-click MyAddin.rc and click Add resource....

  3. Click on the Import... button.

  4. In the file dialog, ensure that the Files of Type dropdown contains All Files (*.*) and select the PNG file.

  5. Under Visual Studio 2005, the Custom Resource dialog appears: enter RCDATA as the resource type. Note that there no quotes around RCDATA. Press OK to add the image to the resource file.

  6. In Resource View select the new resource. Under Visual Studio 2005 the resource will will be under the RCDATA node, and will have a name like IDR_RCDATA1. Under later versions of Visual Studio, the resource will will be under the PNG node and will have a name like IDB_PNG1. Press Alt+Enter to view the resource properties.

  7. In the Properties Grid, change the ID to the ID of the image, including quotes, e.g.: "LOGO". Note that the quotes are always required. The actual ID you use should correspond to the image ID you have used for the image attribute in the ribbon file.

Building the project

Once you have made your changes to the ribbon file you can build the project. After the project is built, and extra build event will be run, something like the following:

"$(Xlp100InstallDir7)bin\XlpRibbonReg.exe" -a "$(TargetPath)" -q true

This command runs a utility which registers the XLL with the XLL+ Ribbon Manager, for the development machine. A line will be added to the Ribbon Manager configuration file (XlpRibbonServer.config), leaving it looking something like the following:

CopyXML
<?xml version="1.0" encoding="utf-8"?>
<XlpRibbonServer>
  <addins>
    <addin location="E:\OtherProjects\SomeOtherAddin\Release\SomeOtherAddin.xll" />
    <addin location="C:\MyProjects\MyAddin\x64\Debug\MyAddin.xll" />
  </addins>
</XlpRibbonServer>

If you later build a different build of the XLL, for example switching from the debug build to the release build, then the XlpRibbonReg utility will run again, and will change the relevant line, e.g.:

CopyXML
<?xml version="1.0" encoding="utf-8"?>
<XlpRibbonServer>
  <addins>
    <addin location="E:\OtherProjects\SomeOtherAddin\Release\SomeOtherAddin.xll" />
    <addin location="C:\MyProjects\MyAddin\x64\Release\MyAddin.xll" />
  </addins>
</XlpRibbonServer>

Once the Ribbon Manager knows about the XLL, it will look at the resources in the XLL when Excel is opened, and try to find a resource with the name "RIBBONX". This will be the XML that was produced by the AppWizard, and which you have edited for your application.

Please note that there is a known problem with the way Visual Studio treats files embedded in resources. If you change the contents of the ribbon file (or of any of the embedded image files), Visual Studio will not automatically rebuild the resource file. You can force the resource to be rebuilt in one of the following ways:

  1. In the output directory, delete the compiled resource file, e.g. MyAddin.res; or

  2. Use the Build/Rebuild Solution menu to rebuild the entire project.

Trouble-shooting

A number of different problems may arise during development of your ribbon UI:

  • You may have entered erroneous XML in the ribbon file.

  • You may have misspelt the name of a callback function.

  • An image file may be missing.

  • The IDs used in the XML and in the C++ may not match.

You can get useful feedback on any UI errors by turning on the option to "Show add-in user interface errors", which can be found on the Advanced tab of the Excel Options page, in the General section:

Excel Options: Show add-in user interface errors

Next: Ribbon callbacks >>

See Also

Ribbon Reference | CXllApp::OnRibbonEvent


Ribbon callbacks

Action callbacks

When a user clicks on a button in the ribbon, or selects an item in a dropdown or gallery, an Action event is raised. The framework and the XLL+ Ribbon Manager cooperate to route this event to the application's OnRibbonEvent virtual function, with a callback type RIBBONCALLBACK_ONACTION.

The table below lists the values of the OnAction attribute that should be used to specify this routing.

Control | Callback | Parameters
button | OnActionButton |
checkBox | OnActionToggleButton | pressed
dropDown | OnActionIndexed | selectedItem, index
gallery | OnActionIndexed | selectedItem, index
toggleButton | OnActionToggleButton | pressed

The XML below shows some examples of OnAction attributes.

CopyXML
<button id="MyAddin_PushButton" size="large" image="LOGO" label="My Button"
        onAction="OnActionButton" />
<toggleButton id="MyAddin_ToggleButton" size="large" imageMso="Delete"
              label="A Toggle" onAction="OnActionToggleButton" />
<checkBox id="MyAddin_CheckBox" label="My Checkbox"
          onAction="OnActionToggleButton"/>
<dropDown id="MyAddin_DropDown" label="A Dropdown"
          onAction="OnActionIndexed">
  <item id="MyAddin_DropDown_Item0" imageMso="Underline" label="Item 0"/>
  <item id="MyAddin_DropDown_Item1" imageMso="Italic" label="Item 1"/>
</dropDown>
<gallery id="MyAddin_Gallery" label="A Gallery" size="large" columns="1"
          imageMso="Font" onAction="OnActionIndexed">
  <item id="MyAddin_Gallery_Item0" imageMso="FontSizeIncrease" label="Item 0"/>
  <item id="MyAddin_Gallery_Item1" imageMso="FontSizeDecrease" label="Item 1"/>
</gallery>

You could use an event handler like the following to inspect the events and react to them:

CopyC++
CXlOper CMyAddinApp::OnRibbonEvent(const CRibbonEvtParams& e)
{
    CXlOper xloResult = CXllApp::OnRibbonEvent(e);
    switch (e.GetCallback())
    {
    case RIBBONCALLBACK_ONACTION:
        if (e.GetId() == _T("MyAddin_PushButton"))
        {
            XlMessageBox(_T("Hello from the ribbon!"),
                XlMessageBoxTypeInformation);
        }
        else if (e.GetId() == _T("MyAddin_ToggleButton"))
        {
            CString strMessage;
            strMessage.Format(_T("The toggle is %s"),
                e.GetPressed() ? _T("down") : _T("up"));
            XlMessageBox(strMessage, XlMessageBoxTypeInformation);
        }
        else if (e.GetId() == _T("MyAddin_CheckBox"))
        {
            CString strMessage;
            strMessage.Format(_T("The box is %s"),
                e.GetPressed() ? _T("checked") : _T("unchecked"));
            XlMessageBox(strMessage, XlMessageBoxTypeInformation);
        }
        else if (e.GetId() == _T("MyAddin_DropDown")
              || e.GetId() == _T("MyAddin_Gallery"))
        {
            CString strMessage;
            strMessage.Format(_T("Control %s: index=%ld item=%s"),
                (LPCTSTR)e.GetId(), e.GetIndex(), (LPCTSTR)e.GetSelectedId());
            XlMessageBox(strMessage, XlMessageBoxTypeInformation);
        }

        break;
    }
    return xloResult;
}

An alternative approach is to route the action callback directly to a named add-in function. This approach is discussed further in Supporting earlier Excel versions

Information callbacks

As well responding to user actions, your code may need to provide information to the ribbon, such as the selected item in a drop-down or a gallery, or the current image or label for a button whose appearance changes dynamically.

If you specify the appropriate callback for a control, then the event will be routed through the OnRibbonEvent handler of your add-ins application class. The XML below shows a gallery control with two additional callback attributes, getSelectedItemIndex and getImage:

CopyXML
<gallery id="MyAddin_Gallery" label="My Gallery" size="large" columns="1"
          onAction="OnActionIndexed" getSelectedItemIndex="GetSelectedItemIndex"
          getImage="GetImage">
  <item id="MyAddin_Gallery_Item0" image="STOP" label="Item 0"/>
  <item id="MyAddin_Gallery_Item1" image="GO" label="Item 1"/>
</gallery>

The code below handles the ribbon events for the gallery. Note the call to CXllApp::InvalidateRibbon after handling the OnAction event. This causes the ribbon to call GetImage and GetSelectedItemIndex again, which in turn causes the gallery's image to be updated.

CopyC++
int nGallerySelectedIndex = 0;

CXlOper CMyAddinApp::OnRibbonEvent(const CRibbonEvtParams& e)
{
    CXlOper xloResult = CXllApp::OnRibbonEvent(e);
    switch (e.GetCallback())
    {
    case RIBBONCALLBACK_ONACTION:
        if (e.GetId() == _T("MyAddin_Gallery"))
        {
            nGallerySelectedIndex = e.GetIndex();
            InvalidateRibbon();   // So that the image gets updated
        }
        break;
    case RIBBONCALLBACK_GETSELECTEDITEMINDEX:
        if (e.GetId() == _T("MyAddin_Gallery"))
        {
            xloResult.FromInt(nGallerySelectedIndex);
        }
        break;
    case RIBBONCALLBACK_GETIMAGE:
        if (e.GetId() == _T("MyAddin_Gallery"))
        {
            xloResult = (nGallerySelectedIndex == 0) ? "STOP" : "GO";
        }
        break;
    }
    return xloResult;
}

The naming convention followed is to specify a callback whose name is the same as the name of the attribute, but with an initial capital letter, e.g. getLabel="GetLabel" getImage="GetImage".

For a complete listing of all the callback functions that can be used as attributes for ribbon controls, see Ribbon callback functions.

Next: Supporting earlier Excel versions >>

See Also

Ribbon Reference | CXllApp::OnRibbonEvent


Supporting earlier Excel versions

Code generated by the AppWizard

In the XLL+ AppWizard, if you select ribbon support as well as menus and/or toolbars, the code generated will automatically suppress the menus and toolbars in Excel 2007 and above, but will show the menus and toolbars in Excel 2003 and below. And of course in Excel 2003 and below, no ribbon will be displayed.

Routing actions through macros

An alternative method of routing commands from the ribbon is to use the callback attribute OnActionButtonRunTag, which will call the macro specified in the control's tag attribute. e.g.:

CopyXML
<button id="MyPushButton" image="MyImage" size="large" label="My command"
        onAction="OnActionButtonRunTag" tag="Macro1()" />

This callback routes the command directly to Excel (via the Excel object model method Application.ExecuteExcel4Macro). If your XLL contains an add-in function named Macro1 which is a macro command, then the macro will be invoked whenever the user clicks the the button.

This approach allows you to write UI code that works in all Excel versions. For example, the code below creates a menu that is equivalent to the ribbon button example above:

CopyC++
BOOL CMyAddin::OnXllOpenEx()
{
    if (!SupportsRibbon())
    {
        // Set up menu
        m_menu.SetTexts(_T("&My menu"));
        m_menu.AddItem(_T("&My command"), _T("Macro1"));
        m_menu.Create();
    }

    return TRUE;
}

So in Excel 2007 or above, a group is added to a tab on the ribbon, and the group will contain a button labelled "My command". When the button is pushed by the user, the macro function Macro1 is run. In Excel 2003 or below, a menu "My Menu" is created, and a menu item "My command" is added to the menu. When the menu item is clicked by the user, the macro function Macro1 is run. A similar approach can be used with toolbar buttons.

For more information about the "RunTag" action callbacks, see the reference topic Ribbon RunTag actions.

Next: Menus >>

See Also

Ribbon Reference


Menus and toolbars

This chapter contains the following topics:

Menus
Toolbars


Menus

Adding a menu to Excel's main menu

You can add your own menus to Excel, by creating CXlMenu objects within your application.

Using the AppWizard

The easiest way to add a menu to your application is to check the "Add a menu" check-box in the XLL+ Application Wizard. This will add code to your application, which creates a menu during OnXllOpenEx() and destroys it during OnXllClose().

A new member object, m_menu is added to the application class, as follows:

CopyC++
class CMenuDemo1App : public CXllApp
{
public:
    CMenuDemo1App();

// Names
public:
    static LPCTSTR m_pszDefName;

// Menu
    CXlMenu m_menu;

...
};

The menu object is initialized and populated in the OnXllOpenEx() method:

CopyC++
BOOL CMenuDemo1App::OnXllOpenEx()
{
    // Set up menu
    // TODO: Change the menu captions
    //       Write an add-in function to be called when the menu item is clicked
    //       Add other menu items
    m_menu.SetTexts(_T("&My menu"));
    m_menu.AddItem(_T("&My menu task"), _T("MyAddinFunction"));
    m_menu.Create();

    // TODO: Allocate any application-level resources
    return TRUE;
}

The menu is destroyed in OnXllClose(), thus:

CopyC++
void CMenuDemo1App::OnXllClose()
{
    // Delete menu
    m_menu.Destroy();

    // TODO: Clean up any application-level resources
}

You will need to change the code as follows:

  1. Change the menu caption from "My menu" to something appropriate.
  2. Change the menu item text from "My menu task" to something appropriate.
  3. Change the menu item's macro function name to one of your own.
  4. Implement the macro function (see below).
  5. Add other menu items.

Macro functions

An add-in function that is invoked by a menu should have the following characteristics.

  1. It should be marked as a macro function in the XLL+ Function Wizard.
  2. It should take no arguments.

The macro function can interact with the user through dialogs if required, and can interact with Excel through the methods of CXlMacros and other objects.

See Macro functions for more information.

Example code

Look at the Simple menus and Advanced menus samples for instructions on using CXlMenu.

International support

Menu texts can be localized, so that they appear in the language of the user. See Internationalization : Commands for more information, the Localized (Single DLL) sample for an example of a localized menu.

Next: Toolbars >>

See Also

Simple menu sample | Advanced menus sample


Toolbars

Adding a toolbar to Excel's main window

You can add your own toolbars to Excel, by using the methods of the CXlToolbar class.

Using the AppWizard

The easiest way to add a toolbar to your application is to check the "Add a toolbar" check-box in the XLL+ Application Wizard. This will add code to your application, which creates a toolbar during OnXllOpenEx() and destroys it during OnXllClose().

A new static member object, m_pszToolbarName is added to the application class, as shown below:

CopyC++
class CToolbarDemo1App : public CXllApp
{
public:
    CToolbarDemo1App();

// Names
public:
    static LPCTSTR m_pszDefName;

...

// Toolbar
    static LPCTSTR m_pszToolbarName;

...
};

The toolbar name is set in the main cpp file, as follows:

CopyC++
/////////////////////////////////////////////////////////////////////////////
// The one and only CToolbarDemo1App object

CMenuDemo1App theApp;

/* static */ LPCTSTR CToolbarDemo1App::m_pszDefName = _T("New Xll");
/* static */ LPCTSTR CToolbarDemo1App::m_pszToolbarName = _T("CToolbarDemo1");

The toolbar is initialized and populated in the OnXllOpenEx() method:

CopyC++
BOOL CToolbarDemo1App::OnXllOpenEx()
{
    // Create toolbar
    // TODO: Change the toolbar name and captions
    //       Write an add-in function to be called when the tool button is clicked
    //       Add other buttons
    CXlToolbarState tstate;
    CXlToolbar::AddToolbar(m_pszToolbarName, tstate);
    CXlToolbar::AddTool(m_pszToolbarName, 1, _T("MyAddinFunction"), _T("My addin function"));
    CXlToolbar::SetToolBitmap(m_pszToolbarName, 1, IDB_BITMAP1);
    CXlToolbar::ShowToolbar(m_pszToolbarName, tstate, true, CXlToolbar::DockRight);

    // TODO: Allocate any application-level resources
    return TRUE;
}

The toolbar is destroyed in OnXllClose(), thus:

CopyC++
void CToolbarDemo1App::OnXllClose()
{
    // Delete toolbar
    CXlToolbar::DeleteToolbar(m_pszToolbarName);

    // TODO: Clean up any application-level resources
}

You will need to change the code as follows:

  1. Change the toolbar name from "CToolbarDemo1" to something appropriate.
  2. Change the tool's help text from "My addin function" to something appropriate.
  3. Change the tool's macro function name from "MyAddinFunction" to one of your own.
  4. Implement the macro function (see below).
  5. Edit the default tool button bitmap, which can be found in the resource file.
  6. Add other tool buttons.

Macro functions

An add-in function that is invoked by a toolbar should have the following characteristics.

  1. It should be marked as a macro function in the XLL+ Function Wizard.
  2. It should take no arguments.

The macro function can interact with the user through dialogs if required, and can interact with Excel through the methods of CXlMacros and other objects.

See Macro functions for more information.

Example code

Look at the sample applications Simple Toolbar, Simple Toolbar using resources and Dynamic Toolbar for instructions on using CXlToolbar.

Next: Utility classes >>

See Also

Simple toolbar sample | Simple toolbar using resources sample


Utility classes

XLL+ contains many utility classes for various purposes. Some of the more commonly used classes are discussed below.

  • CXlDate offers access to the Excel date functions.
  • CXllFinder lets your macro function find and manipulate cells.
  • Serialization classes let you persist and transmit Excel data objects.

CXlDate

The CXlDate class wraps calls to Excel's built-in date functions. Some are listed below.

Method | Description
Today() | Returns today's date as an Excel serial integer.
Now() | Returns the time now as an Excel serial number.
SerialToDate() | Converts an Excel serial number to year/month/day.
DateToSerial() | Creates an Excel serial number from year/month/day.

Any call to the Excel API can fail. If CXlDate methods fail, they throw an exception of type CXlApiException. Since exceptions of this type are caught by the add-in's wrapper function, they can be ignored by the developer. This feature makes CXlDate's methods convenient to use, e.g.:

CopyC++
// Call to Now() may throw an exception, but we don't care
double alarmCall = CXlDate::Now() + 0.25;

CXllFinder

The CXllFinder class is a utility class to help you search and replace the contents and formulae of cells.

Use the finder class with the following pattern:

CopyC++
const char* pszMatch = "fred";
CXllFinder finder(pszMatch, ...);
CXlRef xlrFind;
while (finder.FindNext(xlrFind)) {
    // Inspect the current value
    CXlOper xloValue;
    finder.GetCurrentValue(xloValue);
    // Use the current value...

    // Change the value in the matched cell
    finder.SetCurrentValue("replaced");
}

Note that only one instance of CXllFinder can be used at a time, since the class manipulates the active selection. CXllFinder can only be used from macro functions. It will fail if used from worksheet functions.

See also the FindReplace sample project.

Serialization classes

The XLL+ class library contains a number of classes to help with serialization. They are used (among other purposes) to implement the results cache, where they assist with the transfer of data to and from disk, and for making unique keys from a function's argument values.

The main classes are listed below:

Class | Description
CXlOStream | A stream wrapper that allows the output of Excel native types to STL output streams.
CXlOStrStream | A class that converts Excel native types to in-memory byte arrays.
CXlIStream | A stream wrapper that allows the input of Excel native types from STL input streams.
CXlIStrStream | A class that reads Excel native types from in-memory byte arrays.
CXlSerialData | A byte array containing native and Excel data types.
CXlInputKey | A specialised instance of serialized data, which contains all the inputs to an add-in function, as a byte array.

Next: Using the Microsoft Foundation Classes >>


MFC

This chapter contains the following topics:

Using the Microsoft Foundation Classes
Calling MFC methods


Using the Microsoft Foundation Classes

AppWizard - MFC option

If you want to use the Microsoft Foundation Classes in your add-in, you must select the MFC option in the AppWizard when you create your project.

The effects of setting this option are:

  • The add-in is linked with the MFC versions of the XLL+ runtime libraries.
  • The preprocessor macro XLL_LIB_MFC is defined.
  • Extra files are generated for the project, including stdafx.h and stdafx.cpp.

As a result, you are able to use MFC classes and methods from within your XLL. (Note, however, that the Document/View framework is not available from an XLL.)

Programming for MFC DLLs

Programmers familiar with writing DLLs using MFC will know that certain internal MFC data structures must be initialised whenever they are used in a DLL. In standard MFC, the AFX_MANAGE_STATE macro is used for this purpose. In an XLL+ library, you should use the XLL_FIX_STATE macro.

What this means is that you must place the XLL_FIX_STATE macro in method that uses any MFC features. The XLL+ Function Wizard does this on your behalf in all XLL+ add-in functions. However, if you use the MFC in other methods, that are not called by add-in functions, then you will need to use the macro explicitly.

CExcelWnd

The CExcelWnd class acts as a link between Excel and MFC. Create a CExcelWnd object, and it will act as an MFC CWnd, corresponding to the Excel application window. You can use this object as a parent for any MFC windows and other objects you need to create.

CString

The XLL+ run-time library contains its own implementation of the MFC string classes CString, CStringA and CStringW. (These are implemented as a thin layer around std::string and std::wstring.)

When you select the MFC run-time libraries in the XLL+ AppWizard, these string classes are excluded, and MFC's own classes are used.

Next: Calling MFC methods >>


Calling MFC methods

MFC dialog

The demo application MfcTutorial contains an example of an MFC dialog, CLanguageDialog. The example code below shows how to call this dialog when the add-in is opened.

CopyC++
BOOL CMfcTutorialApp::OnXllOpenEx()
{
    // Create an instance of CExcelWnd
    CExcelWnd wndParent;

    // Create a dialog whose parent is Excel's application window
    CLanguageDialog lang(&wndParent);

    // Show the dialog and fail if the user cancels
    if (lang.DoModal() != IDOK)
        return FALSE;

    // Read the user's input from the dialog
    m_nLanguage = lang.m_nLanguage;
    return TRUE;
}

Next: Using .NET and the Common Language Runtime >>


.NET and the Common Language Runtime

This chapter contains the following topics:

Using .NET and the Common Language Runtime
Converting to and from .NET types
Using WinForms from an add-in
Deploying your .NET assemblies
Using the Excel object model


Using .NET and the Common Language Runtime

.NET Integration

Starting with XLL+ 6.0.4, .NET integration is fully supported for XLL+ add-ins authored in Visual Studio 2005, Visual Studio 2008 and Visual Studio 2010.

Before you start

Users of Visual Studio 2005 should check the technical note .NET requirements to make sure that your development and runtime environments are properly configured.

Importing .NET Assemblies

XLL+ (6.2 and above) includes a set of tools to import a .NET assembly into an add-in. Point the tools at your assembly, and they will generate wrapper functions for you, with little or no assistance from you. See the topic Importing .NET Assemblies for full details.

If you want to write an add-in primarily in C++, but use some .NET code, then continue with this topic.

Samples

There are three .NET integration samples in the toolkit:

  • ClrDemo - a very simple introduction to using the Common Language Runtime from an add-in.
  • AssemblyDemo shows how to call your own assemblies for an add-in, and how to create and use .NET objects.
  • PiaDemo shows how to use the Excel object model from a macro add-in, and how to create and manipulate workbooks and ranges.

AppWizard - CLR option

If you want to use the Common Language Runtime in your add-in, you must select the CLR option in the AppWizard when you create your project.

The effects of setting this option are:

  • The add-in is linked with the CLR versions of the XLL+ runtime libraries.
  • The compiler flag /clr is applied to C++ source files of your project.
  • The MS preprocessor macro _MANAGED is defined.
  • The header file xlpclrconvert.h is included in your main cpp source file, and the namespace ple::clr is included by default.

As a result, you are able to use CLR classes and methods from within your XLL. This includes the members of the standard .NET libraries, and any of your own .NET assemblies.

Calling .NET methods

Your code can call .NET methods, create .NET objects and do anything that any CLR-compliant langauge can do.

The notation for calling .NET from C++ is discussed in detail in the Visual Studio help. There are many new language features in C++/CLI, but only a few of them are used in this discussion. The following language features are important when using managed classes from C++:

Handles

Do not use a pointer to a managed object, such as System::Object* obj. Instead, you should use a handle, expressed as System::Object^ obj.

CopyC++
System::String^ str = number.ToString();

You can use the -> operator to access the properties and methods of the object pointed to by the handle:

CopyC++
System::String^ str = "Quick brown fox";
int len = str->Length;
gcnew

When you create an instance of a managed class, you should use gcnew instead of new.

CopyC++
System::Object^ obj = gcnew System::Object();
array<T, n>

Common Language Runtime arrays are represented using the array template. The second parameter is the rank of the array; if omitted, it is assumed to be 1 - i.e. a vector.

CopyC++
// Create a 2-dimensional array of numbers
array<double, 2>^ a = gcnew array<double, 2>>(rows, columns);
// Create a vector of string handles
array<System::String^>^ b = gcnew array<System::String^>(count);

Items within the array can be read or written using indexing, e.g.:

CopyC++
double d = a[1, 2];
b[3] = "Hello";
safe_cast<T, S>(S)

Generally, you should use safe_cast<T, S>(S s) to cast a managed object s of type S to type T. If the cast fails, an exception of type InvalidCastException will be thrown.

Many Excel object model properties return an untyped result, which needs to be cast to a useful type. Use safe_cast for this purpose.

CopyC++
_Application^ theApp;
_Worksheet^ ws = safe_cast<_Worksheet^>(theApp->ActiveSheet);

Next: Converting to and from .NET types >>


Converting to and from .NET types

Helper functions

The XLL+ library contains a set of helper functions to make it simple to convert C++ types to and from managed types.

The functions are in the header xlpclrconvert.h, and are all in the namespace ple::clr. By default, when the XLL+ AppWizard creates a CLR project, the following lines are added to the main cpp source file:

CopyC++
#include <xlpclrconvert.h>
using namespace ple::clr;

ple::clr::toClr

Use the various versions of toClr(), toClr<T>(), and toClrDate() to convert C++ values passed from Excel into their CLR equivalents.

These functions handle numbers, dates, booleans, strings and arrays. The example below converts a string argument to a .NET string, and an array of strings to a .NET array:

CopyC++
CXlOper* PrefixArray_Impl(CXlOper& xloResult, const CXlStringArg& Prefix, const
    CXlOper* StringArray_op)
{
    // Input buffers
    std::vector<CString> StringArray;
    // Validate and translate inputs
    XlReadVector(*StringArray_op, StringArray, L"StringArray", XLA_TRUNC_ONEMPTY
        |XLA_TRUNC_ONBLANK);
    // End of generated code
//}}XLP_SRC
    // Create an instance of a .NET class
    MyAssembly::MyClass^ instance = gcnew MyAssembly::MyClass(<i>toClr(Prefix)</i>);
    // Use an instance method of the class, and return the result to Excel.
    xloResult = toXl(instance->AddPrefix(<i>toClr(StringArray)</i>));
    return xloResult.Ret();
}

ple::clr::toXl

Use toXl() and toXl<T>() to convert CLR values to Excel return values.

The various forms of toXl() handle booleans, numbers, integers, dates, strings and arrays of 1 or 2 dimensions.

CopyC++
// Return a CLR array of integers as a vector of numbers
array<int>^ clrArrayOfInt = SomeClass::SomeMethod();
xloResult = toXl(clrArrayOfInt);

// Return a CLR string
System::String^ clrString = System::DateTime::Now.ToString();
xloResult = toXl(clrString);

// Return a CLR date as a number
System::DateTime clrDate = System::DateTime::Now;
xloResult = toXl(clrDate);

ple::clr::objectToXl

Use objectToXl() to convert CLR values of unknown type to Excel return values.

objectToXl() handles most standard .NET types, either as scalar values or as arrays of 1 or 2 dimensions.

CopyC++
// Return a CLR object of unknown type
System::Object^ oResult = SomeClass::SomeMethod();
xloResult = objectToXl(oResult);

See the ClrDemo and AssemblyDemo samples for examples of the use of toClr() and toXl().

Next: Using WinForms from an add-in >>


Using WinForms from an add-in

To use WinForms classes from an add-in you need to add a reference to System.Windows.Forms.dll to your project.

  1. Open the Project Settings window.
  2. Select the page "Common Properties/References".
  3. Click "Add New Reference..." (and prepare for a potentially long wait).
  4. On the ".NET" page, select "System.Windows.Forms", and press "OK".

You may find it convenient to also add the following line to your main source file, which will save quite a bit of typing.

CopyC++
using namespace System::Windows::Forms;

To get access to a class that links XLL+ to the .NET Winforms classes, you should also add the following line to your main source file:

CopyC++
#include <xlpclrforms.h>

ExcelForm

The ExcelForm managed class acts as a link between Excel and WinForms (by implementing the interface IWin32Window). Create an ExcelForm object, and it will allow the Excel application window to act as the owner of a WinForms form.

CopyC++
// Call a WinForms method, using a new instance of
// the ExcelForm to create an IWin32Window interface
// for the main Excel application window.
MessageBox::Show(
    gcnew XllPlus::Forms::ExcelForm(),
    "Hello from .NET", ".NET message box",
    MessageBoxButtons::OK,
    MessageBoxIcon::Hand);

See the ClrDemo sample for an example of the use of ExcelForm.

Next: Deploying your .NET assemblies >>


Deploying your .NET assemblies

Calling your own .NET assemblies

You can call your own or 3rd-party .NET assemblies from add-in fuctions or event handlers.

It is a good idea, if possible, to add the C# or VB.NET project to your add-in solution (as we have in the AssemblyDemo sample). This lets you debug both sides at the same time: you can step from the C++ add-in into the .NET assembly and back again, seamlessly.

Referencing a .NET assembly

To call a .NET assembly from your add-in's C++ code, you must add a reference to your project.

  1. Open the Project Settings window.
  2. Select the page "Common Properties/References".
  3. Click "Add New Reference..." (and prepare for a potentially long wait).
  4. If your assembly is part of the current solution, use the "Projects" to select the project and press "OK".
  5. If the assembly is not part of your solution, then use the "Browse" page to navigate to the assembly.

Once the reference is added, a bonus is that Intellisense becomes available in your C++ code, which can save a lot of typing and errors.

Loading .NET assemblies

The XLL+ framework adds an event handler to the current AppDomain so that the add-in can specify the location of the .NET assembly to be loaded.

By default, the add-in looks in its own directory for any .NET assemblies. So, if you deploy your .NET assemblies (and any assemblies upon which they depend) to the same directory as your XLL file, you need not concern yourself any further with the details of assembly loading.

If your assemblies are deployed to a different location, then use CXllApp::SetPrivateBinPath() to set the list of directories that the loader will search. You should call SetPrivateBinPath in the XllOpenEx() event handler, before you call any methods from your assemblies.

CopyC++
BOOL CClrAddinApp::OnXllOpenEx()
{
    ...

    // Set up assembly loading
    // This will append "C:\Assemblies" to the assembly loader's search path
    SetPrivateBinPath(GetPrivateBinPath() + ";" + "C:\\Assemblies");

    ...
    return TRUE;
}

GAC

If your assemblies have been added to the Global Application Cache (GAC) then you do not need to concern yourself with the private bin path; your assemblies will automatically be loaded at run-time.

.NET runtime

You need to ensure that the machines on which your .NET-dependent add-ins are deployed are properly configured to run .NET add-ins under Excel. Please see the technical note .NET requirements for more information.

Next: Using the Excel object model >>


Using the Excel object model

Excel object model

While you can use the Excel C++ API to manipulate workbooks and their contents from add-in macros, it is often very hard work, and the range of options is limited.

The Excel object model is available from Visual Basic for Applications (VBA) macros written inside spreadsheets, and provides a complete and reasonably consistent and intuitive interface into Excel objects. Using XLL+ 6.0.4 upwards, you can access this model easily from add-ins.

Office Primary Interop Assemblies

This set of assemblies is the approved route for accessing Excel's object model (which is implemented using COM) via .NET. They are usually installed into the Global Assembly Cache (GAC) by the Visual Studio installer.

If you want to use the Excel object model, you need to add a reference to your project.

  1. Open the Project Settings window.
  2. Select the page "Common Properties/References".
  3. Click "Add New Reference..." (and prepare for a potentially long wait).
  4. On the ".NET" page, select "Microsoft.Office.Interop.Excel", and press "OK".

If you cannot find the assembly on the .NET page, then you may need to install it. Search the Microsoft web-site for Office Primary Interop Assemblies to find a downloable installer.

You may find it saves you a lot of typing if you also add the following line to your main source file:

CopyC++
using namespace Microsoft::Office::Interop::Excel;

Getting the Application object

Everything in the Excel object model is accessible via the Application object. You can get access to the application by using CXllApp::GetApplicationObject. The code fragment below assumes that you have added the statement using namespace Microsoft::Office::Interop::Excel; to your code.

CopyC++
_Application^ theApp = safe_cast<_Application^>(CXllApp::Instance()->GetApplicationObject());

Note that the earliest time you can call GetApplicationObject() is during the event handler OnXllOpenEx(). You can also call it during any add-in function or macro. You cannot call it during InitInstance() or during the constructor of any global objects.

Using the object model

Once you have a handle to the Application object, you can use it to access the hierarchy of Excel objects.

The code fragment below calls various objects, properties and methods of the Excel object model to create, format and populate a new workbook.

CopyC++
// Create a new workbook
theApp->Workbooks->Add(System::Reflection::Missing::Value);

// Create a range that points to the 4 cells in the top-left corner
_Worksheet^ ws = safe_cast<_Worksheet^>(theApp->ActiveSheet);
Range^ range = safe_cast<Range^>(ws->Cells[1, 1])->Resize[2, 2];

// Apply values and formats to the range
range->Interior->ColorIndex = 4;
range->Interior->Pattern = Constants::xlSolid;
range->Font->ColorIndex = 3;
range->Value2 = "A value";

// Select C3:D4
range->Offset[2, 2]->Select();

A number of points are worth noting here:

  • Missing values are represented by System::Reflection::Missing::Value. They cannot simply be omitted.
  • A number of properties in the Excel model, including Application.ActiveSheet and Range.Cells, return untyped objects. You need to use safe_cast to convert them to the appropriate interface.
  • Many methods are unexpectedly implemented as properties. Range.Resize is a commonly used example of this.
  • The class Microsoft::Office::Interop::Excel::Constants contains many of the Excel constants.

See the PiaDemo sample for an example of using the Excel object model in C++/CLI.

Next: Importing .NET assemblies >>


Importing .NET Assemblies

This chapter contains the following topics:

Importing .NET assemblies
Preparing to import
Imported Assemblies Window
Import Editor
Building and deployment
Using attributes


Importing .NET assemblies

XLL+ (6.2 and above) includes a set of tools to import a .NET assembly into an add-in. Point the tools at your assembly, and they will generate wrapper functions for you, with little or no assistance from you. Any public method or property of a .NET class can be exported as an Excel add-in function or macro.

Transformations

Suppose you have this class definition in C#:

CopyC#
public class MyClass
{
    public static string FormatDate(DateTime dt, string format)
    {
        return dt.Date.ToString(format);
    }
    public static string MostPopularMonth(DateTime[] dts)
    {
        // Omitted for brevity
    }
}

The XLL+ Reflector tools will generate 2 add-in functions as follows:

=FormatDate(dt, format)
=MostPopularMonth(dts)

Each of these functions will contain code to check the type of the inputs, convert them to .NET types, call the .NET method, handle any errors, and convert the results to Excel data types.

You can also specify a prefix, so that the add-in functions become, for instance:

=MyClass.FormatDate(dt, format)
=MyClass.MostPopularMonth(dts)

Comments

If you have added documentation comments to your C# code, they will be carried across to the Excel add-in function:

CopyC#
public class MyClass
{
    /// <summary>
    /// Converts a date to text, using a .NET formatting string
    /// </summary>
    /// <param name="dt">is a date/time value</param>
    /// <param name="format">is a .NET formatting string</param>
    public static string FormatDate(DateTime dt, string format)
    {
        return dt.Date.ToString(format);
    }
}

Objects

You can return objects from your .NET methods, and they will be represented in Excel as handles. You can then pass the handle to any method of the object that is exported as an add-in function.

For example, the two classes below include the factory method Factory.CreateThing(), which returns an object of type Thing, and the instance method Thing.GetInversion(), which returns some calculated information from a Thing object.

CopyC#
public static class Factory
{
    public static Thing CreateThing(string key, int value)
    {
        return new Thing(key, value);
    }
}
public class Thing : IDisposable
{
    public int GetInversion(int order, bool reversed)
    {
        // Omitted for brevity
    }
}

These could be exported as the following Excel add-in functions:

=Factory.CreateThing(key, value)
=Thing.GetInversion(thing, order, reversed)

Note that the first add-in function returns a handle value, and that the second function takes an extra first argument, which must be a handle to a Thing (such as that returned by Factory.CreateThing).

Next: Preparing to import >>


Preparing to import

To create a set of wrapper functions for a .NET assembly, there are 4 steps required:

  1. Create an XLL+ project that supports CLR.
  2. Add a reference to the assembly, in your project.
  3. Use the Imported Assemblies Window to mark the assembly for instance.
  4. Use the Import Editor to select which methods and properties will be exported as XLL Add-in Functions.

Create a project

When you create your XLL+ project you should make sure that it includes Common Language Runtime support, by ticking the appropriate check-box. See AppWizard - CLR Option for details.

It is also often a good idea to create a directory for the solution, with each project in a sub-directory. You can do this by putting a check against "Create directory for solution" in Visual Studio's "New Project" dialog.

Adding a reference

If you have the source code for the .NET assembly, it is often a good idea to add the assembly's project to the current solution. In Solution Explorer, select the Solution node (the root), right-click it, and click on "Add", then "Existing Project".

To add the reference, select the project node for your add-in in Solution Explorer, right-click it, and select "Properties". In the Project Property Pages, select the page "Common Properties/References". Click the "Add New Reference..." button and the Add Reference dialog will appear. (Be prepared, on occasion, for a very long wait.)

If you have added the .NET assembly as a project (as described above), then go to the Projects tab, select the .NET assembly project and press "OK". If you are just adding a reference to the DLL, then go to the Browse tab, navigate to the DLL, and press "OK".

Project references

There are three major advantages in adding a .NET assembly to your solution as a project rather than just a reference.

  • Visual Studio will use the Debug version of the assembly when linking the Debug build of your XLL. You will then be able to use the debugger to step from the C++ add-in code straight into your .NET code.
  • You can edit the .NET code directly, and rebuild your project instantly.
  • You can edit the documentation comments in the .NET code, and they will automatically be copied into the help text for your XLL wrapper functions.

Documentation File

If you added an assembly reference, and your .NET assembly has a documentation file, try to make sure that it is available in the same directory as the assembly's dll file. Then the .NET Import Wizard will be able to find it automatically, and will add some of its contents to the XLL, as help text.

If you added a project reference, then make sure that at least one of the configurations of the referenced .NET project (usually the Debug build) is set up to create a documentation file. In the "Project Properties" page, select the "Build" tab, and put a check against "XML documentation file" in the "Output" section near the end of the page.

Build the project

Build the project, and make sure that the imported assembly - along with its documentation file - has been successfully built.

You are now ready to import the assembly.

Next: Imported Assemblies Window >>


Imported Assemblies Window

Once you have added the assembly reference to your project, open the main C++ source file of your add-in project and use the Tools/Import Assemblies... command from the XLL AddIns window to display the Imported Assemblies Window.

All the .NET references for your project will be listed on the left hand side of the wizard. Put a check against each assembly for which you want to generate wrappers.

For an assembly reference, if you have been provided with a configuration file for the .NET assembly, and it is not in the same directory as the DLL, then you should use the "Documentation" field to navigate to the file.

If you select an assembly to be imported, the tool will update your project settings, adding 2 new files. One is a control file, [assembly-name].import.xml, which will be used by the code generator, and the other is the generated C++ file, [assembly-name]_Wrappers.cpp, which will contain the wrapper functions.

Once you have put a check next to an assembly, use the Edit button to select which methods and properties will be exported as XLL add-in functions.

Next: Import Editor >>


Import Editor

The Import Editor pops up when you click the Edit button in the Imported Assemblies Window. The editor shows a graph of all the exportable methods and properties in the imported assembly.

The methods can be viewed in a tree or in a list. Use the tool-buttons on the top left hand toolbar to switch between Tree View and List View.

Using the tree view, you can apply settings at the assembly level or at the type level, and these will apply to all methods and properties in the types affected. For instance, you could set the Category property at assembly level to Math & Trig to set the category of all exported methods. Or you could set the Filter property of a Type to StaticMethods to ensure that all the type's eligible static methods will be exported.

Using either the tree view or the list view, you can also apply settings to individual methods and parameters, controlling exactly how they are exported as Excel add-in functions and arguments.

You can control many aspects of the function's behaviour and how the arguments are treated, including:

  • Function name in Excel
  • Function category
  • Argument names
  • Default values for omitted arguments
  • Array handling rules for arguments
  • Help text

When you are happy with the import settings for the assembly, click OK to save your changes and return to the Imported Assemblies Window. You can change the settings at any time, by returning to the Import Editor.

In the Imported Assemblies Window, click "OK" and the tool will update your project settings, and save all affected files.

Build your project, and the wrapper functions will be generated and built.

Next: Building and deployment >>


Building and deployment

Project structure

XLL+ adds new items to your Visual Studio project, in order to implement the import process.

The first added item is an XML file, MyLib.import.xml. This contains instructions on how to import the assembly. When the item is "compiled", the XLL+ Reflector tool is invoked, which:

  1. reads the command line arguments from MyLib.import.xml;
  2. loads up any detailed import instructions that you saved using the Import Editor (from a file named MyLib.xnr);
  3. loads the imported assembly MyLib.dll and reads all its members using reflection;
  4. generates C++ wrapper functions and writes them to MyLib_Wrappers.cpp.

MyLib_Wrappers.cpp is the output of MyLib.import.xml, and therefore it is regenerated whenever MyLib.import.xml is updated. There are are also two "Additional Dependencies" registered with Visual Studio: MyLib.dll and MyLib.xnr. As a result, the C++ code is automatically regenerated whenever the imported .NET DLL is changed and rebuilt, and whenever you use the Import Editor to change the detailed import instructions.

The second item added is MyLib_Wrappers.cpp, which is treated as a standard C++ source file and is compiled and linked into the XLL like any other C++ source file.

Deployment

The following issues are important when running or deploying your XLL add-in.

  1. Your XLL add-in must be able to locate and load the .NET assembly (and its dependent assemblies). See Deploying your .NET assemblies for details.
  2. Excel needs to load the correct version of the .NET run-time. See Loading the correct .NET runtime version for instructions.

Failure to address either of these issues may result in the XLL failing to load and a "This file is not in a recognizable format" message appearing.

Next: Using attributes >>


Using attributes

If you use the Import Editor to control the import of methods from your assembly, your settings are saved in an instruction file, [assembly-name].dll.xnr. The settings are read in by the import tool when the application is built.

As an alternative, you can apply attributes directly to your .NET classes and methods.

You can add atributes to your .NET method to control many aspects of the function's behaviour and how the arguments are treated, including:

  • Function name in Excel
  • Function category
  • Argument names
  • Default values and array handling for arguments
  • Help text

For example, some XLL+ import attributes have been added to the C# code below:

CopyC#
[XllFunction]
public static string TestFunction(string a, double b, int c, bool d)
{
    return String.Format("a={0};b={1};c={2};d={3}",
        a, b, c, d);
}

[XllFunction("AddTwoNumbers")]
public static int MyAdd(
    [XllArgument("First", Flags=XlArgumentFlags.Optional, DefaultValue="100")]
    int a,
    [XllArgument("Second", Flags=XlArgumentFlags.Optional, DefaultValue="-99")]
    int b)
{
    return a + b;
}

List of Attributes

The table below lists the main attributes:

Attribute | Description
XllFunction | Controls the export of a specific method or property as an Excel add-in function.
XllArgument | Controls the export and marshalling of a single argument of an exported Excel add-in function.

For full details see the .NET Runtime Library Reference.

Using Attributes

To use attributes in an existing .NET library, follow these steps:

  1. Add a reference to the XLL+ Reflection Runtime library, Psl.XL6.XnReflect.Runtime.dll. This is located in the bin subdirectory of the XLL+ installation folder.

  2. Optionally, add a using statement to your C# code:

    using XllPlus;

  3. Add a XllFunction attribute to any functions that you wish to export to Excel.

  4. Add XllArgument attributes to any arguments that need special handling.

  5. Ensure that your project generates an XML documentation file, and make sure that the comments for all exported functions are up to date.

Inspect the NetWrapAttr walkthrough for more details on how to import a .NET assembly using attributes.

Next: Sized result arrays >>


Sized result arrays

Why do we need to know the size of the caller?

There are several reasons why you may need to know the size of the range from which an array formula is being called.

Misfitting array formulae

If an add-in function returns an array result to a range of cells containing a formula array, it may not be the right size. If the result does not fill the range, then Excel will pad the result with cells containing #N/A!. If the result is too large for the range, then it will be truncated.

You may wish to indicate to the user that truncation has occurred, or you may wish to fill any unused area with blanks.

Repeated vectors

A problem arises if the range containing a formula is two-dimensional, and the returned array is one-dimensional. Excel will repeat the result vector in each row or column of the range.

Fill formulae

You may wish to precisely fill the range containing the formula, for instance with test data, or a set of random numbers.

CXllApp::GetCallerDims

The static method CXllApp::GetCallerDims() can be used to get the dimensions of the range from which the current function was called. The method returns FALSE if the current function was not called from a cell range.

The code below demonstrates how to fill a range precisely.

CopyC++
CXlOper* INTERPFILL_Impl(CXlOper& xloResult, double Start, double End)
{
    // End of generated code
//}}XLP_SRC
    // Get the dimensions of the cell range
    size_t nRows, nCols;
    if (!CXllApp::GetCallerDims(nRows, nCols))
    {
        // We're not being called from a cell range
        throw CXlErrorException(xlerrNA);
    }

    // Calculate the interval between points
    double dAdd = 0.0;
    if (nCols * nRows > 1)
        dAdd = (End - Start) / (double)((nCols * nRows) - 1);

    // Allocate an output range of just the right size
    xloResult.AllocArray(nRows, nCols);

    // Fill each cell, incrementing the value at each cell
    double dValue = Start;
    for (size_t i = 0; i < nRows; i++)
    {
        for (size_t j = 0; j < nCols; j++, dValue += dAdd)
        {
            xloResult.Cell(i, j) = dValue;
        }
    }
    return xloResult.Ret();
}

The example makes use of the exception class CXlErrorException to abandon the function if the caller is not appropriate.

Next: Events overview >>


Advanced Features

This chapter contains the following topics:

Events
Volatile functions
Extended types
Function extensions
Object handles
Groups
Choice arguments
Publishing and suppressing add-in functions
Favorite arguments
International support
Asynchronous functions
Queued functions
CUDA
Logging
Hidden regions
Security settings
Trouble-shooting topics


Events

This chapter contains the following topics:

Events overview
XllOpen & XllClose events


Events overview

In version 6 of XLL+, a unified event model has been introduced. This model makes it straightforward to catch interesting events in the life of Excel, and react to them. Some of these events are listed below:

XllOpen
The XLL itself is being opened by Excel. This is a good time to do initialization and authorization.
XllClose
The XLL itself is being closed. This is the time to close and release resources used by the XLL.
NewWorkbook
A new workbook has been created. If there is code you wish to run against all new workbooks, do it here.
WorkbookOpen
An existing workbook has been opened. This is a good time to check the state of a woprkbook, and perhaps to update data that is controlled by states outside the workbook itself.
Calculate
A worksheet has been recalculated. This is often a good time to deal with external data, such as that represented by handles.

Observer pattern

The event model uses the standard Observer pattern. An instance of an observer class is created, and it is attached to the event using CXlEvent::Register. While the observer is attached, its virtual method Update will be called whenever the event occurs.

The observer can be disconnected from the event by calling CXlEvent::Unregister.

Event arguments

Different events have different event data associated with them. For example, the WorkbookOpen event passes the name of the workbook, while the WorksheetChanged event passes a range on a worksheet.

The base observer class is implemented as a template class, and the type of event argument is used as a parameter to the class.

CopyC++
template<class EventArgsType>
class CXlEventObserver {
public:
    CXlEventObserver() { }
    virtual void Update(EventArgsType* e)=0;
};

So, for example, observers of the WorkbookOpen event are of type CXlEventObserver<CXlWorkbookEventArgs>. Whenever the event occurs, an argument of type CXlWorkbookEventArgs is passed to the observer's Update method.

See the class reference for each of the events for details of the appropriate event argument class.

Coding event observers

Here is an example of observing the Calculate event:

CopyC++
class CMyCalculateObserver : public CXlEventObserver<CXlWorksheetEventArgs> {
protected:
    virtual void Update(CXlWorksheetEventArgs* e)
    {
        // Do something
        TRACE("Worksheet %s has been recalculated\n",
            (LPCSTR)e->GetSheetName());
    }
};
CMyCalculateObserver calculateObserver;

// Register the observer
CXllApp::Instance()->CalculateEvent().Register(&calculateObserver);

// Unregister the observer
CXllApp::Instance()->CalculateEvent().Unregister(&calculateObserver);

The steps are:

  1. Create an observer class, derived from CXlEventObserver<T>, where T is the type of the event's arguments.
  2. In the observer class's Update method, put the code that reacts to the event.
  3. Create an instance of the observer class.
  4. Connect the observer to the event by calling CXlEvent::Register.

Static observers

You can skip much of the work by using a static observer class. If you derive your observer class from a static observer base class, then it will automatically be registered at the appropriate time and unregistered when the XLL closes.

CopyC++
class CMyCalculateObserver2 : public CXlCalculateEventStaticObserver {
protected:
    virtual void Update(CXlWorksheetEventArgs* e)
    {
        // Do something
        TRACE("Worksheet %s has been recalculated\n",
            (LPCSTR)e->GetSheetName());
    }
};
CMyCalculateObserver2 m_calculateObserver2;

In this case, the instance m_calculateObserver2 does not need to be registered. It will be done automatically when the add-in is opened, and the observer will be unregistered when the add-in is closed.

You can find a list of static observer classes in the Class Reference.

Next: XllOpen & XllClose events >>


XllOpen & XllClose events

XllOpen & XllClose are the events you'll most often need to catch. The virtual functions CXllApp::OnXllOpenEx and CXllApp::OnXllClose are provided to make these events easier to handle. Usually, putting your XLL initialization code into OnXllOpen, and your termination code into OnXllClose is the easiest and simplest way to go.

Occasionally, however, you may prefer to use the observer model for these events. For example, The framework uses the event model to "wire up" some methods that support more complex function features, such as Asynchronous functions. (This is largely because the XLL+ Function Wizard inserts and controls code in the cpp file, but does not have control of the header file.)

A pattern for Open/Close events

The code below is a typical pattern for using the open & close events to manage a global resource, such as a database connection.

CopyC++
CMyResource theResource;

class CMyResourceOpen : public CXllOpenEventStaticObserver {
    virtual void Update(CXllOpenEventArgs* e)
    {
        try
        {
            theResource.Open();
        }
        catch(...)
        {
            // Inform user
            CXllApp::MessageBox("Failed to open resource...", 1);
            // Cancel the open event
            e->SetCancel(true);
        }
    }
};
class CMyResourceClose : public CXllCloseEventStaticObserver {
    virtual void Update(CXllOpenEventArgs* e)
    {
        theResource.Close();
    }
};

Next: Volatile functions >>


Volatile functions

External data

Most Excel add-in functions have no dependencies other than their inputs. So, for example, a formula =FunctionOf(A, B, C) depends only on the values of A, B and C; nothing else can affect the result of the function. So long as A, B and C remain unchanged, there is no need to recalculate the formula.

The efficiency of Excel's recalculation depends on this assumption: cells are only recalculated when they need to be, which greatly improves response time.

However, some functions depend on external inputs, which are not passed as inputs to the function. The most obvious example is the Excel built-in function NOW().

Volatile Functions

Functions such as these are defined as Volatile. A cell containing a volatile function is recalculated whenever Excel recalculates any cell on the same worksheet, or whenever the user presses the F9 key, even if none of its inputs have changed.

Marking functions as volatile is a standard solution, but potentially it can be very expensive. Even if the value you return from a volatile function is unchanged, Excel will assume that it has changed, and will recalculate all cells which depend on the volatile cell. If those dependent cells contain slow expensive calculations, you can find yourself doing a long recalculation every time any cell is changed.

A function that uses external data

As an example of a volatile function, let us create a function that uses external data.

Open Tutorial1.cpp, and use the XLL+ Function Wizard to add a new function, STOCKNAME. Set the function's attributes as follows.

Name: STOCKNAME
Return type: CXlOper
Category: Equities
Description: Look up a stock code and return the company name

Notice that we've created a new category, Equities, which will now appear in Excel's Formula Wizard.

Add an argument, as follows:

Type: String
Name: Code
Description: Stock code

Make the function volatile

Finally, click on the Volatile check-box on the Features tab, as shown below.

By marking the function as volatile, we are instructing Excel to recalculate the formula every time the worksheet containing it is recalculated. Because STOCKNAME depends on data that is outside Excel's control (in this case, an in-memory database), we must always assume that this external data has changed since we last called the function, and recalculate the function.

Create the application "database"

Back in Visual Studio, add a simplistic in-memory database to the class definition in Tutorial1.h:

CopyC++
        #include <map>

class CTutorial1App : public CXllApp
{
public:
    CTutorial1App();

// Names
public:
    static LPCSTR m_pszDefName;

// Data
    std::map<CString, CString> m_mapStockNames;
    void InitStockCodeMap();
    BOOL FindStockCode(const char* pszCode, CString& strCompanyName);

// Overrides
    ...
};

In Tutorial1.cpp, add the implementation code:

CopyC++
// Initialise an application-level in-memory database
void CTutorial1App::InitStockCodeMap()
{
    // In a real application, these codes would be loaded from a database
    static const char* apszStockPairs[] = {
        "MSFT", "Microsoft",
        "ORCL", "Oracle",
        "IBM",  "International Business Machines",
        0
    };

    // Clear the map then add each pair
    m_mapStockNames.clear();
    for (int i = 0; apszStockPairs[i]; i += 2)
        m_mapStockNames[apszStockPairs[i]] = apszStockPairs[i + 1];
}

// Look up a stock code
// Returns FALSE if not found, TRUE if found
BOOL CTutorial1App::FindStockCode(const char* pszCode, CString& strCompanyName)
{
    std::map<CString, CString>::const_iterator itF = m_mapStockNames.find(pszCode);
    if (itF == m_mapStockNames.end())
        return FALSE;
    strCompanyName = itF->second;
    return TRUE;
}

We need to make sure that the "database" is initialized, so add a call to InitStockCodeMap() to OnXllOpen():

CopyC++
BOOL CTutorial1App::OnXllOpenEx()
{
    ...
    InitStockCodeMap();
    return TRUE;
}

Use the application data

Finally, change the generated code as shown below:

CopyC++
CXlOper* STOCKNAME_Impl(CXlOper& xloResult, const CXlStringArg& Code)
{
    // End of generated code
//}}XLP_SRC

    // Look up the code and return the company name or #N/A!
    CString strCompanyName;
    if (XllGetTypedApp()->FindStockCode(Code, strCompanyName))
        xloResult = strCompanyName;
    else
        xloResult = xlerrNA;

    return xloResult.Ret();
}

This is a standard pattern for a function that uses application-level data.

  1. Get a pointer to the application object, using ::XllGetTypedApp().
  2. Delegate the business logic to the application object (in this case, by calling the application object's FindStockCode() function).
  3. Put the result into the result CXlOper.

The add-in function is now complete and ready for testing.

Next: Extended types introduction >>


Extended types

This chapter contains the following topics:

Extended types introduction
XLL+ extension files
Using an extended type
Converter class
Creating an extended type
Parameters


Extended types introduction

Extended types

The built-in data types that you can choose for your arguments are limited to simple types, such as Double, String, Boolean or Integer (and arrays of those types).

You can register your own types, with their own validation code, and these types will become available in the Function Wizard and the XLL Add-ins window, along with the built-in types.

When you select the extended type, the input from Excel will be validated and converted to the target type, without the need for the developer to write any validation or conversion code.

A Date type

For example, Excel treats dates and numbers interchangeably (except that it can display dates in a friendly manner). So when your function receives a date value, it is passed as double. The integer part of the value represents the date, and the fractional part represents the time of day.

You own code may handle dates as integers, perhaps of type long. A useful date type might do the following for a date argument ValueDate:

  1. Declare a local target variable

    CopyC++
    long ValueDate;
  2. Check that the input is a legitimate date (e.g. a number greater than 30000, representing a date value after 18 February 1982), and return an error if it is not.
  3. Set the local variable ValueDate to the date value.
  4. Perhaps add a constant to the date value to account for a different base date to Excel's.

All this can easily be achieved by creating and registering a scalar extended type.

Loading an extension file

An extended type is defined in an extension file, and is loaded using the XLL+ Options - Extensions page. Extension files have the file extension xpe.

Let us load up a pre-defined date type.

  1. From the XLL Add-ins window, use the "Tools/Manage Extensions" command to open the "XLL+ Options / Extensions" window.

    Altenatively, use the Visual Studio Tools/Options menu command to show the Options dialog. In the tree on the left, select the node "XLL+ / Extensions".

  2. Click on the "Add" tool to select an extension file to be registered.

  3. Navigate to the "extensions" sub-directory of the XLL+ installation directory (e.g. C:\Program Files\Planatech\XllPlus\6.0\VS8.0\extensions), select date.xpe and press the Open button.

  4. The file will be added to the list of loaded extension files, as shown below.

Next: XLL+ extension files >>


XLL+ extension files

Testing and examining an extension file

To validate the extension file, click on the Test button. A report window should appear, confirming that one file was loaded without errors. Close the window.

Examine the loaded types by pressing the View button. This will show a list of all the extensions in the list. In the tree on the left, select the node "Scalar types/Date".

Notice that all the properties in the list on the right are in grey, meaning that they are read-only: you can't edit the extended types here, only look at them. (To edit a type, you need to work with the definition file, as we will do in a moment.)

Let us examine some of the more important properties of the type:

Name

The name of the extension (in our case "Date") is the identifier for the type within the XLL+ code generation system. It must not conflict with the names of any built-in types or of other extended types.

CppType

This is the type of the target variable, which in our case is long.

NativeType

This is the type used to store the value within Excel; in our case, Double.

ConverterType

The ConverterType holds the name of the C++ class which will do the work of converting and validating the input. For this example, the class is psl::DateConverter.

HeaderFiles

HeaderFiles holds a list of C++ header files which will be needed in order to compile the generated code. In our case, it is the file extensions\DateConverter.h, which contains the definition of the converter class, psl::DateConverter.

The Extension File

Next, let's examine the file itself. Close the XLL+ Extensions window, if it is still open, and use the Edit button in the XLL+ Options / Extensions page to open up the extension file in the Visual Studio editor.

Click the OK button to close the Options dialog and save your changes.

Like the Help file, the extension file has a schema which provides the user with:

  • Syntax checks
  • Intellisense
  • Popup help

Locate the <ScalarType> element. All the important definitions are contained in its attributes:

CopyXML
<ScalarType name="Date" cppType="long" excelType="Double"
            converterType="psl::DateConverter" optionalAllowed="true"
            headerFiles="extensions\DateConverter.h">

The <ScalarType> element also contains a <LocalizedDisplayName> element and a <LocalizedDescription> element. These elements control the display of localized help and identifiers in the XLL+ Function Wizard. If all your developers use the same language then these can be safely omitted.

For more details of the extension file format, examine the full schema of the XLL+ extension file in the reference.

Next: Using an extended type >>


Using an extended type

Selecting an extended type

If we now return to the XLL+ Function Wizard, we will find that the Date type has been added to the list of available argument types.

Code generated for an extended type

Let us examine the code that is generated for a date type:

CopyC++
CXlOper* DateFn_Impl(CXlOper& xloResult, double ValueDate_op)
{
    // Input buffers
    long ValueDate;
    // Validate and translate inputs
    XlReadScalarEx(ValueDate_op, ValueDate, psl::DateConverter(), L"ValueDate");
    // End of generated code

The validation function is slightly different from what we have seen before.

  1. The function is named XlReadScalarEx instead of XlReadScalar.
  2. The function takes an extra argument, a newly created instance of psl::DateConverter.

You will recall that this was the value of the extended type's ConverterType property.

The other change is that we now have a local variable ValueDate of the reqired date type, long.

When the ValueDate argument is validated at run-time, we see some new behavior. If the argument is a number less than 30000, we get the error result:

#ERROR: Expected date for ValueDate

Arrays of extended types

We can just as easily handle arrays of extended type values. For example, we could have a vector input PaymentDates:

This code is generated:

CopyC++
// Input buffers
std::vector<long> PaymentDates;
// Validate and translate inputs
XlReadVectorEx(*PaymentDates_op, PaymentDates, psl::DateConverter(),
    L"PaymentDates", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK);
// End of generated code

The local variable PaymentDates is of type std::vector<long>, as is required.

Next, we will examine the converter class, since that is where all the work appears to be happening.

Next: Converter class >>


Converter class

The converter class can be found in the header file extensions\DateConverter.h. If you examine your source code file after you have inserted a Date type, you will find that the following line has been inserted near the top of the code:

CopyC++
#include "extensions\DateConverter.h"

The file is located in the extensions sub-directory of the XLL+ include directory.

Let us first look at the whole class:

CopyC++
class DateConverter : public CXlUserConverterBase<long, double>
{
private:
    typedef long ElemType;
    typedef double XlNativeType;
public:
    virtual bool ConvertFromExcel(const XlNativeType& xlValue,
        ElemType& outerValue, const ParamsType& params) const
    {
        if (!CheckDateValue(xlValue))
            return false;
        outerValue = (long)xlValue;
        return true;
    }
    virtual bool ConvertToExcel(const ElemType& outerValue,
        XlNativeType &xlValue, const ParamsType& params) const
    {
        if (!CheckDateValue((double)outerValue))
            return false;
        xlValue = (double)outerValue;
        return true;
    }
protected:
    virtual std::string GetTypeName(const ParamsType& params) const
    {
        return "date";
    }
private:
    static bool CheckDateValue(double value)
    {
        return value >= 30000.0 && value <= (double)LONG_MAX;
    }
};

The salient points of the class are:

  1. It is derived from a template class:

    CopyC++
    CXlUserConverterBase<long, double>

    All converter classes are derived from CXlUserConverterBase<ElemType, XlNativeType>, where ElemType is the type of the target C++ variable and XlNativeType is one of Excel's native data types.

  2. The virtual function ConvertFromExcel() is implemented. This method is called by the extended type validation function, XlReadScalarEx. ConvertFromExcel returns true if it succeeds, and false if it fails. If it succeeds, the XlNativeType input is converted to the ElemType output. This virtual function must always be implemented.

Two other methods are implemented:

  1. ConvertToExcel() does the reverse conversion, converting a date to an Excel number. This method is not required, but it is useful if, for instance, you want to return a vector or matrix of dates to Excel. You can use the global methods XlWriteScalarEx, XlWriteVectorEx and XlWriteMatrixEx to convert an extended type (or a vector or a matrix of extended types) into a CXlOper which can be returned to Excel.

  2. GetTypeName() returns the name of the type, "date", which will be used in error messages.

Next: Creating an extended type >>


Creating an extended type

To understand extended types more fully, let us create a new extended type, an ISO currency code.

Converter class

What we want the converter class to do is:

  1. Check that the input is a valid ISO currency code.
  2. Set the target value to be the upper-case ISO code.

You can find all the code described below in the ExtendedTypes sample, under the XLL+ Samples directory.

The header file

The first step is to create a new header file, CurrencyConverter.h, and add the following two lines:

CopyC++
#pragma once
#include <xllplus.h>

The header file should be saved in a directory available to the compiler: either the local directory for the current project, or a directory on the INCLUDE list.

Class declaration

Next, derive the class from CXlUserConverterBase and select the appropriate template arguments. The input and output are both strings, so we can use CString for both:

CopyC++
class CurrencyConverter : public CXlUserConverterBase<CString, CString>
{
private:
    typedef CString ElemType;
    typedef CString XlNativeType;
};

The typedef statements are not strictly necessary, but they make it easier to copy code from existing classes.

ConvertFromExcel method

The first and most important method is ConvertFromExcel. We need to do 2 things:

  1. Validate the input and return false if validation fails.
  2. Put the converted result into outerValue and return true, if validation succeeds.

The code looks like this:

CopyC++
virtual bool ConvertFromExcel(const XlNativeType& xlValue,
    ElemType& outerValue, const ParamsType& params) const
{
    // Look up the code, case-insensitive
    const TCHAR* code = FindCode(xlValue);
    if (code == 0)
        return false;
    // Set the output to be the upper-case code
    outerValue = code;
    return true;
}

We will also need the implementation of FindCode. Here is a simplistic model:

CopyC++
class CurrencyConverter : public CXlUserConverterBase<CString, CString>
{
    ...
private:
    const TCHAR* FindCode(const TCHAR* input) const
    {
        static const TCHAR* codes[] = {
            _T("CAD"),
            _T("CHF"),
            _T("EUR"),
            _T("GBP"),
            _T("JPY"),
            _T("USD"),
            0
        };
        for (int i = 0; codes[i]; i++)
            if (_tcsicmp(input, codes[i]) == 0)
                return codes[i];
        return 0;
    }
};

Generic-text mappings

You'll notice that the character types are declared as TCHAR and the _T(...) macro surrounds all string literals.

This means that the code will build and run correctly under both Unicode and standard builds. It's a bit of extra work, but even if you don't use Unicode yourself, if your extension is likely to be used by other developers it's worth getting it right the first time.

If you know that Unicode is not and will not be an issue, then you can use char instead of TCHAR, _strcmpi instead of _tcsicmp, and omit the _T(...) macro.

Error messages

The final thing we need to do in the converter class is to support error messages, such as:

#ERROR: Expected a currency code for CcyCode
#ERROR: Expected 4 currency codes for PaymentCurrencies

We need to provide the fragments "currency code" and "currency codes" to the framework so that they can be inserted into error messages.

There are three ways to do this:

  1. Implement GetTypeMessageId(). This technique is the most work, but supports multiple user languages. You need to put a string into the resource file, and return the string ID in GetTypeMessageId().

  2. Implement CXlUserConverterBase_GetTypeNameW(). You should return the Unicode string L"currency code".

  3. Implement CXlUserConverterBase_GetTypeName(). You should return the standard strings "currency code".

Let us implement the standard string version, as follows:

CopyC++
class CurrencyConverter : public CXlUserConverterBase<CString, CString>
{
    ...
    virtual std::string GetTypeName(const ParamsType& params) const
    {
        return "currency code";
    }
    ...
};

The whole class

Let's see the whole header file:

CopyC++
#pragma once
#include <xllplus.h>

class CurrencyConverter : public CXlUserConverterBase<CString, CString>
{
private:
    typedef CString ElemType;
    typedef CString XlNativeType;
public:
    virtual bool ConvertFromExcel(const XlNativeType& xlValue,
        ElemType& outerValue, const ParamsType& params) const
    {
        // Look up the code, case-insensitive
        const TCHAR* code = FindCode(xlValue);
        if (code == 0)
            return false;
        // Set the output to be the upper-case code
        outerValue = code;
        return true;
    }
protected:
    virtual std::string GetTypeName(const ParamsType& params) const
    {
        return "currency code";
    }
private:
    const TCHAR* FindCode(const TCHAR* input) const
    {
        static const TCHAR* codes[] = {
            _T("CAD"),
            _T("CHF"),
            _T("EUR"),
            _T("GBP"),
            _T("JPY"),
            _T("USD"),
            0
        };
        for (int i = 0; codes[i]; i++)
            if (_tcsicmp(input, codes[i]) == 0)
                return codes[i];
        return 0;
    }
};

The extension file

Now we need to plug the extension into the XLL+ development tools, using an XLL+ extension file.

Tip: The easiest way to do this is to copy an existing file and then change it to suit your needs. That way you get the right format and schema declarations, which make it much simpler to edit.

The file looks like this:

CopyXML
<?xml version="1.0" encoding="utf-8"?>
<Extensions xmlns="http://schemas.planatechsolutions.com/xlp/601/xt">
  <ScalarTypes>
    <ScalarType name="Currency"
                cppType="CString"
                excelType="String"
                converterType="CurrencyConverter"
                optionalAllowed="true"
                headerFiles="CurrencyConverter.h">
    </ScalarType>
  </ScalarTypes>
</Extensions>

See CXlUserConverterBase - XlNativeType for a list of the mappings between excelType in the definition file and XlNativeType in the class definition.

Save the extension file in an appropriate directory with a name such as Currency.xpe.

Using the extension

Register the extension by adding the extension file to the list in the XLL+ Options/Extensions page.

A new Currency type now appears in the argument type drop-down in the XLL+ Function Wizard. Code is generated for currency arguments, like the following:

CopyC++
// Input buffers
CString Ccy1;
// Validate and translate inputs
XlReadScalarEx(Ccy1_op, Ccy1, CurrencyConverter(), L"Ccy1");
// End of generated code

For vectors of currencies, code like this is generated:

CopyC++
// Input buffers
std::vector<CString> Ccys;
// Validate and translate inputs
XlReadVectorEx(*Ccys_op, Ccys, CurrencyConverter(), L"Ccys",
    XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK);
// End of generated code

If a currency is not recognized, then an error message such as the following is returned:

#ERROR: Expected currency code for Ccy1

Examples

For more examples of extended types see the files in the extensions directory (and their matching header files in include\extensions).

Next: Parameters >>


Parameters

The extended types we have looked at so far are simple to use. Some other extended types may need extra information in order to work. For example, we might add a FixedLengthString type, which will reject a string that is not of a certain length. The developer needs to be able to specify what the required length actually is, and this can of course vary for different arguments.

The solution to this issue is to add a Parameter to the extended type's definition.

FixedLengthString extended type

Use the XLL+ Options/Extensions page to load the file FixedLengthString.xpe from the XLL+ extensions sub-directory (as described in Extended types).

Use the View button to examine the type in the XLL+ Extensions window.

Observe that the type has a parameter, Length, which is defined as an integer. The parameter has the property AvailableAtRuntime set to true, so it's value will be passed to the converter class.

In Visual Studio, create a new add-in function and add an argument of type FixedLengthString. A new column appears in the XLL+ Function Wizard, to let you specify the Length parameter.

The code generated for a type with parameters is more complex than the usual code.

CopyC++
CXlOper* StringFn_Impl(CXlOper& xloResult, const CXlStringArg& Product_op)
{
    // Input buffers
    CString Product;
    // Validate and translate inputs
    XlReadScalarEx(Product_op, Product, FixedLengthStringConverter(),
        CScalarConvertParams<CString>(L"Product", 0, 0, -1).SetIntParam(0, 4));
    // End of generated code
//}}XLP_SRC
    ...
}

The Wizard has generated code that passes the value of the Length parameter to the validation function, by calling SetIntParam(0, 4), i.e. setting the value of the first integer parameter to 4.

Open up FixedLengthStringConverter.h in the XLL+ include\extensions sub-directory, and you can see how the parameter value is used:

CopyC++
class FixedLengthStringConverter : public CXlUserConverterBase<CString, CString>
{
public:
    virtual bool ConvertFromExcel(const CString& xlValue, CString& outerValue,
        const ParamsType& params) const
    {
        if (xlValue.GetLength() != params.GetIntParam(0))
            return false;
        outerValue = xlValue;
        return true;
    }
protected:
    virtual std::string GetTypeName(const ParamsType& params) const
    {
        char buf[128];
        _snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, "%d-character string",
            params.GetIntParam(0));
        return buf;
    }
    ...
};

The parameter value is used in two places:

  1. It is compared to the length of the string argument received from Excel.
  2. It is used to compose the type name for error messages.

If the input fails the length test, an error message like the following is returned:

#ERROR: Expected 4-character string for Product

Examples

For more examples of extended types with parameters see the files in the extensions directory (and their matching header files in include\extensions).

Next: Function extensions >>


Function extensions

You may have some standard code that you use in most or all of your add-in functions. You can transfer responsibility for writing the code to the XLL+ code generator by writing and registering a Function extension.

Typical uses of function extensions include:

  • Writing usage information to a log.
  • Selectively allowing only certain classes of user to access certain add-in functions.
  • Handling exceptions.
  • Tracing entry and exit points of functions to track down the irritating errors that occur only in release builds and not in debug builds.

Behavior of a function extension

When a function extension is registered, it appears in the XLL+ Function Wizard and in the Properties window, as an option that can be applied to any add-in function.

For example, if we register an extension named Trace, which writes to the debug console every time a function is used, we can see it in the function's Features list.

If we put a check against it, then additional lines will be injected into the generated code:

CopyC++
CXlOper* StringFn_Impl(CXlOper& xloResult, const CXlStringArg& Product_op)
{
    TRACE(_T("Entering StringFn\n"));
    // Input buffers
    CString Product;
    // Validate and translate inputs
    XlReadScalarEx(Product_op, Product, psl::FixedLengthStringConverter(),
        CScalarConvertParams<CString>(L"Product", 0, 0, -1).SetIntParam(0, 4));
    TRACE(_T("Validated StringFn\n"));
  // End of trace
    // End of generated code
//}}XLP_SRC
    ...
}

If at a later time you want to remove the extra code, you can use the Function Wizard or the Properties window to turn the extension off.

Code injection

Extension code can be injected at various places in an add-in function.

Insertion point | Description
BeforeValidation | At the start of the common implementation function, before any validation code is called.
AfterValidation | In the common implementation function, immediately after all validation code has been called.
BeforeTryCatch | At the start of each wrapper function before the try-catch block that calls the common implementation function.
AfterCatchException | In each wrapper function, after the try-catch block that calls the common implementation function. (This is a good place to catch exceptions that are not derived from CXlRuntimeException.)
BeforeMacro | Outside any function definition, in a global context, just before the IMPLEMENT_XLLFN3 macro.
AfterMacro | Outside any function definition, in a global context, just after the IMPLEMENT_XLLFN3 macro, and before the wrapper functions.

In the example above, TRACE statements were injected at BeforeValidation and AfterValidation.

Syntax

The full syntax of function extensions can be found in the reference here.

The critical part of the extension's definition is the code that is to be injected. You can use macros that will be substituted by the code generation engine, and allow you to generate data that is specific to the add-in function being extended.

For example, the Trace extension above uses the add-in function's name:

CopyC++
TRACE(_T("Entering $#ExportedName$\n"));

The generator will replace $#ExportedName$ with the value of the add-in function's ExportedName property.

You can find a list of function properties in the reference.

Examples

See the Profiling sample for an example of a function extension in action.

For more examples of function extensions see the files in the extensions directory.

Next: The need for object handles >>

See Also

Profiling sample


Object handles

This chapter contains the following topics:

The need for object handles
Using object handles
How handles work
Requirements and deployment
Combining handles with other features
Custom handle formats
Persistent object handles
Other handle implementations
Specifying a smart pointer type
Sharing object handles between XLLs


The need for object handles

Many programmers wish to be able to hold objects in memory and access them from Excel worksheets. A calculation may produce a vast amount of data, including for example:

  • multiple results;
  • arrays that are too large to display in Excel; and
  • diagnostic results.
The developer may wish to represent the entire object in Excel by a "handle" of some kind, and then use "getter" functions to inspect the data contained in the object.

For example, a function MonteCarlo(...) may produce a final value, statistical measures indicating the certainty of the value, a very large series of random numbers used by the calculation, and performance figures that show the cost of the calculation. The entire result set can be placed in an object, and exposed in Excel as a numeric handle to the object.

Thus the main function, MonteCarlo(...) returns a string, which is a handle to the result set. Various getter functions, such as MonteCarlo.Value(handle), MonteCarlo.MaxValue(handle) and MonteCarlo.AllValues(handle, start, count) can be used to show the interesting results in the worksheet.

In the picture below, cell E2 contains a formula which returns a handle:

Cells E3, E4 and E5 contain "getter" functions, which get a value from the object represented by the handle.

Cells E7:E26 contain an array formula: {=MonteCarlo.AllValues(E2,1,20)}, which retrieves the first 20 values from the object represented by the handle. The AllValues array is potentially huge, and it may be impossible (or undesirable) to show it in its entirety, so there are two extra parameters to specify the sub-range to retrieve.

As you will see in the following topics, this pattern is extremely easy to implement using XLL+ extensions.

Next: Using object handles >>


Using object handles

Handle extensions

Virtually all of the code required to implement handles can be generated by for you, if you use one of the XLL+ Handle extensions.

Several different flavours are available, which differ in how the handle is displayed, and in how the lifetime of the handle objects is managed:

Extension | Handle format | Example
RtdHandles.xpe | Guid:State | {A6CBD52A-040D-4990-89EF-41A6721BADC6}:1280298484
NumericHandles.xpe | Address | 66145697
StringHandles.xpe | Class:Index | MyObject:3
StringPtrHandles.xpe | Class:Address | MyObject:66145697

For this example, we will use the RtdHandles.xpe extension.

Load the extension file

Use the "Manage extensions" command to show the XLL+ Options/Extensions page:

Use the Add button on the XLL+ Options/Extensions page to load the extension file RtdHandles.xpe from the extensions sub-directory.

Note: Ensure that none of the alternative handles extensions (NumericHandles.xpe, StringHandles.xpe or StringPtrHandles.xpe) are loaded. Remove them from the list if they are. Only one variety of handles at a time can be used in a project.

If you use the View Extensions command (located in the XLL Add-ins window on the Tools menu) to inspect the loaded extensions, you will observe that RtdHandles.xpe contains two extended types - Handle and NCHandle - and a function extension - HandleCreator. We will examine these in a moment.

Create the project

Let us try an example, using the RtdHandles extension.

Note: You can find all the source code discussed here in the RtdHandleDemo sample.

Create a new project, RtdHandleDemo with a menu and a results cache. (Check the options Add a menu and Include a cache for results in the XLL+ AppWizard. Do not check the option Save the cache to file.)

We're going to need the menu later, so that the user can clear the handles from time to time if they choose.

The object to be represented as a handle

In the new project, add the code below to the main source file. It is the definition of a very simple object that will be represented in Excel by a numeric handle. We will also create "getter" add-in functions that take a handle as an argument and return data from the object.

CopyC++
class Thing {
public:
    Thing(const char* name_, int value_, double created_)
      : name(name_), value(value_), created(created_)
    {
    }
    std::string name;
    int value;
    double created;
};

An add-in function to create the Thing

Our first add-in function Thing.Create() creates an object with the supplied name and value, adds it to a cache, and returns a numeric handle for the object.

Use the XLL+ Function Wizard to create a new add-in function with the characteristics below:

Name: | Thing.Create
Return type: | CXlOper
Category: | User Defined
Description: | Creates a new Thing

Add two arguments to the function, the name and the value of the new Thing:

Type | Name | Description
String | Name | Name of thing
Int | Value | Value of thing

The wizard looks something like this:

We have one more thing to do in the Wizard. We need to register the function as a creator of handles. Select the Extensions tab, and select the Extension HandleCreator in the list on the left, and put a check against it.

On the right-hand side a list of the function extension's parameters will appear. Set the Handle type parameter to Thing, because that is what we will be returning.

Finally, save the function and add the code shown below:

CopyC++
CXlOper* Thing_Create_Impl(CXlOper& xloResult, const CXlStringArg& Name, long
    Value)
{
    // End of generated code
//}}XLP_SRC

    Thing* thing = new Thing(Name, Value, CXlDate::Now());
    xloResult = psl::CreateHandleInCache(thing);

    return xloResult.Ret();
}

The two new lines do three things:

  1. Create a new Thing object based on the inputs and the current time.
  2. Add the Thing to the handle store, and get a handle in return.
  3. Return the numeric handle to Excel.

Add-in functions to get the Thing's properties

Now we need some functions to get something useful out of the handle.

Using the XLL+ Function Wizard, create a new function, with the characteristics below:

Name: | Thing.Name
Return type: | CXlOper
Category: | User Defined
Description: | Gets the name of a Thing from its handle

Next, add a new argument, thing, of type Handle. As you set the type of the argument, the Function Wizard will display a new column, Handle type. You should set it to Thing, as shown below.

Type | Name | Description | Handle type
Handle | thing | Handle to a thing | Thing

The wizard should look something like this:

Save your changes and add the one line of code shown below:

CopyC++
CXlOper* Thing_Name_Impl(CXlOper& xloResult, double thing_op)
{
    // Input buffers
    const Thing* thing;
    // Validate and translate inputs
    XlReadScalarEx(thing_op, thing, psl::HandleConverter<Thing>(),
        CScalarConvertParams<const Thing*>(L"thing", 0, 0, -1).SetStringParam(0,
        L"Thing"));
    // End of generated code
//}}XLP_SRC

    xloResult = thing->name;
    return xloResult.Ret();
}

As you can see, the validation function, XlReadScalarEx has validated the handle and converted it to a Thing* pointer. There's no need for any checks in our code: we know that the thing is a valid pointer; if it were not, an exception would have been thrown by now, and this code would not be running.

So all we have to do is set the result to be thing->name.

For the other functions, Thing.Value() and Thing.Created(), you should save yourself time by copying the signature of Thing.Name(), thus:

Next: How handles work >>


How handles work

Let us take a moment to examine how the handle mechanism works.

Implementation classes

For the implementation classes discussed below, refer to the header file extensions\RtdHandles.h.

HandleCache

Most of the work is done by the HandleCache<T> class (where T is the class of object being represented by a handle). This object holds and "owns" all of the objects of a particular type, and converts them to and from handles. It is also responsible for releasing them during clean-up.

HandleToPtr() attempts to convert a handle to a pointer to T. If the handle is valid, and refers to an item in the HandleCache, then it is successfully converted. This is the method invoked when converting a handle argument received from Excel to a T* pointer.

Conversely, CreateHandleInCache() converts a pointer to a handle, and adds the object to the HandleCache. This is the method invoked by functions that return handles.

HandleCache<T> is a singleton (i.e. only one instance may exist). If no instance exists, then the XLL+ framework will create one at run-time. The public methods of the class are thread-safe, protected by the CXlLockable embedded in the cache.

HandleCacheCreator

This simple class connects an add-in function (that has been marked with the HandleCreator extension) to the handle cache for its particular handle type.

HandleConverter

This is the converter class for the Handle extended type. It is derived from CXlUserConverterBase<const T*, double>, meaning that it converts a numeric value to a const T* pointer. (See Extended types and CXlUserConverterBase for more on converter classes.)

The implementation method, ConvertFromExcel() uses HandleCache::HandleToPtr() to do all the work of validation and conversion.

The error helper method GetTypeNameW() returns the name of the handle type, so that appropriate error messages can be generated, e.g.:

#ERROR: Expected handle to Thingamajig for X

Global functions

There are several global template functions, including CreateHandleInCache() which is used as follows:

CopyC++
// Add a Thing to the cache and return its handle
Thing* thing = new Thing(Name, Value, CXlDate::Now());
xloResult = psl::CreateHandleInCache(thing);
return xloResult.Ret();

Code supplied by the developer

Creating handles

For a function marked with the HandleCreator extension, one additional line of code is generated, e.g.:

CopyC++
psl::HandleCacheCreator<Thing> handleCache__Thing__Thing_Create(L"Thing", L"Thing.Create");

This constructs a global HandleCacheCreator<Thing> object. This object in turn causes a HandleCache<Thing> to be created (if it does not already exist), and tags it with the name of the add-in function.

The developer must simply write the code that adds the newly created object to the HandleCache, by calling the global template function, psl::CreateHandleInCache(T*), e.g.:

CopyC++
Thing* thing = new Thing(Name, Value, CXlDate::Now());
xloResult = psl::CreateHandleInCache(thing);

Using handles

The Handle extended type does all its work through its converter class, HandleConverter, discussed above. No additional code needs to be supplied by the developer.

Next: Requirements and deployment >>


Requirements and deployment

The RTD implementation of object handles uses Excel's RTD mechanism. An add-in that uses the RTD handle implementation therefore has some runtime requirements on any machine where it is to be used.

Requirements

Excel version
Excel's RTD mechanism is only available in Excel XP upwards (Excel XP/2002, Excel 2003 and Excel 2007). It cannot be used with Excel 97 or Excel 2000.

Installation

The model uses a COM module (RtdHandleServer.dll) to support Excel's RTD mechanism. You should register the RTD server module RtdHandleServer.dll, in one of the following ways:

  1. Use REGSVR32 at the command line, e.g.
    REGSVR32 "C:\Program Files\Planatech\XllPlus\6.0\VS9.0\bin\RtdHandleServer.dll"
  2. Build the project Samples\RtdHandleServer\RtdHandleServer.sln. Choose either the Debug or the Release MinDependency build.

Note: The RtdHandleServer DLL is automatically registered when you install the XLL+ toolkit on a development machine. You only need to register it yourself when you deploy XLLs with RTD object handles to another machine.

Alternatives

If you are unable to satisfy these requirements, you can consider using an alternative object handle mechanism. See Other handle implementations for details.

Next: Combining handles with other features >>


Combining handles with other features

Using a results cache

The implementation for Thing handles we have discussed so far is not necessarily efficient. Look at the screen-shot below.

There are four identical calls to Thing.Create(), and they create four separate objects. This is wasteful of memory and can be bad for performance if the handle creation function is expensive.

However, we can clear up this problem instantly by using a results cache. Set the Cache results feature for the object creation function:

Now only one Thing handle will be created for any unique set of inputs:

Note: Do not attempt to save and restore the results cache. All it will contain are handles, which are, in effect, simply pointers to memory addresses that are no longer valid. Make sure that you do not check the "Save the cache to file" check-box in the XLL+ AppWizard.

(If you have already created the project, just remove any calls to CXlOperCache::Save() and CXlOperCache::Restore().)

Formula Wizard

You should switch on the feature "Do not call in Formula Wizard", otherwise many unnecessary handles will be created.

Thread-safe

Add-in functions that create handles may not be marked as ThreadSafe. This is a restriction of Excel that applies to the RTD mechanism.

However, functions that merely use handles as arguments can be marked as thread-safe.

Asynchonous functions

If the handle creator function is slow, you can add an asynchronous function which is executed in a background thread. See Asynchronous functions for more information. See the MonteCarlo sample for an example of a handle creation function that has an asynchronous version.

Next: Custom handle formats >>


Custom handle formats

Object handles, as implemented in the RtdHandles.xpe extension, consist of a set of parts, separated by colons (or other separators), which combine to form a handle. The parts include:

  • A unique key, in the form of a GUID, e.g. {A6CBD52A-040D-4990-89EF-41A6721BADC6}.
  • State number, a long integer, e.g. 1280298484.

Using the default handle format, a handle looks like this:

{A6CBD52A-040D-4990-89EF-41A6721BADC6}:1280298484

Custom handle format

The developer can implement their own handle formatting class, and thereby take control of the appearance of the handle, by deriving a class from CHandleFormatter<T>.

For example, you can include the type, name and other details of the object being represented:

CustomThing:The name of the thing:{A6CBD52A-040D-4990-89EF-41A6721BADC6}:1280298484
YieldCurve:USD:Govt:{A6CBD52A-040D-4990-89EF-41A6721BADC6}:1280298484

This makes for much more user-friendly handles; it becomes much easier to understand the structure of a spreadsheet that uses handles, and to track down problems.

If you do not specify a separator, then a colon is used. If you have handles that need to include colons, you can specify a different separator by passing it to the constructor of the base class, e.g.:

YieldCurve~USD:Govt~{A6CBD52A-040D-4990-89EF-41A6721BADC6}~1280298484
YieldCurve/USD:Govt:Short/{A6CBD52A-040D-4990-89EF-41A6721BADC6}/1280298484

A custom handle formatter class

A class derived from CHandleFormatter<T> must implement the two conversion functions: MakeHandle and SplitHandle. If the class has a destructor, it must be declared as virtual.

The example code below can be found in the RtdHandleDemo sample. Here is the simple object which will be used with a custom handle formatter:

CopyC++
class CustomThing {
public:
    CustomThing(const TCHAR* name_, int value_, double created_)
      : name(name_), value(value_), created(created_)
    {
    }
    std::tstring name;
    int value;
    double created;
};

We will define a custom handle formatter class, which creates handles that include the target object's type and name, e.g.:

CustomThing/Gregory/{A6CBD52A-040D-4990-89EF-41A6721BADC6}/1280298484

The class implements the two required virtual methods, SplitHandle() and MakeHandle(). The code is based on the implementations in the base class, which can be found in include\XlRtdHandles\HandleFormatter.h.

In addition, the constructor passes a forward slash to the base class constructor, to be used as a separator character.

CopyC++
class CustomThingHandleFormatter : public psl::rtd::CHandleFormatter<CustomThing>
{
public:
    // The constructor specifies a forward slash as the separator character
    CustomThingHandleFormatter()
      : psl::rtd::CHandleFormatter<CustomThing>(_T('/'))
    {
    }
    virtual bool SplitHandle(const TCHAR* pszHandle, std::tstring& strKey, long& lState)
    {
        // Extract the required parts: the guid key and the state
        // which are at positions 2 & 3 respectively.
        // The base class method ExtractKeyAndState() method does all the work.

        return ExtractKeyAndState(pszHandle, strKey, lState, 2, 3);
    }
    virtual std::tstring MakeHandle(const CustomThing* t, const TCHAR* pszKey, long lState)
    {
        // Create a handle: [Class]/[Name]/[GUID]/[State]

        // This code is based on that in the parent class,
        // with an additional 2 key parts inserted at the start
        // of the handle.

        std::vector<std::tstring> parts;

        // 1st, the class
        parts.push_back(_T("CustomThing"));

        // 2nd, the name. Note that the base class
        // method Escape() is used to remove any separator characters.
        parts.push_back(Escape(t->name));

        // 3rd and fourth, the GUID and the state.
        // These two parts are required, but can be in any position.
        // We put them at the end of the handle, because they are not
        // interesting to the user, and we therefore do not care much
        // if they are not visible.
        parts.push_back(pszKey);
        parts.push_back(WriteState(lState));

        // Join the parts together and return the concatenated string.
        return Join(parts);
    }
};

Finally, in the OnXllOpen() event handler, we register the custom formatter with the single instance of HandleCache<CustomThing>:

CopyC++
BOOL CRtdHandleDemoApp::OnXllOpenEx()
{
    // Install the custom handle formatter, for CustomThings.
    psl::HandleCache<CustomThing>::GetOrCreateInstance()->SetFormatter(
        new CustomThingHandleFormatter());

    return TRUE;
}

Next: Persistent object handles >>


Persistent object handles

Recalculation of handles

When a spreadsheet containing RTD object handles is reopened, all the handles are immediately recreated. Consequently, all cells that depend on the handles are recalculated.

This behavior is time-consuming, but it is correct: the handle refers to an object in memory, but the object is no longer there. Therefore a new object must be created, and the handle must be changed.

Persistent handles

There is a solution to this problem: you can save the objects to a cache file (along with their handles) and restore them to memory when they are needed.

As a result, spreadsheets containing handles can be closed and reopened with no recalculations.

The XLL+ RtdHandle implementation contains a class to do most of the work for you: PersistentHandleCache<T>. PersistentHandleCache<T> works as follows:

  1. When the add-in is opened, all saved objects are reloaded from persistent storage on disk.
  2. When a workbook containing RTD handles is opened, the handle is searched for in the set that was loaded from persistent storage. If the handle is found, the object is restored to the object cache, and no recalculation takes place.
  3. If a handle is not found in storage, then it is recreated as usual, and the cells that depend on it are recalculated.
  4. When a workbook containing handles is saved, its handles are added to the persistent store in memory.
  5. When the add-in is closed, the persistent store is saved to disk.

Implementation

There are 2 steps required for implementing persistent object handle storage:

  1. Define streaming operators for the object to be saved. For an object of type T, these are:

    CopyC++
    CXlIStream& operator>>(CXlIStream& is, T*& t);
CXlOStream& operator<<(CXlOStream& os, const T* t)

    Note that the operators act on pointers to T, not to the objects directly.

  2. Create an instance of PersistentHandleCache<T>, and assign the location of the persistent storage file and the performance characteristics of the persistent cache.

These steps are discussed in detail below.

Streaming operators

The object to be serialized is PersistentThing:

CopyC++
class PersistentThing {
public:
    PersistentThing(const TCHAR* name_, int value_, double created_)
      : name(name_), value(value_), created(created_)
    {
    }
    std::tstring name;
    int value;
    double created;
};

To serialize the object so that it can be saved to disk, the following operator overload is used:

CopyC++
inline CXlOStream& operator<<(CXlOStream& os, const PersistentThing* t)
{
    os << t->name << t->value << t->created;
    return os;
}

This is a simple object, and can be serialized easily by using the streaming operators for the built-in types std::tstring, int and double. The CXlOStream and CXlIStream classes contain many other useful streaming operators, including support for std::vector, std::map and matrices of type ple::imtx; so it is easy to serialize complex objects as well.

To deserialize the object from disk into memory, the following operator overload is used:

CopyC++
inline CXlIStream& operator>>(CXlIStream& is, PersistentThing*& t)
{
    std::tstring name;
    int value;
    double created;
    is >> name >> value >> created;
    t = new PersistentThing(name.c_str(), value, created);
    return is;
}

Note that the PersistentThing instance must be created on the heap, using new, and the passed pointer t is set to point to the new object.

An alternative approach might be to set the properties directly, after using a parameterless constructor, as follows:

CopyC++
inline CXlIStream& operator>>(CXlIStream& is, PersistentThing*& t)
{
    t = new PersistentThing();
    is >> t->name >> t->value >> t->created;
    return is;
}

Using existing serialization code

If your object already has code that allows it to be serialized, then you can adapt this code to CXlIStream and CXlOStream by using CXlIStream::ReadByteArray and CXlOStream::WriteByteArray.

See the SerializedThing object in the PersistentHandleDemo sample for an example of this technique.

PersistentHandleCache

In the sample the instance of PersistentHandleCache is declared globally; you could equally well make it a member variable of the application class.

The constructor includes all the run-time parameters required for the persistent cache:

CopyC++
const TCHAR* pszCacheFile = _T("%TMP%\\PersistentThings.dat");

psl::PersistentHandleCache<PersistentThing> thePersistentCache(
    NULL,         // Use the default handle formatter
    pszCacheFile, // Data file
    100,          // Maximum number of items in saved file
    0,            // Maximum age in seconds (ignored if 0)
    true);        // AutoSave

The path used for the location of the data file includes an environment variable, %TMP%. This will be expanded at run-time to a complete path. This is a sensible location to use for per-user storage, since the user will always have read and write permission to the location, regardless of the operating system or security setup.

The AutoSave parameter is set to true, which saves any further coding: the cache will be restored from file during the OnXllOpenEx() event and saved to file during the OnXllClose() event.

Sample code

As well as the PersistentHandleDemo sample discussed above, there is also a more real-world example in the MonteCarlo2 sample.

Next: Other handle implementations >>


Other handle implementations

This discussion of handles has focused on the RTD handle implementation, since this is the most efficient and also the most flexible implementation.

Unsynchronized caches

As discussed earlier, another set of implementations are available, which use an unsynchronized cache, instead of the synchronized cache used by RTD. They are all very similar to each other, and differ only in how the handle is displayed.

Extension | Handle format | Example
NumericHandles.xpe | Address | 66145697
StringHandles.xpe | Class:Index | MyObject:3
StringPtrHandles.xpe | Class:Address | MyObject:66145697

The cache used by the RTD implementation receives a message from Excel whenever a handle goes out of use. It immediately destroys the object and removes it from the cache. As a result, the use of memory and the speed of the implementation remains constant. (We refer to this as a synchronized cache.)

These alternative implementations do not receive a message when a handle is no longer used, and therefore do not know when to destroy it. The cache grows in size until Excel is closed, or until the user decides to clear it. (We refer to this as an unsynchronized cache.)

Advantages

These unsynchronized implementations have three advantages over the RTD implementations:

  1. They work with very old versions of Excel, including Excel 2000 and below. RTD requires Excel XP (2002), Excel 2003 or Excel 2007 or above.
  2. They are completely self-contained, whereas the RTD handle implementations require an RTD server module, RtdHandleServer.dll, to be deployed and registered on users' machines.
  3. Functions that create handles can be marked as thread-safe, whereas they cannot be marked as thread-safe when using RTD handles.

Disadvantages

There are also significant disadvantages in using the unsynchronized handle implementations:

  1. The object cache grows as long as Excel is in use, so memory use and performance are not constant.
  2. In order to invalidate handles contained in workbooks that are reopened, the add-in forces a recalculation of all cells that contain handle creation functions. This is achieved through a COM event handler (which catches the WorkbookOpen event) and a macro which searches each worksheet. This technique is slower and much more intrusive than the technique used by RTD handles.
  3. The format of the handles is limited. You cannot apply custom formatters, as you can with RTD handles.
  4. You must provide a house-keeping mechanism, such as a menu command "Clear object handles", so that the user can reduce the size of the cache without exiting Excel. You also need to educate users as to the purpose and use of the command.

House-keeping

There are two additional "house-keeping" tasks that need to be managed in a handle add-in that uses these unsynchronized handles.

Stale handles

The handle values saved in a workbook are irrelevant when the workbook is reopened. Since they are, in effect, pointers, there is no guarantee that the memory pointed to is still valid, and still contains an object of the right type. Worse still, the pointer may be for an object of the right type, but out of date, so that the results are erroneous.

So, we must make sure that all the handles in a workbook are recalculated when the workbook is reopened. The HandleCache object contains an event observer object (m_workbookOpenObserver) which handles this by trapping the WorkbookOpen event, and using a CXlFormulaRefresh object to update all cells containing a handle creator function.

All this is dealt with by the code generated by the XLL+ Function Wizard. The developer does not need to add any code.

Clearing the cache

If Excel stays open for long periods, and many object handles are created over time, it is sensible to clear out all the handles in the cache from time to time.

You should provide a menu command that clears the handle cache thus:

CopyC++
psl::ClearHandleCache<Thing>();

You can find an example of this in the NumericHandleDemo sample.

Note that if you have used a results cache, you need to make sure that you clear the results cache first, and then clear all the handles:

CopyC++
CXlOper* Thing_ClearCache_Impl(CXlOper& xloResult)
{
    // End of generated code
//}}XLP_SRC

    ::XllGetTypedApp()->m_cache.Clear();
    psl::ClearHandleCache<Thing>();
    return xloResult.Ret();
}

Next: Specifying a smart pointer type >>


Specifying a smart pointer type

ple::simple_shared_ptr<T>

When a pointer to an object is stored in the object cache, it is wrapped in a smart pointer. This ensures that when the object is no longer needed, it will automatically be deleted.

By default, ple::simple_shared_ptr<T> is used as the smart pointer. This type is included as part of the XLL+ run-time libraries, in simple_shared_ptr.h.

Other smart pointer types

If the objects that you wish to represent as handles in Excel are already wrapped in smart pointers, you will need to use the same type of smart pointer within the object cache. This will ensure that ownership of the object is shared between the object cache and the library that created the object, and thus the object will not be deleted until is no longer needed by both the object cache and the originating library.

To specify a specific smart pointer type you should define the macro RTDHANDLES_PTR_CLASS before the inclusion of rtdhandles.h. For example, to use the boost shared_ptr class, the following lines are used:

CopyC++
#include <boost\shared_ptr.hpp>
#define RTDHANDLES_PTR_CLASS boost::shared_ptr
#include <extensions\rtdhandles.h>

You can then use the smart pointer type as an argument to the global function CreateHandleInCache, e.g.:

CopyC++
CXlOper* CachedThing_Create_Impl(CXlOper& xloResult, const CXlStringArg& Name,
    long Value)
{
    // End of generated code
//}}XLP_SRC
    boost::shared_ptr<CachedThing> thing(new CachedThing(Name, Value, CXlDate::Now()));
    xloResult = psl::CreateHandleInCache(thing);
    return xloResult.Ret();
}

More realistically, you might use code like the following to put a shared pointer in the object cache, and return a handle:

CopyC++
boost::shared_ptr<YieldCurve> yc = CurveFactory::CreateYieldCurve(
    ccy, dates, rates);
xloResult = psl::CreateHandleInCache(yc);
return xloResult.Ret();

For more details see the BoostHandles sample project.

Next: Sharing object handles between XLLs >>


Sharing object handles between XLLs

Shared handles

Beginning with XLL+ version 7.0.6, it is possible to shared object handles between XLLs. An object can be constructed in one XLL, and its handle can be passed to a function in a second XLL for use within an add-in function.

For a class to be shared between XLLs, a number of conditions must be satisified.

  1. The handle provider XLL must export the function exported_GetCacheInstance().
  2. Each object type to be used in a Consumer XLL must be registered, by calling HandleCacheInstanceImportManager::RegisterType().
  3. The objects must be identically laid out in memory in both XLLs. Therefore both XLLs must use the identical compile and link flags.
  4. The compiler settings must be changed to use the shared DLL version of the Microsoft run-time libraries.
  5. The handle type must be set to one of the non-RTD handle types: StringHandle, StringPtrHandle or NumericHandle. The current implementation does not support sharing RTD handles.

Handle provider

A handle provider XLL that needs to share handles with other XLLs must export the function exported_GetCacheInstance().

This function may only be included by one C++ source file in any particular XLL. For one cpp file, and only one cpp file, insert #define NONRTDHANDLES_IMPLEMENT_EXPORT before the line that includes the handles extension file, e.g.

CopyC++
#define NONRTDHANDLES_IMPLEMENT_EXPORT
#include "extensions\StringHandles.h"

Including this line will have the effect that the function exported_GetCacheInstance() is created and exported.

If the line is not included by any CPP source file, then handles will not be exported for use by other XLLs.

Handle consumer XLLs

An XLL that uses handles created by another XLL - a consumer XLL - must instruct the global singleton instance of the HandleCacheInstanceImportManager object where to find handles of each type, by calling HandleCacheInstanceImportManager::RegisterType() during OnXllOpenEx(), e.g.:

CopyC++
BOOL CHandleConsumerApp::OnXllOpenEx()
{
    // Inform the controller that handles for the following object types will
    // be sourced from "HandleProvider.xll"
    psl::HandleCacheInstanceImportManager::RegisterType(L"Thing", _T("HandleProvider.xll"));
    psl::HandleCacheInstanceImportManager::RegisterType(L"test::Thing2", _T("HandleProvider.xll"));
    psl::HandleCacheInstanceImportManager::RegisterType(L"std::map<std::string,std::string>", _T("HandleProvider.xll"));
    return TRUE;
}

The class name argument must be a wide (Unicode) string and must exactly match the form of the class name used in add-in functions. If a namespace is used in the add-in function's definition then the namespace must be used in the RegisterType() call.

Similarly, if template arguments are used, they must be in exactly the same form as in the add-in function, including white-space.

Note that the XLL name is in standard text form (either ASCII or Unicode depending on the project settings) and that it:

  1. includes the extension ".xll";
  2. does not include the directory of the XLL.

Example

For more details see the SharedHandles sample project.

Next: Grouping arguments >>


Groups

This chapter contains the following topics:

Grouping arguments
Scalar groups
Vector groups


Grouping arguments

There are two reasons why you might want or need to group a number of arguments together, so that they appear in Excel as a single argument.

Argument limit

There is a limit to how many arguments you can pass to an Excel add-in function, and a function with too many arguments will not work. In this case, you must select some of your arguments and group them, creating a scalar group or a vector group.

Under Excel 2003 and below, functions with more than 30 arguments cannot be registered, and functions with more than 20 arguments will not have descriptions in the Excel Formula Wizard. Under Excel 2007, the limit for arguments is 255. However, if you need to support both versions of Excel, you will need to follow the lower limit.

The XLL+ Function Wizard will generate a warning if there are more than 30 arguments to a function that is intended for use in the older versions of Excel.

Ease of use

The user interface may be easier to use if there are fewer arguments. For example, you may have a group of columns which are closely related, such as a column of dates and a column of payment amounts for each date. In this case, it may make sense to group the two columns as a two-dimensional array, by creating a vector group.

You can use the XLL+ Function Wizard to create groups of arguments. The wizard will generate code that splits the single Excel argument into its constituent parts, and checks that all required constituents are present and correct.

Choices

Another way you might want to group arguments is as a choice, whereby only one of the grouped arguments is expected, but it can appear in multiple different forms. See the topic Choice arguments for more information.

Next: Scalar groups >>


Scalar groups

A scalar group can contain any number of scalar (single-cell) arguments. Each of these inner arguments must have a specified value type; the following generic types are not allowed:

  • Value
  • Reference
  • XlArray

The inner arguments may be built-in data types or extended scalar types. The inner arguments are not constrained to be the same type, they can be the same or different as you choose.

Appearance in Excel

The inner arguments will appear in Excel as a single vector argument. For example, take a group argument, PaymentDetails, that contains four inner arguments, as follows:

Name | Type
StartDate | Date
EndDate | Date
AccountType | String
PaymentDays | Long

The wizard will generate code that inspects the outer (Excel) argument. This code will fail and return a helpful error message unless the argument is one of the following shapes:

  • 4 rows x 1 column, with the cells in inner argument order, e.g.:

  • 1 row x 4 columns, with the cells in inner argument order, e.g.:

  • 4 rows x 2 columns, with labels in the left column, and the cells in any order, e.g.:

Wizard-generated code for compressed groups

The wizard-generated code to unpack this group will look something like this:

CopyC++
// Input buffers
long StartDate;
long EndDate;
std::string AccountType;
long PaymentDays;
// Validate and translate inputs
XlReadGroupedScalarEx(*PaymentDetails, StartDate, DateConverter(), L"Payme"
    L"ntDetails", 0, L"StartDate");
XlReadGroupedScalarEx(*PaymentDetails, EndDate, DateConverter(), L"Payment"
    L"Details", 1, L"EndDate");
XlReadGroupedScalar(*PaymentDetails, AccountType, L"PaymentDetails", 2,
    L"AccountType");
XlReadGroupedScalar(*PaymentDetails, PaymentDays, L"PaymentDetails", 3,
    L"PaymentDays");

If the input-checking code fails, then a useful error message will be returned, such as:

#Error in cell 4 of PaymentDetails (PaymentDays): expected an integer

If all the input-checking code is successful, then the variables StartDate, EndDate, AccountType and PaymentDays will be populated and ready for use.

Creating a scalar group

The simplest way to create a scalar group is to select all the arguments you wish to group and then using the [image] Group arguments command.

Note: For help on selecting multiple arguments, see Selecting arguments.

After you click the Group tool, a new argument, named "Group1" will be created, containing the existing four arguments.

Go to the group's "Name" column and change it to the correct name.

Group descriptions

You can choose to rely on the Function Wizard to create the description of the group, by selecting one of the standard descriptions that drop down below the cell, when you click on the arrow.

The advantage of using on of these built descriptions is that the group's description will automatically be updated whenever you change the order or membership of the group's arguments, or change the name or description of one the arguments.

Editing a scalar group

There are several ways to create and edit a scalar group in the Function Wizard.

  • The [image] New Group command can be used to create a new empty group, to which you can then add new or existing arguments.
  • The [image] Group arguments and [image] Ungroup arguments commands can be used to group selected arguments or to ungroup an existing group.
  • You can drag an argument into or out of a group using the mouse.
  • You can use the [image] Move argument right and [image] Move argument left commands to move a group into or out of a group respectively.

Example

You can see an example of a scalar group of arguments in the LabelledArgs sample project.

Next: Vector groups >>


Vector groups

If you have a group of vector arguments which are closely related, and are always the same size as each other, then you may want to use a vector group. The user will then see only one argument, and the wizard will generate code to split it into a number of vectors, checking that each inner argument is present and that all columns (or rows) are the same length.

Advantages of vector groups

Vector groups can be useful for both the add-in developer and the user.

  • The total number of arguments is reduced. Since Excel has a limited number of arguments per function, combining multiple vector arguments into one grouped argument may leave room for more arguments.
  • The user has less arguments to worry about. Furthermore, if the vectors are returned from some other function or from a database as a single result, it may be very convenient for the user to pass them on to another function as a single group.

Disadvantages of vector groups

Vector groups are not always a useful feature.

  • The columns or rows must be in a particular order, left to right, or top to bottom. It may be inconvenient for the user to arrange them in this way.

    Note: However, the user can work around this problem by using a function which combines multiple cells into a single range, such as TFOLD.

Wizard-generated code for vector groups

For example, take a grouped argument, PaymentSchedule, that contains two vectors, as follows:

Name | Type
PaymentDates | Date[]
PaymentAmounts | Double[]

The XLL+ Function Wizard will generate code that declares a vector of the appropriate type for each column or row and populates it with the contents of the corresponding region of input. If the input cannot be read, then an appropriate error message will be returned.

CopyC++
// Input buffers
std::vector<long> PaymentDates;
std::vector<double> PaymentAmounts;
// Validate and translate inputs
XlReadGroupedVectorEx(*PaymentSchedule, PaymentDates, DateConverter(), L"Pa"
    L"ymentSchedule", 0, L"PaymentDates", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK
    |XLA_OPER_IS_GROUP);
XlReadGroupedVector(*PaymentSchedule, PaymentAmounts, L"PaymentSchedule", 1,
    L"PaymentAmounts", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK|XLA_OPER_IS_GROUP);

If the validation code fails, then a useful error message will be returned, such as:

#Error in cell 3 of PaymentSchedule column 1 (PaymentDates): expected a date

or:

#Error column 2 of PaymentSchedule: expected 4 rows

If all the validation code is successful, then the variables PaymentDates and PaymentAmounts will be populated and ready for use. In addition, both vectors will be the same length.

Next: Choice arguments >>


Choice arguments

Groups allow you to tie a set of real arguments to a single Excel argument. Another way to group arguments together is to use a Choice, to transform the Excel input into just one real argument, choosing from a list of mutually exclusive inner arguments. A Choice inspects the Excel input and validates it against each of the arguments held within the choice. As soon as one succeeds, validation stops.

Example

A simple example is a dividend stream argument. This argument can be either a set of predicted cash-flows - with two columns containing dates and amounts - or a single interest rate.

The picture above shows the organization of the Choice group. The outer argument, Dividend, is the argument that is visible in Excel.

When the add-in function validates the input, it first tries to match the the first member of the choice, DividendStream. If it finds that the input consists of two columns, the first containing dates and the second containing numbers, then it reads the values of the columns into the inner arguments, DividendDates and DividendAmounts, and stops processing the argument.

However, if the input does not match DividendStream, then the add-in function tries again, and checks whether the input is a single number, DividendRate. If it matches, then the inner argument DividendRate is set to the value of the input, and processing for the argument is complete.

If the input does not match either of the choice arguments, then an exception of type CXlChoiceFailedException is thrown. The add-in function aborts, and an error is returned to Excel:

#ERROR: Failed to convert Dividend to any of the permitted types

Coding with choices

The validation code generated for the example above is as follows:

CopyC++
CXlOper* ChoiceFn1_Impl(CXlOper& xloResult, const CXlOper* Dividend)
{
    // Input buffers
    std::vector<long> DividendDates;
    std::vector<double> DividendAmounts;
    double DividendRate;
    // Validate and translate inputs
    int Dividend__index = -1;
    if (Dividend__index < 0) {
        try {
            XlReadGroupedVectorEx(*Dividend, DividendDates, psl::DateConverter
                (), L"Dividend", 0, L"DividendDates", XLA_TRUNC_ONEMPTY|
                XLA_TRUNC_ONBLANK|XLA_OPER_IS_GROUP);
            XlReadGroupedVector(*Dividend, DividendAmounts, L"Dividend", 1,
                L"DividendAmounts", XLA_TRUNC_ONEMPTY|XLA_TRUNC_ONBLANK|
                XLA_OPER_IS_GROUP);
            Dividend__index = 0;
        } catch(...) {}
    }
    if (Dividend__index < 0) {
        try {
            XlReadScalar(*Dividend, DividendRate, L"DividendRate");
            Dividend__index = 1;
        } catch(...) {}
    }
    if (Dividend__index < 0)
        throw CXlChoiceFailedException("Dividend");
    // End of generated code
//}}XLP_SRC
    // TODO - set the value of xloResult, or return another value
    //          using CXlOper::RetXXX() or throw a CXlRuntimeException.
    return xloResult.Ret();
}

You will see that an additional local variable Dividend__index has been declared, and initialized to -1.

The validation code tries each element of the choice in turn. If validation succeeds, then Dividend__index is set to the index of the member that succeeded. If no member passes validation, then Dividend__index remains -1, and the validation of the entire choice fails.

The table below lists which local variables contain valid values for each value of Dividend__index.

Dividend__index | Valid inputs
-1 | None, and an exception is thrown
0 | DividendDates & DividendAmounts
1 | DividendRate

Your code can use the value of Dividend__index in a switch statement:

CopyC++
switch (Dividend__index)
{
case 0:
    xloResult.Format("%lu predicted dividends", DividendDates.size());
    break;
case 1:
    xloResult.Format("%lf rate", DividendRate);
    break;
}

This approach takes a lot of the complexity associated with multi-format inputs and delegates it to the generated code, leaving your own code simpler to understand and maintain.

Next: Publishing and suppressing add-in functions >>


Publishing and suppressing add-in functions

Sometimes it is necessary to restrict which of the add-in functions in an XLL are made available to users. The XLL+ toolkit contains a set of classes - in header file xlpfunctionfilter.h - which offer various policies for applying such restrictions.

Development-time or run-time

There are two very different strategies for filtering the functions made available to the user:

  • Development time Filtering can be controlled at development-time, by using a function extension to make entries in the source code.
  • Run-time Filtering can be controlled at run-time by supplying a configuration file that is loaded by the add-in.

The use of a run-time configuration file is less secure, since this method of control can be altered by users; if you want to keep the function filter under the control of the developer, then you should apply the restriction to the source code at development time, by using the FunctionFilterOptIn or FunctionFilterOptOut function extensions.

To use the development-time approach you will need to load the extension file FunctionFilter.xpe which is located in the extensions directory of your XLL+ installation. See Loading an extension file for instructions.

Policy

Two different filtering policies are offered, opt-in and opt-out.

Opt-in
Only functions that have been registered to be published will be made available to the user; all other functions will be suppressed. Adding this option to an existing add-in will suppress all it's add-in functions; the developer must then add some code to register some or all of the functions in the add-in.
Opt-out
All functions will be made available except those which have been chosen to be suppressed. Adding this option to an existing add-in will have no impact. The developer must then add some code to suppress some or all of the functions in the add-in.

Development time filtering

To apply filtering at development time, ensure that the extension file FunctionFilter.xpe is loaded (see above). This will add two new boolean properties to the "Miscellaneous" section of the add-in's proprties in the Properties window: FunctionFilterOptIn and FunctionFilterOptOut.

An opt-in policy looks at the FunctionFilterOptIn property and ignores FunctionFilterOptOut. An opt-out policy looks at the FunctionFilterOptOut property and ignores FunctionFilterOptIn.

In an opt-in policy, to ensure that a function is published, set its FunctionFilterOptIn property to True. Only these functions will be included.

In an opt-out policy, to ensure that a function is suppressed, set its FunctionFilterOptOut property to True. These functions will be included and all other functions will be included.

You need to apply the filter just before function registration takes place, and two helper classes are available to achieve this. Each is a specialized event handler for the XlRegisterFunctions event.

To apply an opt-in policy, declare a global instance of CXllFunctionFilterEventHandlerOptIn:

CopyC++
CXllFunctionFilterEventHandlerOptIn theFunctionFilter;

During the XlRegisterFunctions event, the object's Update method will be called. As a result, an opt-in policy will be appied to the global instance of the function filter (CXllFunctionFilter), using the following code:

CopyC++
CXllFunctionFilter::Apply(*CXllApp::Instance(), true);

You can find a full example of this policy in the PubDevIn sample application.

To apply an opt-out policy, declare a global instance of CXllFunctionFilterEventHandlerOptOut:

CopyC++
CXllFunctionFilterEventHandlerOptOut theFunctionFilter;

During the XlRegisterFunctions event, the object's Update method will be called. As a result, an opt-in policy will be appied to the global instance of the function filter (CXllFunctionFilter), using the following code:

CopyC++
CXllFunctionFilter::Apply(*CXllApp::Instance(), false);

You can find a full example of this policy in the PubDevOut sample application.

Run-time filtering

The event handler class CXllFunctionFilterEventHandlerFromFile can be used to implement a run-time filter.

This event observer should be declared at global scope as a static instance, as below:

CopyC++
CXllFunctionFilterEventHandlerFromFile theFunctionFilter(CXllFunctionFilterLoader::EXPLICIT);

During the XlRegisterFunctions event, the object's Update method will be called. As a result, the specified configuration file will be located, loaded and parsed and then applied to the function filter registry, CXllFunctionFilter. The actual work of loading and parsing the file is performed by CXllFunctionFilterLoader.

The configuration file will be parsed in one of two ways.

If the loadType specified in the constructor is CXllFunctionFilterLoader::OPT_IN or CXllFunctionFilterLoader::OPT_OUT then the file should contain a list of function names, each on a single line. Blank lines are ignored.

If the loadType is CXllFunctionFilterLoader::EXPLICIT then the file should contain a list of function names and actions, each on a single line. Each line should contain a pair of items, separated by white space: first a function name, and second a boolean value, which can be 1, 0, true or false. If the boolean value is 1 or true, then the function in that line is published. If the boolean value is 0 or false, then the function in that line is suppressed. Blank lines are ignored.

You can find a full example of this approach in the PublishRT sample application.

Testing

The developer will almost certainly need to carry on testing and developing the add-in functions which are not being delivered to the user. To facilitate this, it is usual to wrap the filtering code in an #ifdef directive, e.g.:

CopyC++
#ifndef _DEBUG
CXllFunctionFilterEventHandlerOptOut theFunctionFilter;
#endif

Next: Favorite arguments >>


Favorite arguments

If you frequently use the same argument for many different functions, you should consider adding it to the Favorite Arguments list.

Adding to favorites

To add an argument to the favorites list, select it in the XLL+ Function Wizard, and click on the Add to Favorite Arguments command.

The Add to favorites window will appear. Select the folder in which to store the argument - or create a new folder withe New Folder... button - and press OK to save the argument.

Retrieving a favorite argument

When you need to add a favorite argument to a function, use the Favorite Arguments command.

Select an argument from the appropriate folder of the favorites list, and click OK to add it to your function.

Managing favorites

You can use the Favorite Arguments window to manage your list of favorites. Use drag-and-drop to move items between folders, or control-drag to copy items.

You can create folders, delete them and move them in the folder hierarchy.

Once you're finished managing the list, use the File/Save menu to save your changes.

Tip: You can also open the Favorites window from the XLL Add-ins window, using the Tools/Favorite Arguments menu command.

Sharing favorites

You can share your favorites list with others, or copy it to another computer, by using the File/Import... command in the Favorite Arguments window.

To find the location of your favorites file, use the XLL+ Options/General page, and inspect the FavoriteArgumentsFileResolved setting (located in the Tools category). You can send a copy to another machine and import it there.

Tip: A useful technique for teams is to use the XLL+ Options/General page to set the FavoriteArgumentsFile setting to a file on a shared drive, so that all members of the team have access to the same favorites list. This can help considerably in maintaining standards and increasing re-use.

Next: International support overview >>

See Also

Favorites window


International support

This chapter contains the following topics:

International support overview
Levels of support
Choice of languages
Ensuring stable behavior
String substitutions
Types of string
Deployment
Conversion of an existing project


International support overview

If you are programming for users that use a version of Excel in a language other than yours, or who set their user preferences to a language other than yours, there are a number of issues that you should consider. This is particularly true if you wish to support users in more than one language.

The links below list all the internationalization topics in the User Guide. You can also refer to Global resource functions for a list of the functions which retrieve strings from the resource file.

Topic | Description
Levels of support | What do I need to do to support users with languages other than my own?
Choice of languages | How do I decide which language my add-in should use at run-time?
Ensuring stable behavior | What do I have to do to ensure that my add-in will behave as expected in languages other than my own?
String substitutions | Techniques for substituting strings at run-time, so that the selected language is used.
Types of string | The various types of string that may need to be localized, and techniques for localizing them.
Deployment | Where to store resources; how to allow other developers to add support in their own languages.
Conversion of an existing project | How to convert an existing single-language add-in to support multiple langauges.

Samples

The following sample projects contain examples of all the techniques discussed in these topics.

Sample | Description
International | Demonstrates how to get and use Excel's international settings
Localized (Single DLL) | Demonstrates how to support multiple languages in a single XLL
Localized (Multiple DLL) | Demonstrates how to support multiple languages using one DLL per language

Next: Levels of support >>

See Also

Global resource functions


Levels of support

There are three levels of support for internationalization that you should consider.

Level 1: Stability

The add-in runs as expected in a foreign language, but all supporting text (names, help etc) remains in the author's language.

See the topic Ensuring stable behavior for instructions on how to ensure this level of support.

Almost all XLL+ sample projects satisfy level 1 support criteria.

Level 2: Self-contained add-in with multi-language support

The add-in's supporting text is available in a limited number of languages, fully under the control of the author of the add-in.

Techniques for achieving this level of support are discussed in the following topics:

  • String substitutions
  • Types of string
  • Conversion of an existing project

See Conversion of an existing project for instructions on converting a single-language add-in to support multiple languages.

The sample project Localized (Single DLL) supports level 2 criteria.

Level 3: Independent multi-language support

The add-in's supporting text is available in any number of languages, and support for new languages can be added in new modules by third parties, without any impact on the core add-in, or on any other language modules.

See Deployment for a discussion of the differences between this type of support and support for a self-contained add-in with multi-language support.

The sample project Localized (Multiple DLLs) supports level 3 criteria.

Next: Choice of languages >>

See Also

International support


Choice of languages

There are three types of regional setting that are of relevance to an Excel user and developer.

  1. The language version of Excel that is being used.
  2. The regional settings selected by the user in the Windows Control Panel.
  3. A language selected by the user at run-time.

Excel version language

Most versions of Excel are fixed to a particular language. If you buy the English version of Excel, the menus will always be displayed in English, and the function names of built-in worksheet functions will always be displayed in their English form. If the user changes their regional settings using the Control Panel, it may change many aspects of how Excel displays spreadsheets, including numeric and date formats etc, but the menus will still be in the language of the Excel version.

When interrogated as to its country settings, Excel returns a single numeric country code (usually the international telephone dialling code). The XLL+ run-time libraries take care of translating this into an appropriate language identifier.

The following functions provide support for using the Excel version language:

XllGetExcelCountryCode | Returns the Excel country code.
XllGetExcelLanguageID | Returns the best available language contained in the add-in's resource files, for the Excel country code.
XllLoadStringForExcelLanguage | Loads a string resource in the best available language to match the Excel version language.
XllTranslateString | Takes a string that contains string resource IDs (e.g. "#@123") and replaces the IDs with the appropriate strings from the resource file.

Regional settings

If a user uses the Control Panel to set their Windows preferences to German (Austria), and uses an English language version of Excel, they will see dates and currencies in cells, formatted in Austrian convention. However, their menus and dialogs will still be in English (the Excel version language).

The following functions provide support for using the language of the regional settings:

XllGetStringLanguageID | Returns the language currently preferred by the user. The default value for this is the language selected in the Control Panel's Regional Settings applet.
XllLoadString | Loads a string resource in the best available language to match the current language.
XllTranslateString | Takes a string that contains string resource IDs (e.g. "#123") and replaces the IDs with the appropriate strings from the resource file.

User selection

Finally, you may wish to allow the user to specify the language for the add-in's supporting text. A German speaker will wish to make their own decision as to whether to see text in English or in French, if those are the only two languages available for a particular add-in.

You may choose to provide a facility for the user to make a decision at run-time as to which language they will use, for example by providing a menu which lists all the laguages available for the add-in.

The following functions provide support for using a language selected by the user:

XllGetStringLanguageID | Returns the language currently preferred by the user. The default value for this is the language selected in the Control Panel's Regional Settings applet.
XllSetStringLanguageID | Sets the preferred language for this add-in. This language will be used by all calls to XllLoadString, XllTranslateString etc.
ResListLanguages | Gets a list of all the languages supported by the add-in.

Next: Ensuring stable behavior >>

See Also

International support | Global resource functions


Ensuring stable behavior

There are two main issues to address in order to be sure that your add-in behaves as expected when used in a language other than the one you wrote it in.

Category

In the XLL+ Function Wizard, you can select a category for your add-in function. The standard categories shown in the XLL+ Function Wizard are built into Excel. If you select one of the standard categories for your function, then it will automatically appear in the local language of the Excel version being run. See Function category for a list of the built-in categories.

If you wish to take advantage of this facility, you should be sure to use a category that is identical to that in the drop-down list. If you change the wording at all, then XLL+ will not recognize it as a built-in category, and will show the category exactly as you entered it, rather than translating it to the Excel version language.

If you decide to use a new category, you can localize it in the usual way by using a resource ID instead of a string (as shown below), and adding a string with the appropriate resource ID to each language's string table in the resource file. See String substitutions for information about resource ID strings.

Formulae

A formula's argument separators vary according to the user's regional settings. For example, =MyFunc(A,B,C) (in English) will appear as =MyFunc(A;B;C) in German, with semicolons replacing commas. In addition, the names of built-in functions vary in different language versions of Excel. If you are setting formulae from your code, or if you are reading formulae and parsing them, you should be aware of these issues and code defensively.

See Setting formulae for a full discussion of the internationalization of formulae.

Next: String substitutions >>

See Also

International support


String substitutions

An add-in contains several types of string which you might consider localizing, so that they appear in the language of the user.

In general, the technique for localizing strings in XLL+ is as follows:

  1. Create several string tables in the application's resource file, one for each language you wish to support.
  2. Add each string to each table in the appropriate language, using the same resource ID in each string table.
  3. Where the string would normally appear, for instance in the XLL+ Function Wizard, enter #NNN instead of a string. NNN should be the numeric version of the resource ID.
At run-time, the XLL+ library will automatically replace the #NNN place-holder with a string in the correct language.

String resource IDs

Resource IDs are made up of prefixed integers (either decimal or hexadecimal), and can be in one of the following forms:

Type | Examples | Translation
Regional settings | #123 #0x7B | Will be replaced by a string in the language implied by the user's current regional settings, if it can be found in the resource file. If the language cannot be found, then English will be used. The function used to detect the current language is XllGetStringLanguageID.
Excel version | #@123 #@0x7B | Will be replaced by a string in the language implied by the Excel version, if it can be found in the resource file. If the language cannot be found, then language implied by the user's current regional settings will be used. If that language cannot be found, English will be used. The function used to detect the Excel version language is XllGetExcelLanguageID.

Using resource IDs

You can use a resource ID instead of a string in the following places:

  • In the XLL+ Function Wizard.

    For instance, in the picture above, the resource id "#202" is used for the function's description. This will be replaced at run-time by a string from the resource file.

  • In source code, when calling some XLL+ functions.

    m_menu.AddItem(_T("#101"), _T("MyFunction"));

    In the example above, the menu item's caption will be looked up in the resource file. It will be replaced with the best language match for string resource 101, according to the current language settings.

    See ::XllTranslateString() for a list of all the XLL+ functions that accept and translate resource ID strings.

  • With ::XllTranslateString()

    CString strOut;
::XllTranslateString(_T("#ERROR: #102"), strOut);

    You can use ::XllTranslateString() to replace numeric string identifiers with appropriate language strings at run-time. This is the method used by the functions of the XLL+ run-time library.

Next: Types of string >>

See Also

International support | Global resource functions | View Resource ID Column command


Types of string

Types of string

There are several types of string which you might consider localizing. The list below contains links to a detailed discussion of each.
String | Summary
Library name | This is the name of the add-in library, as it will appear in the Tools/Add-ins... dialog.
Exported function name | The name of an add-in function, as it will appear in Excel.
Argument names | The names of each of an add-in function's arguments, as they appear in the Excel Formula Wizard.
Function category | The category under which a function appears in the Excel Formula Wizard.
Help text | The help text that appears for an add-in function and for each of its arguments in the Excel Formula Wizard.
Commands | Captions and help text for menus and toolbars.
Formulae | The text of a formula, which can be set using CXlOper::SetFormula.
Error strings | Currently, the error strings returned by the XLL+ run-time libraries are hard-coded in English. In a future release, we will provide the option for error strings to be localized.

Library name

The library name has to be available very early in the process of initializing an add-in library, during the CXllApp::InitInstance event handler. At this point the Excel language version is not available, so any localization can only refer to the user's regional settings.

In the example below, the name of the application is given as "#6". Thus it will be replaced by the resource string whose numeric ID is 6. The string will be retrieved in the appropriate language, which at this point is the user's regional language setting as set in Control Panel).

Note that "#@6" may not be used, since the Excel language version is not available at this point. If you do try to use the Excel version language, the add-in will fail to load.

/* static */ LPCTSTR CInternationalApp::m_pszDefName = "#6";

BOOL CInternationalApp::InitInstance()
{
    // Call the base class
    if ( !CXllApp::InitInstance() )
        return FALSE;

    // Set the name of the library to the default value
    m_stName = m_pszDefName;

    // Add the statically defined function specifications
    AddStaticFns();

    // TODO: Add your specialized code here

    return TRUE;
}

Exported function name

The name of an add-in function, as it will appear in Excel. This should not be localized; otherwise workbooks saved in one language setting will not work when opened in a different one. There is no way for Excel to know that a formula saved by a German user as, for example, =WASSER(...) should be interpreted as =WATER(...) when the workbook is opened by an English user.

By contrast, you will have noticed that Excel's built-in functions are allowed to appear differently in different language versions of Excel. This is because, when a formula is stored, built-in functions are replaced by their numeric function identifiers. For built-in functions, these numeric function identifiers are fixed, and functions can therefore be serialized as numbers. For add-in functions, numeric function identifiers are not fixed, and may change each time an add-in library is loaded; therefore user-defined functions are saved as text.

Argument names

The names of an add-in function's arguments, as they will appear in the Excel Formula Wizard. Unlike the function name, these can be localized, since they are not stored as part of a worksheet, and are of interest only at run-time, to the Excel Formula Wizard.

However, the XLL+ Formula Wizard uses argument names for C++ variables in the generated C++ function implementation,and clearly resource IDs cannot be used there.

If you want to localize an argument name, you can enter a resource ID in the Resource ID column of the XLL+ Function Wizard, and add a localized name with the appropriate resource ID to each language's string table in the resource file.

Note: If you can't see the ResID column in the argument grid, use the View Resource ID Column command to make it visible.

Category

In the XLL+ Function Wizard, you can select a category for your add-in function. The standard categories shown in the XLL+ Function Wizard are built into Excel. If you select one of the standard categories for your function, then it will automatically appear in the local language of the Excel version being run. See Stability : Category for more information.

Help text

The Description field and the Description column of the XLL+ Function Wizard hold descriptions of the add-in function and each of its arguments, as they will appear in the Excel Formula Wizard. They can be replaced by resource ID strings (e.g. "#100", or by strings containing resource IDs (e.g. "#101 2", for "Argument 2").

Commands

Captions and help text for menus and toolbars are set by passing arguments to the methods of CXlMenu and CXlToolbar. The following functions accept resource string IDs as arguments:

CXlMenu::Create | CXlMenu::AddItem | CXlMenu::SetTexts
CXlMenu::ReplaceItem | CXlToolbar::AddSeparator | CXlToolbar::AddTool
CXlToolbar::AddToolbar | CXlToolbar::AssignToTool | CXlToolbar::DeleteTool
CXlToolbar::DeleteToolbar | CXlToolbar::EnableTool | CXlToolbar::PressTool
CXlToolbar::SetToolBitmap | CXlToolbar::ShowToolbar |

To localize a menu, use the following techniques:

CopyC++
BOOL CMyAddinApp::OnXllOpenEx()
{
    ...
    // "#101" replaces "&My menu". The string resource 101
    // should contain the localized menu caption.
    m_menu.SetTexts(_T("#101"));

    // "#102" replaces "&My menu task". The string resource 102
    // should contain the localized menu item text.
    m_menu.AddItem(_T("#102"), "MyAddinFunction");

    m_menu.Create();
    ...
}

To localize a toolbar, use code like the following:

CopyC++
// "#4" replaces the original toolbar name. The string resource 4
// should contain the localized toolbar name.
/* static */ LPCTSTR CMyAddinApp::m_pszToolbarName = _T("#4");

BOOL CMyAddinApp::OnXllOpenEx()
{
    ...
    CXlToolbar::AddToolbar(m_pszToolbarName);
    // "#5" replaces the original tool help text. The string resource 5
    // should contain the localized tool help text.
    CXlToolbar::AddTool(m_pszToolbarName, 1, _T("Intl3_SelectLanguage"), _T("#5"));
    ...
}

void CMyAddinApp::OnXllClose()
{
    ...
    // Delete toolbar
    CXlToolbar::DeleteToolbar(m_pszToolbarName);
    ...
}

Formulae

A formula's argument separators vary according to the user's regional settings. For example, =MyFunc(A,B,C) (in English) will appear as =MyFunc(A;B;C) in German, with semicolons replacing commas. In addition, the names of built-in functions vary in different language versions of Excel. If you are setting formulae from your code, or if you are reading formulae and parsing them, you should be aware of these issues and code defensively.

See Setting formulae for a full discussion of the internationalization of formulae.

Error strings

The error strings returned by the XLL+ run-time libraries are also held in a resource file. This resource file xlpres.rc is included by the resource file in each XLL+ project.

Currently, only English strings are contained in the file. In a future release, we will provide localized error strings, and, for those languages not supported, we will provide instructions for localizing them yourself.

Visit the XLL+ web-site at http://www.planatechsolutions.com/xllplus for up-to-date information on new releases.

Next: Deployment >>

See Also

International support | Global resource functions


Deployment

An optional additional step is to isolate the resources for each language into a separate resource-only DLL. Under this architecture, the main XLL contains the resources for the primary language of the add-in, and each other language is held in a separate DLL.

Advantages

  • A new language can be added by a third party, without any changes to the original code.
  • The new language module can be distributed separately from the original add-in.

Disadvantages

  • The build process is more complicated.
  • The authors of the add-in must distribute a resource file containing a string table, so that the authors of the new language resource can use the correct IDs.
  • If new strings are added to the original version, they must also be added to each of the resource-only DLLs.
  • Distribution and installation of the add-in is more complex.

It should be clear that there is no clear-cut correct decision here. Different working environments will require different solutions, and the frequency of changes to the add-in will also influence the decision.

DLL names

You should select an appropriate naming convention for your resource-only DLLs. You will need to be able to list them using a directory search, and to be able to impute the language ID from the file name.

In our sample InterMulti.xll, we used "InterMultiRes_NNNN.dll", where NNNN is the decimal representation of the language ID, e.g. "InterMultiRes_1036.dll" for French (France). We also assumed that all the resource-only DLLs would be in the same directory as the XLL itself.

Creating a resource only DLL

To create a resource only DLL, follow these steps:

  1. Create an empty DLL project.
    • In Visual Studio 6, create a "Win32 Dynamic-Link Library" with "An empty DLL project" selected.
    • In VS .NET or VS 2005, use "Win32 Project" in the "Visual C++ Projects" group, and select Application type "DLL" under "Application Settings". Put a check against "Empty project".
  2. Add the linker option /NOENTRY to the linker settings for each build.
    • In VS 6, add "/NOENTRY" to the "Project Options" edit field in the Project Settings/Linker/Customize tab of the "Project Settings" dialog.
    • In VS.NET or VS 2005, add "/NOENTRY" to the "Additional Options" edit field in the Configuration Properties/Linker/Command line tab of the project properties dialog.
  3. Create a resource file.
    • In VS 6, create a new "Resource Script" and enter a file name with the extension ".rc".
    • In VS .NET or VS 2005, create a new "Resource File (.rc)" and enter a file name with the extension ".rc".
  4. Copy all the native-language resources from the core XLL to your new resource file.
  5. Change the language of each resource to that of the resource-only DLL, and change the text and bitmaps as required.
  6. If a resource file containing error strings is available, change the inclusion #include <xlpres.rc> to the appropriate language, e.g. #include <xlpresfrfr.rc>. For a description of these files, see here.

For more information see the topics "resource-only DLLs" in MSDN help.

Creating resource only DLLs for further languages

To support further languages, follow these steps for each language.

  1. Copy the entire project to a new (appropriately named) directory
  2. Change the name of the output DLL in the linker settings.
  3. Translate all strings and bitmaps to the new language.

Support code

You will need to write support code for the purposes listed below. See the Localized (Multiple DLLs) sample for and example of the required support code.

  1. Listing the available languages. This usually involves searching a directory for DLL files with appropriate names, and then imputing the language from the name.
  2. Determining the user's current language. You should retrieve the user's current regional settings with XllGetStringLanguageID, and then try to match one of the available languages. If no complete match is available, then you should try to match the main language only (ignoring sub-language).
  3. Loading the DLL. Once you have determined the full file path of the DLL, use ::LoadLibrary() to get its instance handle, and pass it to XllSetStringResourceHandle.
  4. Reload all resources. If you change the language at run-time, after the XLL has been loaded, you should (i) unregister all localized resources, (ii) set the resource handle using XllSetStringResourceHandle and (iii) re-register localized resources.

Deployment

There are any number of ways to deploy the resource-only DLLs. Examples include:

  1. Named sub-directories. All resource-only DLLs have the same name. Each is held in a sub-directory which reflects the language ID. e.g. "1033\MyDll.dll", "1036\MyDll.dll". This technique is used by MSDN.
  2. Named files using numeric IDs, e.g. "MyDllRes_1033.dll", "MyDllRes_1036.dll". This technique is used by the Localized (Multiple DLLs) sample.
  3. Named files using language acronyms, e.g. "MyDllFRA.dll", "MyDllENU.dll". This method is used by MFC.

Whatever technique you have chosen for determining the name and path of your resource-only DLLs, you must ensure that they are delivered to the appropriate directory when the XLL itself is installed.

Example

You can find an example of this technique in the Localized (Multiple DLLs) sample.

Next: Conversion of an existing project >>

See Also

International support | Global resource functions


Conversion of an existing project

This topic walks through the steps required to convert a single-language add-in to support multiple languages. The examples below assume that the name of the addin is MyAddin.

Step | Topic
1 | Review your function categories
2 | Create a string table resource
3 | Replace hard-coded strings
4 | Localize add-in functions
5 | Test single language version
6 | Add additional languages
7 | Test new language version
8 | Build resource-only DLLs

1. Review your function categories

Look at each of the categories you have chosen for your add-in functions. If you can use a standard (built-in) category, then do so. You will not have to do any further work to localize built-in categories.

See Stability : Category for more information.

2. Create a string table resource

In Visual Studio 6, use the Insert/Resource... menu, and select "String Table", as shown below.

In Visual Studio .NET or Visual Studio 2005, select the resource file MyAddin.rc in the Resource View, and use the Edit/Add Resource... menu, and select "String Table", as shown above.

Press "New" to add the resource. It will be added in your default language. If necessary, you should change it's Language property to match the current language of your add-in.

3. Replace hard-coded strings

Look through your code, and copy any strings you find to your new string table resource. Replace the existing string with a resource id. In particular, look at the strings discussed below.

Library name

The library name is declared near the top of your main .cpp file, and contains the name you selected in the XLL+ AppWizard when you created the project.

CopyC++
/* static */ LPCTSTR CMyAddin::m_pszDefName = "New XLL";

Add a new string to the string table.

In Visual Studio .NET or or Visual Studio 2005, fill in the columns of the string table as shown in the example below (obviously, you should replace "New XLL" with the display name of your add-in).

Change the library name definition as follows.

CopyC++
/* static */ LPCTSTR CMyAddin::m_pszDefName = _T("#1");

Menus

If you have included a menu in your project, replace the strings with resources. For the following menu:

CopyC++
m_menu.SetTexts(_T("&My menu"));
m_menu.AddItem(_T("&My menu task"), _T("MyAddinFunction"));
m_menu.Create();

Add these resources:

And amend the code as follows:

CopyC++
m_menu.SetTexts("#2");
m_menu.AddItem("#3", "MyAddinFunction");
m_menu.Create();

Toolbars

If you have included a toolbar in your project, replace the strings with resources. For the following toolbar declaration:

CopyC++
/* static */ LPCTSTR CMyAddinApp::m_pszToolbarName = _T("MyAddin");

BOOL CMyAddinApp::OnXllOpenEx()
{
    ...
    CXlToolbar::AddToolbar(m_pszToolbarName);
    CXlToolbar::AddTool(m_pszToolbarName, 1, _T("MyAddinFunction"), _T("My addin function"));
    CXlToolbar::SetToolBitmap(m_pszToolbarName, 1, IDB_BITMAP1);
    CXlToolbar::ShowToolbar(m_pszToolbarName, true, CXlToolbar::DockRight);
    ...
}

Add these resources:

And amend the code as follows:

CopyC++
/* static */ LPCTSTR CMyAddinApp::m_pszToolbarName = _T("#4");

BOOL CMyAddinApp::OnXllOpenEx()
{
    ...
    CXlToolbar::AddToolbar(m_pszToolbarName);
    CXlToolbar::AddTool(m_pszToolbarName, 1, _T("MyAddinFunction"), _T("#5"));
    CXlToolbar::SetToolBitmap(m_pszToolbarName, 1, IDB_BITMAP1);
    CXlToolbar::ShowToolbar(m_pszToolbarName, true, CXlToolbar::DockRight);
    ...
}

4. Localize add-in functions

Use the XLL+ Function Wizard to inspect each of your add-in functions. Copy the function description and each argument name and description to the string table.

For a function which initially looks like this:

Add strings to the string table as follows:

Then return to the XLL+ Function Wizard and amend the function as shown below:

Notes

  1. If you can't see the Resource ID column in the Function Wizard, right-click on the argument grid header, and put a check against the View Resource ID Column command.
  2. The resource ID names used above (e.g. "IDS_LIBNAME", "IDS_FN1_DESC" are arbitrary (but meaningful). These IDs are not usually used in your code - only the numerical version is required.
  3. The function's name is not localized. See String types : Function Names for an explanation.

5. Test single language version

At this point it is worth rebuilding your add-in and testing it. Open your add-in in Excel and use the Excel Formula Wizard to inspect each function's description and argument names and descriptions. The example above should look like this:

6. Add additional languages

To add a new language to the add-in, do the following.

  1. Copy the string table.

    You can use the Insert Copy... command by right-clicking on the string table in Resource View.

  2. Select the language of the new table in the dialog that pops up.

  3. Edit the new string table, and translate each string. Leave the numbers and resource ID names unchanged.

  4. Add error messages in the new language, if available.

    Look in the XLL+ include directory to see if there is a resource file for the new language. Each language file is named xlpresxxyy.rc where xx is the language name, e.g. fr for French, and yy is the sub-language name, e.g. fr for France.

    If the file is present, include it in your resource file by using the "Resource Includes..." command:

    Add the language-support resource file, as shown below:

7. Test new language version

  1. Rebuild your add-in.
  2. Use the Control Panel Region Settings applet to change your current language to the new language.
  3. Open your add-in in Excel. You will see that the menu and toolbar now have new captions.

  4. Use the Excel Formula Wizard to inspect each function's description and argument names and descriptions. The example above should look like this:

8. Build resource-only DLLs

An optional additional step is to isolate the resources for each language into a separate resource-only DLL. Under this architecture, the main XLL contains the resources for the primary language of the add-in, and each other language is held in a separate DLL.

See Deployment for a full discussion of this technique.

Next: Introduction to asynchronous functions >>

See Also

International support | Global resource functions


Asynchronous functions

This chapter contains the following topics:

Introduction to asynchronous functions
Requirements for asynchronous functions
How asynchronous functions work
Upgrading asynchronous functions from XLL+ 6.0


Introduction to asynchronous functions

If a function takes a very long time to complete, Excel is locked and unusable in the meantime. It is sometimes useful to run the function asynchronously, in a separate thread, so that Excel remains available while the function completes. While the calculation is continuing, the target cell will display "#WAIT!", and when it is complete, the result will automatically be updated to display the result.

The XLL+ Function Wizard now lets you create an asynchronous version of a function with no coding.

Creating an asynchronous function

Let us use a ready-made slow function, AvgOptValue, which can be found in the AvgOpt sample application.

This function runs a MonteCarlo simulation to calculate the value of an average price option, and can take a very long time to run.

Adding an asynchronous version of the function is very simple: just open up the function in Xll+ Function Wizard and put a check against "Create asynchronous version" on the Features tab:

The Wizard will now create an extra add-in function, AvgOptValueAsync, which will be available in Excel along with AvgOptValue.

Using an asynchronous function

As far as the user is concerned, there is no difference between using AvgOptValue and using AvgOptValueAsync.

When the function is called, it will initially return "#WAIT!".

Excel will remain usable, and the user can continue to move around the workbook and make changes to it.

Once the function has completed, the cell will automatically be recalculated, and this time it will return the result.

Note: in versions 6.0.0 to 6.0.4 of XLL+, asynchronous functions required an extra argument, RtdSignalCell. Since XLL+ 6.2, this argument in no longer needed, after an enhancement of the implementation of asynchronous functions. See Upgrading asynchronous functions from XLL+ 6.0 for more information

Developing asynchronous functions

Before you begin using or building the sample code, make sure that your development platform and target environment will support the model: check the requirements in Requirements for asynchronous functions.

Next: Requirements for asynchronous functions >>


Requirements for asynchronous functions

Requirements

Excel version
This model uses Excel's RTD mechanism, which is only available in Excel XP upwards. It cannot be used with Excel 97 or Excel 2000.
Operating system
The model requires Windows 2000 or above, since Windows 98 does not support multi-threading.

Deliverables

The deliverables required for the projects discussed here include the following files and folders:

File | Description
Samples/AvgOptAsync | Source code for the asynchronous Excel add-in discussed below.
Samples/XllRtdLink | Source code for the RTD server discussed below.
Samples/Bin/XllRtdLink.dll | Compiled RTD server module.

Installation

The model uses a COM module (XllRtdLink.dll) to support Excel's RTD mechanism. You should register the RTD server module XllRtdLink.dll, in one of the following ways:

  1. Use REGSVR32 at the command line, e.g.

    REGSVR32 "C:\Servers\win32\XllRtdLink.dll"

    Ensure that you register the correct version of the DLL: on a machine with 64-bit Excel, you should register the 64-bit version of the file, which can be found in redist\x64, whereas on a machine with 32-bit Excel, you should register the 32-bit version of the file, which can be found in redist\win32.

  2. Build the project Servers\XllRtdLink\XllRtdLink.sln. Choose either the Debug or the Release MinDependency build.

Note: The XllRtdLink DLL is automatically registered when you install the XLL+ toolkit on a development machine. You only need to register it yourself when you deploy XLLs with asynchronous functions to another machine.

Next: How asynchronous functions work >>


How asynchronous functions work

RTD

The implementation of asynchronous functions uses Excel's Real-Time Data (RTD) mechanism. This feature lets you use a formula such as:

=RTD("my.server",,"my.data.topic")

Whenever the RTD server (my.server) changes the value of topic my.data.topic, Excel will automatically update the cell containing the RTD formula with a new topic value.

This mechanism is widely used for data-feeds.

How asynchronous functions use RTD

Within the implementation of an asynchronous function such as AvgOptAsync, the framework makes a call into Excel to evaluate an RTD formula, e.g.:

=RTD("xllrtdlink.xllrtdseqnumserver",,"{5AAB8CEC-FCED-457C-A742-2F13F37ABAD5}")

The first argument is the name of the XLL+ RTD link server, contained in XllRtdLink.dll. The last argument is an arbitrary unique string generated by the framework to track this particular calculation.

Because Excel has registered that this calculation depends on the value of the RTD topic "{5AAB8CEC-FCED-457C-A742-2F13F37ABAD5}", the formula will be recalculated whenever the value of this RTD topic changes.

As soon as the XLL's worker thread has completed a calculation, it tells the RTD server to update the appropriate, uniquely named, topic (e.g. "{5AAB8CEC-FCED-457C-A742-2F13F37ABAD5}"). The RTD cell updates; Excel calls the function again, and the add-in function responds with the correct answer, which it now has available in a cache.

During this second call, the add-in function does not make a call to Excel to evaluate =RTD(...). Excel registers the fact that the cell no longer depends on the RTD topic, and the cell is no longer liable to asynchronous update.

For more details on the mechanisms underlying the RTD link implementation, see Real-time data overview, which uses the same technology, but shows all the code written by hand.

Next: Upgrading asynchronous functions from XLL+ 6.0 >>


Upgrading asynchronous functions from XLL+ 6.0

Note: this topic describes issues arising with asynchronous add-in functions developed using XLL+ version 6.0. If you have not developed or released any such functions, you can safely skip this topic.

Older model

The implementation of asynchronous functions was changed significantly in version 6.2 of XLL+. Asynchronous add-in functions generated by early versions of XLL+ 6 used an extra argument, RtdSignalCell, which was used as a channel for RTD update notifications. This model required the use of an extra cell, controlled by the add-in, to contain the argument.

This model, while it was transparent in its workings, was found to be inconvenient. The revised model introduced in XLL+ version 6.2 uses a less intrusive technique. All the RTD calls are made "under the hood", inside the asynchronous function's implementation. There is no longer any need for the extra cell.

The new model has several advantages:

  • There is no longer any need for the extra argument, so the signatures for the synchronous and asynchronous versions are now identical.
  • The RtdSignalCell is no longer altered by the add-in, which was an intrusive technique which was liable to reduce user confidence.
  • The new model is more robust.
  • The new model is slightly more efficient in performance.

Upgrading to the new model

To upgrade existing asynchronous functions to use the new model, use the XLL+ ToolWindow to select all functions that have an asynchronous version, and use the Regenerate functions command.

Supporting existing spreadsheets

If you have created asynchronous functions using XLL+ 6.0, and there are spreadsheets that use them, then the new model will break these spreadsheets. Because they use an extra argument, the cells that call them will simply return error values.

You can avoid this problem by using the UseAsyncHandleModel property.

Note: This is an advanced property, which is normally hidden by the user interface. To view and edit an advanced property in the XLL+ ToolWindow, set the ShowAdvancedProperties property in the XLL+ Options page to true. To see advanced properties in the XLL+ Function Wizard, use the Show Advanced Properties command.

Set the property to True for all asynchronous functions that are already in use. The Function Wizard will add an extra argument RtdSignalCell, exactly as in the old model. The argument will be completely ignored by the Asynchronous function, and can safely be omitted by all new users of the add-in function.

Next: Queued functions >>


Queued functions

Beginning in Excel 14 (Excel 2010), functions can be marked as "Asynchronous". This flag does not mean that the functions immediately return "#WAIT!", run asynchronously and inform Excel when they have finished; see Asynchronous functions for this behavior.

The effect of the new Asynchronous flag is more subtle. If a function is marked as thread-safe then many threads may be running the same function at the same time. If the function makes use of a shared resource, such as a database, then all but one of the threads may be locked out, waiting for the thread currently using the resource to complete.

If the function is also marked as asynchronous, then Excel will call the function and immediately return, without waiting for the result. The branches of the recalculation tree whch are affected by the current cell will not be calculated at this time, but will be queued to be dealt with later. The calculation thread can now be used to resolve some other part of the tree, which is ready to be calculated. It is the responsibility of the add-in function to dispatch the task to a background thread, and to inform Excel when the background thread has completed the task (by calling the SDK call-back function xlAsyncReturn).

Once Excel has received the xlAsyncReturn signal, it knows that the cell is ready, and can continue to calculate the branches of the tree that were queued.

The effect of the behavior on functions which compete for the same resource can be very powerful: performance can improve by 100% or even more.

Creating a queued function

To create a queued version of a function, use the Features tab of the XLL+ Function Wizard. In the Behavior section, put a check against Create queued version.

An additional version of the function will be generated by the wizard, with the suffix "Queued". For example, a function "GetBid" will have a queued version name "GetBidQueued". The developer is responsible for coding the "GetBid" function, as a normal synchronous function. The wizard will create the queued version, and will write all the thread management code.

After experimenting with the queued version, you may decide that the queued version is more effective than the synchronous version, and that you therefore do not need to offer the synchronous version to the user. At this point you can use the Hide synchronous version flag.

The synchronous version of the function wil be renamed, e.g. "GetBidSync", and will be hidden, so that it does not appear in the Excel Formula Wizard. The queued version will be shown in Excel without the "Queued" suffix, e.g. "GetBid".

Implementation

The XLL+ Function Wizard generates all the code that implements the asynchronous behavior.

A class will be created that holds a copy of the input values, e.g. CGetBid_XlAsyncFunctionInputs. The class is derived from a base class CXlAsyncFunctionInputs, which handles the implementation details.

A thread function (e.g. GetBid_XlAsyncThreadFn) will be created, which will be run in the background thread. The thread function simply calls the synchronous version of the function, saves the results, and signals Excel that the calculation is complete, by calling the xlAsyncReturn SDK call-back.

A wrapper function which implements the queued behavior will also be generated, along with the code to register it as an add-in function. The wrapper function packages all the inputs into the class declared above (e.g. CGetBid_XlAsyncFunctionInputs), and invokes the CXlAsyncManager class which will dispatch the task to a background thread.

Older versions of Excel

Version of Excel earlier than Excel 2010 do not support the "asynchonous" flag, and therefore an additional registration is made if the Excel version is found to be 2007 or earlier. This registers the synchronous version of the function, and no attempt is made to register the queued version of the function. For the user, there is no difference in behavior, only a difference in performance.

Next: Using CUDA with XLL+ projects >>


CUDA

This chapter contains the following topics:

Using CUDA with XLL+ projects
Getting started with CUDA
Add-in functions that use CUDA
Working without CUDA
Floating point types
Deployment
Sample project


Using CUDA with XLL+ projects

This section explains how to use the XLL+ toolkit with the CUDA developer's toolkit.

The CUDA developer's toolkit allows programmers to use an Nvidia Graphical Processing Unit (GPU) to accelerate the performance of mathematics-intensive code, by applying massive parallelization. Using the techniques described in this section, it is possible to create add-ins that achieve huge performance gains: improvements of over 100x have been regularly achieved by using the GPU for parallel processing.

For more information please see the Nvidia developer zone at http://developer.nvidia.com/cuda-toolkit.

A sample project that uses CUDA is included in the XLL+ toolkit: AvgOptCuda.

Next: Getting started with CUDA >>


Getting started with CUDA

There are several steps required to add CUDA support to an XLL+ project.

  1. Install the Nvidia GPU toolkit
  2. Create an XLL+ project
  3. Add CUDA support to the project
  4. Add CUDA source file(s) to the project
  5. Complete the CUDA support by changing various project settings

Install the Nvidia GPU toolkit

Warning: take extreme care when installing new drivers on a computer, and consult with support staff as required.

  1. Locate the Nvidia GPU toolkit at the Nvidia Developer Zone (http://developer.nvidia.com/cuda-toolkit). This topic assumes that production release 4.1 is used.
  2. Check whether your computer has an appropriate graphics card before continuing; a list of CUDA-supporting cards is available at the Nvidia Developer Zone.
  3. Download and install the latest Nvidia developer drivers.
  4. Download the "CUDA Toolkit Downloads" (Windows), either 32-bit or 64-bit, and install it. Note that if you install the 32-bit toolkit you will not be able to build 64-bit code, but that the 64-bit toolkit will let you build both 32-bit and 64-bit add-ins.
  5. Optionally, download the "GPU Computing SDK Downloads" (Windows) and install it.

Create an XLL+ project

Using XLL+ 7, create a standard XLL+ add-in project.

You should choose the STL run-time libraries, not the MFC libraries. This guide assumes that you create a 64-bit version as well as a 32-bit version.

Add CUDA support to the project

In Visual Studio 2010, select the project in the Solution Explorer and right-click the Build Customizations... menu.

Put a check against CUDA 4.1 (.targets, .props), as shown below, and click OK.

In Visual Studio 2008 or 2005, select the project in the Solution Explorer and right-click the Custom Build Rules... menu.

Put a check against CUDA Runtime API Build Rule, as shown below, and click OK.

Add CUDA source file(s) to the project

This step is a little more complicated than it should be because the CUDA support in Visual Studio is incomplete:- .cu files are not available in the New File dialog.

  1. Open the File/New/File... dialog and select General/Text File; Click OK.
  2. Select the File/Save as... command. In the dialog, navigate to the project directory. Set Save as type to All Files (*.*). Save the (still empty) file as (e.g.) YourFileName.cu.
  3. Right-click the Source Files node in the Solution Explorer window. Select the Add/Existing Item... command. Select YourFileName.cu and click on OK.

Complete the CUDA support by changing various project settings

Note that this step needs to follow after the Add CUDA source file step above, because the CUDA C/C++ node will not appear in the Project Properties dialog until after a .cu file has been added.

Under Visual Studio 2010:

  1. Show the project properties and select the CUDA C/C++ / Host node. For the release build, set the Run-time Library to Multi-Threaded (/MT). Do this for both the 32-bit and the 64-bit builds. Switch to the debug build and set the Run-time Library to Multi-Threaded Debug (/MTd). Again, do this for both the 32-bit and the 64-bit builds.
  2. Select Debug configuration and All Platforms, and go to the Linker / Input node. Add the following to the start of the Additional Dependencies list:
    xlllibsd.lib;cudart.lib;curand.lib;
    Select Release configuration and All Platforms, and remain on the Linker / Input node. Add the following to the start of the Additional Dependencies list:
    xlllibsr.lib;cudart.lib;curand.lib;

Under Visual Studio 2008 or 2005:

  1. Show the project properties and select the CUDA Runtime API / Host node. For the release build, set the Run-time Library to Multi-Threaded (/MT). Do this for both the 32-bit and the 64-bit builds. Switch to the debug build and set the Run-time Library to Multi-Threaded Debug (/MTd). Again, do this for both the 32-bit and the 64-bit builds.
  2. Select Debug configuration and All Platforms, and go to the Linker / Input node. Add the following to the start of the Additional Dependencies list:
    xlllibsd.lib cudart.lib curand.lib;
    Select Release configuration and All Platforms, and remain on the Linker / Input node. Add the following to the start of the Additional Dependencies list:
    xlllibsr.lib cudart.lib curand.lib;
  3. Select All configurations and All Platforms, and go to the Linker / General node. Add the following to the end of the Additional Library Directories list:
    $(CUDA_PATH)lib\$(PlatformName)
  4. Select Release configuration and x64 platform, and go to the CUDA Runtime API / Host node. Set the Target Machine Platform to x64.
  5. Select Debug configuration and x64 platform, and go to the CUDA Runtime API / Host node. Set the Target Machine Platform to x64.

Note that because of a bug in the GPU toolkit, under Visual Studio 2008 and 2005, you may need to (a) close the Project Properties dialog, (b) change the active configuration and/or platform and then (c) reopen the Project Properties dialog each time you make a change to the CUDA Runtime API node or any of its child nodes.

You should now be able to build the project under all configurations and platforms.

Next: Add-in functions that use CUDA >>


Add-in functions that use CUDA

Separation of code

You should not mix the code that contains the add-in function and the code that uses the GPU. Always keep the two sets of code in separate files. Use a header file to declare the CUDA functions, and include that in the add-in functions' source file.

Your CUDA code (in .cu files) cannot include the XLL+ headers, since they use C++ language features such as recursion that are not supported in CUDA code.

Similarly, your add-in functions should not include CUDA language extensions.

Structures shared between add-in function and GPU

If you pass structured data between the host and the GPU's global shared memory, you will find it much easier to pack it into a "flat" format than to support pointers within the structure. For example, the code below supports a format that contains a yield curve of variable size:

CopyC++
struct YieldCurvePoint {
    int date;
    double yield;
};

struct YieldCurve {
    unsigned int count;
    YieldCurvePoint points[1];
};

#define YIELDCURVE_SIZE(count) \
    (sizeof(YieldCurve) + (sizeof(YieldCurvePoint) * (count - 1)))

To allocate and populate the structure from C++ code, you might use the following class:

CopyC++
class YieldCurveHolder {
public:
    YieldCurveHolder() : data(0) {}
    ~YieldCurveHolder()
    {
        deallocate();
    }
    YieldCurveHolder(const std::vector<long>& dates,
                     const std::vector<double>& yields)
    {
        unsigned count = static_cast<unsigned int>(dates.size());
        allocate(count);
        data->count = count;
        for (unsigned int i = 0; i < count; i++)
        {
            data->points[i].date = static_cast<int>(dates[i]);
            data->points[i].yield = yields[i];
        }
    }
    void allocate(unsigned int count)
    {
        data = (YieldCurve*)new char[YIELDCURVE_SIZE(count)];
    }
    void deallocate()
    {
        if (data)
        {
            delete[] (char*)data;
            data = 0;
        }
    }
public:
    YieldCurve* data;
};

This helper class ensures that memory is correctly allocated, and reliably freed. This simplifies the code that uses the structure and is particularly important when exceptions may be thrown.

Next: Working without CUDA >>


Working without CUDA

You should consider how to handle the situation where there is no appropriate GPU available. There are several reasons why you might include a non-GPU alternative:

  • Performance comparison between GPU and non-GPU (CPU) versions
  • Debugging
  • Convenience of deployment

If you decide to support a non-GPU version, you should provide a function that tests for the presence and capabilities of a GPU, such as the following:

CopyC++
bool IsGpuAvailable(bool doublePrecisionRequired)
{
    cudaError_t cudaResult;
    struct cudaDeviceProp deviceProperties;

    // Get device properties
    cudaResult = cudaGetDeviceProperties(&deviceProperties, 0);
    if (cudaResult != cudaSuccess)
    {
        return false;
    }

    // Check precision is valid
    unsigned int deviceVersion = deviceProperties.major * 10 + deviceProperties.minor;
    if (doublePrecisionRequired && (deviceVersion < 13))
    {
        return false;
    }

    return true;
}

Next: Floating point types >>


Floating point types

Different GPU cards offer varying levels of support for double-precision floating-point numbers. You may therefore decide to support both single- and double-precision floating-point numbers in your GPU code.

It is generally easiest to support multiple floating-point types through the use of templated classes, where the floating-point type is the parameter of the template class.

If you decide to use this approach, then you may also benefit by using the C++ SharedMemory class supplied by Nvidia, a copy of which is in the sample file AvgOptDevice.cu in the AvgOptCuda sample project.

Next: Deployment >>


Deployment

When deploying CUDA add-ins to a machine other than the development machine, you must ensure that the appropriate CUDA run-time DLLs are also present. These include cudart*.dll and optionally curand*.dll, cufft*.dll, cusparse*.dll and cublas*.dll.

It is not enough to deliver these to the directory that contains the XLL add-in. They need to be delivered either to a directory on the machine's PATH or to the directory that contains EXCEL.EXE.

Next: Sample project >>


Sample project

The standard XLL+ sample project, AvgOpt, has been revised to support GPU code. The new sample project is named AvgOptCuda.

Building the project

The project contains both 32-bit and 64-bit builds. You should make sure that you use the appropriate build for your version of Excel.

Performance

The table below gives some sample performance ratios on various hardware combinations. The time taken (in milliseconds) for a calculation is shown for both double- and single-precision calculations, along with the ratio of GPU performance to CPU performance.

The best performance in the tables below reduced a 40 second calculation to less than 1/5th of a second; this order of performance improvement may well be considered worth the programming effort required.

100,000 iterations
CPU | GPU | Excel | Precision | CPU (ms) | GPU (ms) | Ratio
i7-2600 (3.40 GHz) | Geforce GTX 560 Ti (1.25 Gb) | 32-bit | double | 3626 | 49 | 74
i7-2600 (3.40 GHz) | Geforce GTX 560 Ti (1.25 Gb) | 32-bit | single | 3981 | 35 | 113
i7 870 (2.93 GHz) | Geforce GTX 460 (1 Gb) | 64-bit | double | 3978 | 70 | 57
i7 870 (2.93 GHz) | Geforce GTX 460 (1 Gb) | 64-bit | single | 3649 | 40 | 91

200,000 iterations
CPU | GPU | Excel | Precision | CPU (ms) | GPU (ms) | Ratio
i7-2600 (3.40 GHz) | Geforce GTX 560 Ti (1.25 Gb) | 32-bit | double | 7246 | 77 | 94
i7-2600 (3.40 GHz) | Geforce GTX 560 Ti (1.25 Gb) | 32-bit | single | 7910 | 51 | 156
i7 870 (2.93 GHz) | Geforce GTX 460 (1 Gb) | 64-bit | double | 7938 | 121 | 65
i7 870 (2.93 GHz) | Geforce GTX 460 (1 Gb) | 64-bit | single | 7237 | 62 | 116

1,000,000 iterations
CPU | GPU | Excel | Precision | CPU (ms) | GPU (ms) | Ratio
i7-2600 (3.40 GHz) | Geforce GTX 560 Ti (1.25 Gb) | 32-bit | double | 36335 | 311 | 117
i7-2600 (3.40 GHz) | Geforce GTX 560 Ti (1.25 Gb) | 32-bit | single | 39983 | 172 | 232
i7 870 (2.93 GHz) | Geforce GTX 460 (1 Gb) | 64-bit | double | 39610 | 551 | 72
i7 870 (2.93 GHz) | Geforce GTX 460 (1 Gb) | 64-bit | single | 35991 | 252 | 143

Next: Logging framework >>


Logging

This chapter contains the following topics:

Logging framework
Directing log events
Using the logging macros
Configuring the logging framework
Configuration files
Formatting patterns


Logging framework

XLL+ (from version 6.2 onwards) contains a logging framework, cpplog, which helps you to write diagnostic and other information to log files.

log4cxx

The API for this framework is based on that of the Apache Foundation's log4cxx. log4cxx is more efficient, more powerful and more complete than cpplog. However, it is a lengthy package to install, needs extra steps to build, and comes with a lot of extra baggage.

The cpplog framework is designed so that it is trivial to switch from it to log4cxx, if you wish. If at any time you find that the cpplog framework is not providing the functionality or performance that you need, you should consider switching to log4cxx.

Overview

There are 3 aspects to logging using this framework, which are described in more detail in the next topics:

  • Directing log events.

    Your code decides which logging node - known as a logger - your logging events will be sent to. This will control the routing of the event and, therefore, control which files, streams and other log destinations the event will be written to.

  • Generating log events.

    Your code should include log statements, which report a message, perhaps other state data, and a severity level. These are always expressed in the form of macros, such as LOG_ERROR(logger, "Something went wrong");

  • Configuring the logging framework.

    You, or the user of your software, decides which messages will go to which logging devices, such as files, email, event logs or trace streams.

Example

Below is a class that writes to the logging framework.

CopyC++
class MyClass
{
private:
    static LoggerPtr m_logger;
public:
    void DoSomething(int value, const TCHAR* str)
    {
        LOG_INFO(m_logger, _T("About to do something with ") << value << _T(" and ") << str);
        LOG_TRACE(m_logger, _T("Leaving DoSomething"));
    }
};

LoggerPtr MyClass::m_logger = Logger::getLogger(_T("MyClass"));

Note the LOG_xxx macros in the DoSomething method. The first macro means:

  1. Look at the logger pointed to by m_logger.
  2. If the logger is set to report log events of INFO level or above, continue. Otherwise, stop now.
  3. Evaluate the expression on the right - "About to do something with [value] and [str]" - and stream it to all attached log sinks.

Below is the context within which the above logging code is used:

CopyC++
int _tmain(int argc, _TCHAR* argv[])
{
    // Configure the logging framework
    BasicConfigurator::configure(_T("%-5p %c - %m%n"), LL_DEBUG);

    // Get a logger pointer and use it
    LoggerPtr logger = Logger::getLogger(_T("main"));
    LOG_DEBUG(logger, _T("Starting main"));

    // Create an instance of MyClass, and use it.
    MyClass c;
    c.DoSomething(15, _T("a string value"));

    // Write to the "main" logger
    LOG_DEBUG(logger, _T("Leaving main"));
}

The first part configures the root logger to write events of severity level DEBUG and above to the console, using a simple formatting pattern. In effect this means that all events except TRACE events will be reported.

The second part gets a logger pointer for the logger "main", which it then uses to write a debug event.

After creating and using an instance of MyClass - which also does some logging - the last part of _tmain writes another debug message to the log.

The output to the console will be as follows:

DEBUG main - Starting main
INFO  MyClass - About to do something with 15 and a string value
DEBUG main - Leaving main

Notice that the TRACE event from DoSomething() is suppressed, because it is of a lower severity than any of the loggers that it is sent to. All other events are reported to the console.

Next: Directing log events >>


Directing log events

Retrieving a logger pointer

Before you can start writing events to the log, you need to call Logger::getLogger to retrieve a pointer to a Logger object, using the name of the Logger through which you wish to route your logging events. Typically, the Logger pointer is acquired during initialization, by making the pointer a static member of the class being logged.

There only needs to be one statement of this kind for any class.

CopyC++
using namespace psl::log;

class MyClass {
protected:
    static LoggerPtr m_logger;
public:
    void DoSomething();
};

LoggerPtr MyClass::m_logger = Logger::getLogger(_T("MyClass"));

Note the use of the _T() macro for the string argument. If you use this technique, your code will compile and work in Unicode as well as in ANSI builds.

Hierarchy

The loggers are nodes in a hierarchy. Within the hierarchy a logger named x.y is considered to be a child of logger x, and a logger x.y.z is considered to be a child of logger x.y.

The root logger has no name, and is considered to be the parent of logger x, and all other loggers whose name does not include a period. The root logger can be acquired by calling Logger::getRootLogger(), and it is referred to in configuration files as log.rootLogger.

Any setting applied to a parent node will apply to all its descendents, uinless they have their own settings. Consider the following configuration file settings:

log.rootLogger=ERROR, F
log.X=TRACE
log.X.Y.Z=INFO

The logging levels resulting from these settings are:

Logger | Level
Root | ERROR
x | TRACE
x.y | TRACE (inherited from x)
x.y.z | INFO

Note that if an intermediate parent node is not specified, it is assumed to exist. Thus if there are two loggers x.y.z and x, an intermediate logger x.y will be created, as the parent of logger x.y.z and the child of logger x.

Next: Using the logging macros >>


Using the logging macros

You can find a full list of the logging macros here.

A logging macro takes two arguments. The first is a logger pointer, acquired as described in Directing log events.

The second argument is an expression which will be appended to the logger output streams. You can use any expression which can be used with std::ostream on the right-hand-side of a << operator. It can be a simple string, a number, or any object that supports the output stream operator. The expression may include any number of items, each separated by a << operator.

CopyC++
void MyClass:DoSomething()
{
    LOG_DEBUG(m_logger, "Starting some function");
    if (failed)
    {
        LOG_FATAL(m_logger, "Fatal error condition. rc = " << rc);
        exit();
    }
    LOG_ERROR(m_logger, "Invalid option selected.");
    LOG_WARN(m_logger, "File " << strFileName << " contains errors and will be ignored.");
    LOG_INFO(m_logger, "Got user input. value = " << value << "; rc = " << rc);
    for (int i = 0; i < 1000; i++)
    {
        LOG_TRACE(m_logger, "Some low-level info. " << i);
    }

    LOG_DEBUG(m_logger, L"Use wide strings for Unicode builds.");
    LOG_FATAL(m_logger, _T("This will work under both Unicode and ANSI builds. rc = ") << rc);
}

Severity levels

The severity level of the log event is implied by the macro name. For a list of severity levels, in order of severity, see LogLevel.

What happens to the log events that you generate depends on how the logging framework has been configured. If your event is of sufficiently high severity, it will be written to all the appenders that are currently attached to the logger and its ancestors.

Unicode

Strings must be in the appropriate format for the character set used by the build. If you are building in Unicode, the strings must be wide, e.g. std::wstring, L"My Unicode string". If the build uses MBCS, then you should use narrow strings, e.g. std::string, "My Unicode string".

You can avoid trouble by using the _T() macro for all literal strings, so that your code will build under either or both character sets.

Static destructors

The logging macros should not be used during the destructor of a statically declared object; if you do so, the results are unpredictable, and may cause Excel to crash.

Next: Configuring the logging framework >>


Configuring the logging framework

The logging framework is initialized at run-time by using one of the following configurator classes (or by writing your own):

Class | Description
BasicConfigurator | Configures the logging framework to write errors to the console.
PropertyConfigurator | Configures the logging framework by reading settings from a text file.
ModulePropertyConfigurator | Configures the logging framework by reading a text file, whose name and location is relative to the currently executing module.
XllConfigurator | Configures the logging framework by reading a text file, whose name and location is relative to the XLL add-in.

For an XLL add-in, the XllConfigurator is the best choice. The configure() method takes one optional argument:

CopyC++
static bool XllConfigurator::configure(bool bIgnoreMissingFile=true);

For an XLL C:\MyAddinDir\MyAddin.xll, the XllConfigurator will look for a configuration file C:\MyAddinDir\MyAddin.xll.log.ini. If it fails during configuration, it will (i) display an error message (ii) write the error to an error file and (iii) return false. If it succeeds, it will return true.

If you pass true for bIgnoreMissingFile, then a missing configuration file will not be treated as an error. The process will fail elegantly: logging will not be started, but no error code will be returned. If bIgnoreMissingFile is false, then a missing configuration file will be treated as an error.

Your OnXllOpenEx() method should call XllConfigurator::configure() and should handle the return value appropriately, by immediately returning FALSE if XllConfigurator::configure() returns false. This will prevent the add-in from loading. See the LogDemo sample for an example of this configuration pattern.

XLL+ AppWizard

If you select Enable Logging in the XLL+ AppWizard, your new add-in project will contain code to initialize the logging framework and also a log configuration file.

Next: Configuration files >>


Configuration files

The configurator classes PropertyConfigurator and ModulePropertyConfigurator can load configuration files at run-time. This topic discusses the format of these files.

The configuration file format for cpplog is a subset of that used by log4cxx.

  • Each statement is on a single line.
  • Empty lines and comment lines that start with the hash character, '#', are ignored.
  • Each line consists of a "identifier=value" pair, without spaces.

Example

# Comment

log.rootLogger=ERROR, A, B

log.appender.A=AtlTraceAppender
log.appender.A.layout=PatternLayout
log.appender.A.layout.ConversionPattern=%-5p %c - %m%n

log.appender.B=FileAppender
log.appender.B.File=c:\Logs\RtdHandleServer_log.txt
log.appender.B.layout=PatternLayout
log.appender.B.layout.ConversionPattern=%-20.20d %-5p %c - %m [%l]%n

log.appender.C=RollingFileAppender
log.appender.C.File=%TMP%\Logs\RtdHandleServer_log_%t.log

log.logger.RtdHandleServer.Global=ERROR
log.logger.RtdHandleServer.CXllRtdHandleServer=TRACE
log.logger.RtdHandleServer.CTopicTable=TRACE

Root logger

log.rootLogger=Level[, AppenderName...]

Part | Description
Level | One of FATAL, ERROR, WARN, INFO, DEBUG, TRACE. Not case-sensitive.
AppenderName | The name of an appender defined in the same file (see below).

Examples

log.rootLogger=ERROR, A, B
log.rootLogger=TRACE

Logger

log.logger.LoggerName=Level[, AppenderName...]

Part | Description
LoggerName | The full name of the logger, case-sensitive.
Level | One of FATAL, ERROR, WARN, INFO, DEBUG, TRACE. Not case-sensitive.
AppenderName | The name of an appender defined in the same file (see below).

Examples

log.logger.RtdHandleServer=ERROR, FileAppender1
log.logger.RtdHandleServer.CXllRtdHandleServer=TRACE
log.logger.RtdHandleServer.CTopicTable=TRACE, TraceAppender, FileAppender

Appender

log.appender.AppenderName=AppenderType

Part | Description
AppenderName | The name of the appender, case-sensitive. The name has meaning only inside the current configuration file, where it can be used in the right-hand-side of logger and rootLogger statements.
AppenderType | A class identifier. In cpplog, only the last part of the identifier is used; the namespaces that precede the class name are ignored.

Examples

log.appender.B=FileAppender
log.appender.B=log4j.Appenders.FileAppender
log.appender.DebugAppender=TraceAppender

Note that the first two examples above are exactly equivalent.

Layout

log.appender.AppenderName.layout=LayoutType

Part | Description
AppenderName | The name of the appender, case-sensitive. This must be an appender that has been declared in a previous line.
LayoutType | A class identifier. In cpplog, only the last part of the identifier is used; the namespaces that precede the class name are ignored. Currently, only PatternLayout is supported.

Example

log.appender.B.layout=PatternLayout

This statement can be omitted.

ConversionPattern

log.appender.AppenderName.layout.ConversionPattern=Pattern

Part | Description
AppenderName | The name of the appender, case-sensitive. This must be an appender that has been declared in a previous line.
Pattern | A formatting pattern. See Formatting patterns for details.

Example

log.appender.B.layout.ConversionPattern=%-20.20d %-5p %c - %m [%l]%n

File

log.appender.AppenderName.File=FileName

Part | Description
AppenderName | The name of the appender, case-sensitive. This must be an appender that has been declared in a previous line.
FileName | The full name, including path, of the destination file of a FileAppender. The file name may include an environment variable, such as %TMP%, which will be expanded. If the appender is of type RollingFileAppender, then the file name may include the characters %t; these will be replaced by the date/time when the name is expanded.

Examples

log.appender.B.File=C:\Logs\logfile.txt
log.appender.C.File=%TMP%\Logs\RtdHandleServer_log_%t.log

Next: Formatting patterns >>


Formatting patterns

A formatting pattern is a text string containing one or more symbols, which will be substituted into the formatted output text. The symbols are listed below.

Symbols

Symbol | Description
%c | Logger name.
%d | Timestamp.
%F | File name of originating source file.
%l | Location of code that logged the event, including file name and line number. Equivalent to %F(%L).
%L | Line number of code that logged the event.
%m | Message
%n | New line
%p | Severity level (i.e. ERROR, WARN, etc)
%r | Ticks - millisecs since originating computer was started.
%t | Thread ID.
%% | The percent symbol.

Width

Each symbol can be preceded by a width statement, in the form min or min.max where min and max are both integers, e.g.: %5p, %-10.20c, %7.7t The outputted field will be padded with spaces if it contains less than min characters. If min is negative, then the padding will be on the right - i.e. the field will be left-justified. If min is positive, then the padding will be on the left - i.e. the field will be right-justified. If the field contains more than max characters, it will be truncated.

Examples

%-5p %c - %m%n

Prints the severity level of the event, left-justified, padded to 5 characters, followed by the name of the logger that initially received the event, the message itself, and finally a new-line.

ERROR MyClass - Something went very wrong
WARN  MyOtherClass - Something untoward occurred

%-20.20d %-5p %c - %m [%l]%n

Prints the time the event was raised, the severity level of the event (left-justified, padded to 5 characters), the name of the logger that initially received the event, the message itself, the line of code where te event was raised and finally a new-line.

Sat Feb 07 11:05:17  INFO  RtdHandleServer.CTopicTable - CTopicTable: Remove topic {5ECBBA8B-EDF7-432E-B127-823F089FADF0}; count after = 0 [c:\source\topictable.h(166)]
Sat Feb 07 11:05:17  TRACE RtdHandleServer.CXllRtdHandleServer - CXllRtdHandleServer::DisconnectData() ends [c:\source\xllrtdhandleserver.cpp(248)]

Next: Hidden regions >>


Hidden regions

From XLL+ version 6.3, the XLL+ supports the use of hidden regions to hide the implementation code that is rarely, if ever, of interest to the developer.

#pragma region

Blocks demarcated by #pragma region [Label] and #pragma endregion can be hidden in Visual Studio 2005 and above.

CopyC++
// Function:    DF_SET
// Purpose:     Publishes a single value to the data feed

//{{XLP_SRC(DF_SET)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region DF_SET support code

IMPLEMENT_XLLFN3(DF_SET, DF_SET_4, DF_SET_12, "RCCC", "UC%C%C%", L"DF_SET", 0,
    L"Security,Property,Value", 0, L"10", 0, L"Publishes a single value to the"
    L" data feed", 0, L"is the code for the security\0is the name or numeric i"

    ... More code ...

CXlWizExUIArgumentListCreator xweuialc__DF_SET__1(L"DF_SET", 1, L"X,dummy valu"
    L"e", L',', L';');

#pragma endregion
CXlOper* DF_SET_Impl(CXlOper& xloResult, const CXlStringArg& Security, const
    CXlStringArg& Property, const CXlStringArg& Value)
{
    // End of generated code
//}}XLP_SRC

    ... Your code ...
}

Only the label after the #pragma region will be visible when the code block is hidden.

Controlling visibility

Use the small + or - symbol just in the left margin to expand or collapse the region.

By default, the XLL+ Function Wizard will collapse any collapsible regions when it generates a new function, and will preserve the current expanded/collapsed state of an existing function when the code is regenerated.

You can use the CollapseAllSections setting in XLL+ Options to control this behavior.

You can also use the Collapse All Hidden Regions command on the XLL Add-ins window's Tools menu to hide the hidden region of all add-in functions in the current file.

Next: Security settings >>


Security settings

During development, it can become very tedious having to constantly click past security warnings when your XLL is opened by Excel.

There are several ways round the problem during development.

Trust the directory

Under Excel 2007, you can add your source code directory to the list of "Trusted Locations". Ensure that "Sub-folders of this location are also trusted" is checked.

However, depending on your other security settings, this may be insufficient; you may also need to sign your code (see below).

Sign the code

You can use the code signing tool signtool.exe (provided as part of Visual Studio 2005) to apply a trusted signature to your file as soon as it has been built.

Post-Build Event

In the project properties window, go to the Build Events/Post-Build Event page, and set Command Line to:

signtool sign /a "$(TargetPath)"

This will sign the code with the most appropriate certificate, if any are available.

Create a signature

You can use the selfcert.exe tool to create a certificate that will work on your own machine, but will not be trusted elsewhere. This is appropriate for testing and debugging.

Change security level

You can change the macro security level of Excel to "Low". This approach is a blunt instrument, and should only be considered for a development machine in a safe network environment.

Production builds

The methods described above should only be used for debug builds and for test environments.

Production builds that create code for use on other machines should be subject to more stringent and precise security measures, as specified by your network administrator.

Next: Trouble-shooting >>


Trouble-shooting topics

This chapter contains the following topics:

Trouble-shooting
Installed files
XLL+ Application log


Trouble-shooting

If you run into a problem with XLL+, first look at the list of Frequently Asked Questions below. Then try the online FAQ at http://www.planatechsolutions.com/nav.asp?section=faq.

If you can't find a solution there, then report the problem to us, either by email, or by using the on-line reporting form at: http://www.planatechsolutions.com/support/support_request.aspx.

Reporting problems

If you need to report an error, please enclose the following information, if possible:

  1. Visual Studio version and service pack level.

  2. Excel version and service pack level.

  3. A copy of the information in the XLL+ About box.

    To show the About box, click on the "About XLL+..." command on the Tools menu of the XLL Add-ins window. Click the "Copy" button to copy the version details to the clipboard and paste them into your error report.

Frequently Asked Questions

How can I tell whether XLL+ 7 has been installed?

If XLL+ 7 has been installed, it will be listed in the Visual Studio About box. Click on Help/About Microsoft Visual Studio to show the About box, and scroll down the list of installed products to find "XLL Plus 7.x" (where x is the minor version number).

The XLL+ menu items do not appear on the Visual Studio "Tools" menu.

First, check that XLL+ 7 has been installed. If it has been, use the Tools/Customize... menu in Visual Studio to show the Customize dialog.

Select the "Commands" tab, and the "Tools" Category. Scroll down the list of commands and find "New XLL+ Function...". Drag it onto the Tools menu.

In the same list of commands, find "XLL+ Function Wizard..." and also drag that onto the Tools menu.

Where are my XLL+ settings stored?

The settings that you enter in the XLL+ Options/General page are kept in the registry in the folder HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\DialogPage\Planatech.XllPlus7.OptionsPageGeneral. See Registry settings for more information.

The size and layout of the XLL+ windows and dialogs are retained in the file XlpFormLayouts.xml in the user's application directory. See User files for details.

What files are installed by XLL+?

See Installed files for a list.

Where is the XLL+ log file?

See XLL+ Application log.

Next: Installed files >>


Installed files

XLL+ installs and uses files in three general locations:

User files
Files created and used for a specific user.
Machine-level files
Files shared by all users on a machine.
Visual Studio integration files
Files created within the Visual Studio installation tree, to help XLL+ integrate with Visual Studio.

For information on XLL+ registry settings, please see Registry settings.

In the lists below VS[N] refers to the node for the Visual Studio version being supported. VS8.0 is used for Visual Studio 2005, VS9.0 for Visual Studio 2008 and VS10.0 for Visual Studio 2010.

User files

The per-user files are all stored in the XLL+ per-user application directory. The location of this directory is controlled by various network settings and by the user's ID.

You can see which directory XLL+ is using for user settings by opening the "XLL+/General" pane in the Visual Studio Options window, and inspecting the property "UserSettingsFolder".

In the directory names below, it is referred to as [UserSettingsFolder].

[UserSettingsFolder]\Planatech\XLL+\7.0\VS[N]

File | Description
FavoriteArguments.xml | Favorite arguments repository file. A user can use a different file instead, by changing the FavoriteArgumentsFile setting.
XlpFormLayouts.xml | Layout settings of all XLL+ development tools. If a user changes their screen configuration - particularly from 2 screens to one - and then runs into trouble with invisible windows, delete this file to set the layouts back to the factory defaults.

[UserSettingsFolder]\Planatech\XLL+\7.0\VS[N]\templates

These files are copied into the user's directory the first time a user uses the XLL+ Visual Studio package. They can be edited without affecting other users on the same machine.

File | Description
TemplateManagerSettings.xlpts | List of template files used by the code generator of the XLL+ Visual Studio package.
*.tpl | Template files used by the code generator of the XLL+ Visual Studio package.

Machine-level files

The XLL+ machine-level files are installed in the XLL+ installation directory. By default this is [Program Files]\Planatech\XllPlus, but it can be changed during the installation. In the directory names below, it is referred to as [XlpDir].

[XlpDir]\7.0\VS[N]\bin

File | Description
xllplus7.NN.dll | Main assembly file of XLL+ Visual Studio package. NN is replaced by 80 under VS 2005, 90 under VS 2008 and 100 under VS 2010.
xllplus7.extensionmodules.xml | Configuration file for XLL+ Visual Studio package.
BuildHelp.exe | Command-line utility for building help files.
cwgencls.exe | Command-line utility that generates wrapper classes.
cwgeninf.exe | Command-line utility that generates skeleton information files for use with cwgencls.exe.
XlpRibbonReg.exe | Office Ribbon registration tool.
XnReflect.exe | .NET reflector command-line utility.
psl.*.dll | Support assemblies for XLL+ Visual Studio package.
log4net.dll | Apache Foundation log4net package.
XlpLogSettings.log4net.xml | Configuration file for log4net.
Janus.*.dll | UI assemblies used by XLL+ Visual Studio package.
Microsoft.Cci.*.dll | Common Compiler Infrastructure assemblies used by the .NET reflector tools.

[XlpDir]\7.0\VS[N]\bin\win32

This folder contains 32-bit COM servers that have been registered on the development machine. The directory will be empty if a 64-bit version of Excel is found.

File | Description
RtdHandleServer.dll | Supports RTD handles.
XllRtdFeed.dll | Supports RTD handles.
XllRtdLink.dll | Supports asynchronous functions.
XlpRibbonServer.dll | Supports the use of the Office ribbon.
XlpRibbonServer.config | Configuration file for XlpRibbonServer.dll. It contains a list of XLLs that will be registered when Excel is opened.

[XlpDir]\7.0\VS[N]\bin\x64

This folder contains 64-bit COM servers that have been registered on the development machine. The directory will be empty if a 32-bit version of Excel is found.

File | Description
RtdHandleServer.dll | Supports RTD handles.
XllRtdFeed.dll | Supports RTD handles.
XllRtdLink.dll | Supports asynchronous functions.
XlpRibbonServer.dll | Supports the use of the Office ribbon.
XlpRibbonServer.config | Configuration file for XlpRibbonServer.dll. It contains a list of XLLs that will be registered when Excel is opened.

[XlpDir]\7.0\VS[N]\buildhelp\files

File | Description
[various] | Data files and skeleton files used by the XLL+ help generator.

[XlpDir]\7.0\VS[N]\buildhelp\xsl

File | Description
*.xsl | XSLT files used by the XLL+ help generator.

[XlpDir]\7.0\VS[N]\docs\chmhelp

File | Description
xllplus.chm | XLL+ documentation in compiled help format (CHM).

[XlpDir]\7.0\VS[N]\docs\legal

File | Description
License.rtf | A copy of the XLL+ End User License agreement.
[various] | Copies of the licenses of 3rd party products.

[XlpDir]\7.0\VS[N]\docs\vshelp

File | Description
xllplus*.Hx? | XLL+ documentation in HELP2 format, for integration within Visual Studio help.
h2reg.exe | Help integration utility.
h2reg.ini | Help integration utility configuration file.
h2reg_log.txt | Log file of help integration utility.

[XlpDir]\7.0\VS[N]\extensions

File | Description
*.xpe | XLL+ extension files.

[XlpDir]\7.0\VS[N]\include

File | Description
xllplus.h | Main XLL+ header file.
*.h | XLL+ header files, many of them automatically included by xllplus.h. See Overview of files in the Class Reference for more information.
xlpres.rc | US English version of XLL+ run-time error messages.
xlpresXXYY.rc | Various other langauge versions of XLL+ run-time error messages.

[XlpDir]\7.0\VS[N]\include\extensions

File | Description
*.h | Header files to support XLL+ extensions.

[XlpDir]\7.0\VS[N]\lib\win32

[XlpDir]\7.0\VS[N]\lib\x64

These two folders contain the run-time library files, in 32-bit and 64-bit versions respectively.

File | Description
xlllibsr.lib | XLL+ run-time library. STL, ANSI, Multithreaded CRT, Release
xlllibsd.lib | XLL+ run-time library. STL, ANSI, Multithreaded CRT, Debug
xlllibsmr.lib | XLL+ run-time library. STL, ANSI, Multithreaded DLL CRT, Release
xlllibsmd.lib | XLL+ run-time library. STL, ANSI, Multithreaded DLL CRT, Debug
xlllibr.lib | XLL+ run-time library. MFC, ANSI, Multithreaded DLL CRT, Release
xlllibd.lib | XLL+ run-time library. MFC, ANSI, Multithreaded DLL CRT, Debug
xlllibpr.lib | XLL+ run-time library. MFC, ANSI, Multithreaded CRT, Release
xlllibpd.lib | XLL+ run-time library. MFC, ANSI, Multithreaded CRT, Debug
xlllibscr.lib | XLL+ run-time library. CLR, ANSI, Multithreaded DLL CRT, Release
xlllibscd.lib | XLL+ run-time library. CLR, ANSI, Multithreaded DLL CRT, Debug
xlllibsrw.lib | XLL+ run-time library. STL, Unicode, Multithreaded CRT, Release
xlllibsdw.lib | XLL+ run-time library. STL, Unicode, Multithreaded CRT, Debug
xlllibsmrw.lib | XLL+ run-time library. STL, Unicode, Multithreaded DLL CRT, Release
xlllibsmdw.lib | XLL+ run-time library. STL, Unicode, Multithreaded DLL CRT, Debug
xlllibrw.lib | XLL+ run-time library. MFC, Multithreaded DLL CRT, Unicode, Release
xlllibdw.lib | XLL+ run-time library. MFC, Multithreaded DLL CRT, Unicode, Debug
xlllibprw.lib | XLL+ run-time library. MFC, Multithreaded CRT, Unicode, Release
xlllibpdw.lib | XLL+ run-time library. MFC, Multithreaded CRT, Unicode, Debug
xlllibscrw.lib | XLL+ run-time library. CLR, Unicode, Multithreaded DLL CRT, Release
xlllibscdw.lib | XLL+ run-time library. CLR, Unicode, Multithreaded DLL CRT, Debug

[XlpDir]\7.0\VS[N]\redist\win32

This folder contains 32-bit versions of the redistributable COM components which support XLLs. Details of the servers can be found above under [XlpDir]\7.0\VS[N]\bin\win32.

[XlpDir]\7.0\VS[N]\redist\x64

This folder contains 32-bit versions of the redistributable COM components which support XLLs. Details of the servers can be found above under [XlpDir]\7.0\VS[N]\bin\x64.

[XlpDir]\7.0\VS[N]\samples

File | Description
[various sub-directories] | Complete XLL+ sample applications, each in its own sub-directory.

[XlpDir]\7.0\VS[N]\samples\bin

File | Description
*.xll | Compiled versions of each of the XLL+ sample applications.
*.xls | Demonstration spreadsheets for each of the XLL+ sample applications.
*.chm | Interactive help files for some of the XLL+ sample applications.

[XlpDir]\7.0\VS[N]\servers

The sub-directories of this folder contain the source code for the redistributable COM servers.

[XlpDir]\7.0\VS[N]\templates

Usually, these files are not used directly by the XLL+ package. Instead, copies of these files are placed in the user application directory (see above), the first time a user uses the XLL+ package.

File | Description
TemplateManagerSettings.xlpts | List of template files used by the code generator of the XLL+ Visual Studio package.
*.tpl | Template files used by the code generator of the XLL+ Visual Studio package.

[XlpDir]\7.0\VS[N]\walkthroughs

File | Description
[various sub-directories] | Complete XLL+ walkthrough applications, each in its own sub-directory.

[XlpDir]\7.0\VS[N]\walkthroughs\bin

File | Description
*.xll | Compiled versions of each of the XLL+ walkthrough applications.
*.xls | Demonstration spreadsheets for each of the XLL+ walkthrough applications.
*.chm | Interactive help files for some of the XLL+ walkthrough applications.

Visual Studio integration files

The following files are created within the Visual Studio installation tree, to help XLL+ integrate with Visual Studio. The directories are all below the Visual Studio installation directory, referred to as [VsDir] below.

By default, Visual Studio 2005 is installed in:

[Program Files]\Microsoft Visual Studio 8

By default, Visual Studio 2008 is installed in:

[Program Files]\Microsoft Visual Studio 9

By default, Visual Studio 2010 is installed in:

[Program Files]\Microsoft Visual Studio 10

In the list below, NN should be replaced with 80, 90 or 100, depending on the Visual Studio version.

[VsDir]\Xml\Schemas

File | Description
xlp.xsd | XLL+ Extensions schema file. This file provides editing support for XLL+ extension files.
xlphelp.xsd | XLL+ Help schema file. This file provides editing support for XLL+ help files.

[VsDir]\VC\vcprojects

File | Description
XlpDLL7_NN.ico | XLL+ Application Wizard icon file.
XlpDLL7_NN.vsdir | XLL+ Application Wizard listing file. This controls the appearance of the XLL+ project type in the Visual Studio "New Project" dialog.
XlpDLL7_NN.vsz | XLL+ Application Wizard location file. This contains the location of the XLL+ AppWizard.

[VsDir]\VC\vcprojects\XLL+

File | Description
XlpDLL7_NN.vsdir | XLL+ Application Wizard listing file. This controls the appearance of the XLL+ project type in the "XLL+" node of the Visual Studio "New Project" dialog.

[VsDir]\VC\VCWizards\AppWiz\XLL+\Addin

The sub-directories of this folder hold the various files of the XLL+ AppWizard.

Next: XLL+ Application log >>


XLL+ Application log

log4net

The XLL+ development tools use the Apache Foundation's log4net logging library. For information on log4net, see the Apache log4net web-site at http://logging.apache.org/log4net/.

The error log

When installed, the XLL+ development tools are set to report ERROR level messages only. These messages are written to a text file, xllplus.log, located in the user's TMP directory. You can view it by typing in a console window as follows:

notepad %TMP%\xllplus.log

Configuration file

XLL+ reads its log4net settings from the log4net configuration file, XlpLogSettings.log4net.xml.

It first looks in the user's application directory: [User Settings]\Application Data\Planatech\XLL+\7.0\VS8.0 (e.g. C:\Documents and Settings\MyName\Application Data\Planatech\XLL+\7.0\VS8.0). If a copy of the file is found there, then that is used.

If no file is found in the user's application directory, then XLL+ looks in the XLL+ binaries directory, e.g. [Program files]\Planatech\XLL+\7.0\VS8.0\bin.

Editing the configuration file

To switch on all levels of logging, change the value attribute of the root/level element to "DEBUG":

CopyXML
<root>
  <level value="DEBUG" />
  <appender-ref ref="FileAppender" />
</root>

To view the log in the Visual Studio output window, add the VsAppender appender:

CopyXML
<root>
  <level value="DEBUG" />
  <appender-ref ref="FileAppender" />
  <appender-ref ref="VsAppender" />
</root>


Class Reference

The XLL+ Class Reference contains details of all the classes and functions contained in the XLL+ run-time libraries.

All the classes and methods in the reference are accessible through on-line help in Visual Studio. Just select the method or class name in your source code, and type F1 to go to the relevant help page.

Starting Points

Classes
A list of all the XLL+ object classes.
Files
A list of XLL+ header files.
Runtime Libraries
A list of the various XLL+ runtime libraries, and of the project settings that affect them.
Examples
A list of XLL+ example code fragments.
Messages
A list of all messages returned by the XLL+ run-time libraries.

See Also

Class Reference

© 1997-2014 Planatech Solutions Ltd. All rights reserved.


Overview of files

The XLL Plus library provides a number of C++ header files for use in writing Excel add-ins. The classes and definitions contained in the header files have been designed to simplify the use of Excel programming objects, but only a subset is needed by programmers building the standard run of add-in functions.

The table below summarises the C++ header files available in the library.

File | Description
xllplus.h | The core objects of the library.
xlldate.h | Date classes and functions.
xlfuncs.h | Classes containing static methods for calling Excel worksheet and macro functions.
xlpexcept.h | Exception classes.
xlpevents.h | Event classes.
xlpconvert.h | Classes and functions that validate user input.
xlserialize.h | Classes that support serialization and cacheing of Excel data types.
xlpcom.h | Classes and functions for using Excel's OLE automation interface.
xllfinder.h | A utility class for searching and replacing cells in Excel spreadsheets.
xldialog.h | Classes for displaying and controlling Excel native dialogs.
xlpribbon.h | Classes and enumerations to support the XLL+ ribbon implementation.
xlmenu.h | A class for creating user-defined menus in Excel.
xltoolbar.h | A class for creating user-defined toolbars in Excel.
xllres.h | String resource functions.
plemtx.h | Template classes for storing and manipulating two-dimensional data arrays.
xlhandle.h | Classes and templates for storing C++ objects and accessing them from worksheet cells by their numeric "handle".
xlpclrconvert.h | Functions that help with conversion to and from Common Language Runtime types.
xlpclrforms.h | A class to help with invoking the Common Language Runtime Forms library.
cpplog.h | A self-contained logging framework modelled on log4j and log4cxx.
xlvaluelistconstraint.h | A constraint on an input value, such that it must be a member of a specific set of values.
xlwizexui.h | Classes that extended the user interface of the Excel Formula Wizard.
xllrtdfeedserverproxy.h | Classes that enable real-time data to be returned to Excel from add-in functions.
xlpfastit.h | Classes that support fast iteration of Excel arrays.

See Also

XLL+ Class Reference


Overview of classes

The XLL Plus library contains a variety of C++ classes for use in writing Excel add-ins. All of these classes have been designed to simplify the use of Excel programming objects, but only a few are needed by programmers building the standard run of add-in functions.

It is possible to make productive use of the library with a simple understanding of just one class: CXlOper.

The table below summarises the principal C++ object classes available in the library.

Class | Description
CXlOper | An argument sent by Excel to an add-in function or a result sent back to Excel by an add-in function.
CXllApp | The object representing the add-in library itself. It can be used to store data that is global to the library.
CXlRuntimeException | The root exception class. All other exception classes are derived from this.
imtx<T> | A two-dimensional array of numbers, booleans or strings.
CXlMenu | A run-time menu added to Excel's main application menu bar.
CXlToolbar | A run-time toolbar added to Excel's main window.
CXlRef | A reference to a rectangular block of cells.
CXlEvent | The base class for events. This class implements the Subject of the observer pattern.
CXlDialog | A dialog displayed using Excel's native dialog mechanism.
CXllFinder | A tool for finding and replacing the contents of cells.
CXlFuncs | A class containing static methods for calling Excel worksheet functions.
CXlMacros | A class containing static methods for calling Excel macro functions.
CXlOperCache | A class which caches the results of add-in functions, preventing unnecessary recalculations.
CXllFn | A representation of a single add-in function.
CExcelWnd | An MFC window class that provides access to the Excel application window.
CXlArray | An array of floating-point numbers passed by or returned to Excel.
CXlHandleStore<T, S> | A store of objects, which can be accessed from add-in functions by their numeric "handle".
CXlFormulaRefresh | A utility class, which can be used to force recalculation of any cell whose formula contains a specified function.
CXllCom | Offers an interface for calling Excel's COM automation interface.
ExcelForm | A C++/CLR window class that provides access to the Excel application window.
CXlValueListConstraint<INT_T> | Defines a constraint on an integral input value, such that it must be a member of a specific set of values.
CXllRtdFeedServerProxy | Used to return real-time data to Excel from add-in functions.

See Also

XLL+ Class Reference


Run-time messages

The localizable run-time messages used by the XLL+ run-time libraries are listed below.

The resource id of each message (as listed in the localized resource file) is XLP_IDS_ followed by the name, e.g. XLP_IDS_EXCEPTION_FORMAT.

Index | 1
Name | EXCEPTION_FORMAT
Description | Error format applied to the text of exceptions just before returning to Excel
Parameter 0: message | Message text of exception
US English text | #ERROR: {0}
Example | #ERROR: Expected 2 rows in X
Index | 2
Name | ASYNC_WAIT
Description | Result returned by asynchronous functions which have not yet completed
US English text | #WAIT!
Example | #WAIT!
Index | 3
Name | TYPE_UNKNOWN
Description | Name used for unknown type
US English text | unknown type
Example | #ERROR: Expected unknown type for X
Index | 4
Name | TYPE_BOOLEAN
Description | Name used for boolean types
US English text | boolean
Example | #ERROR: Expected boolean for X
Index | 5
Name | TYPE_DOUBLE
Description | Name used for floating-point number type
US English text | number
Example | #ERROR: Expected number for X
Index | 6
Name | TYPE_INT
Description | Name used for floating-point number type
US English text | integer
Example | #ERROR: Expected integer for X
Index | 7
Name | TYPE_STRING
Description | Name used for string type
US English text | string
Example | #ERROR: Could not convert value from string to date
Index | 8
Name | TYPE_ERROR
Description | Name used for error type
US English text | error
Example | #ERROR: Expected error for X
Index | 9
Name | TYPE_LONG
Description | Name used for long integer type
US English text | long integer
Example | #ERROR: Expected long integer for X
Index | 10
Name | CONVERSION_EXCEPTION_DEFAULT
Description | Generic conversion error message
US English text | Conversion error
Example | Conversion error
Index | 11
Name | CONVERSION_EXCEPTION_EXPECTED_TYPE
Description | A conversion operation failed because the unnamed input was of unexpected type
Parameter 0: type | The expected type, as a localized string
US English text | Expected {0}
Examples | Expected number
 | Expected date
Index | 12
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_TYPE
Description | A conversion operation failed because the named input was of unexpected type
Parameter 0: arg_name | Localized argument name
Parameter 1: type | The expected type, as a localized string
US English text | Expected {1} for {0}
Examples | Expected integer for X
 | Expected date for X[3]
 | Expected boolean for X[3,1]
Index | 13
Name | CONVERSION_EXCEPTION_NAME_EMPTY_ARRAY
Description | A conversion operation failed because the named array input was empty
Parameter 0: arg_name | Localized argument name
US English text | Expected at least 1 value for {0}
Example | Expected at least 1 value for X
Index | 14
Name | CONVERSION_EXCEPTION_NAME_NOT_FOUND
Description | A conversion operation failed because the named group input did not contain the named item
Parameter 0: group_name | Localized group name
Parameter 1: item_name | Localized item name
US English text | Label {1} not found in {0}
Example | Label ValueDate not found in Terms
Index | 15
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_VECTOR
Description | A conversion operation failed because the named vector argument has 0 cells or is 2-dimensional
Parameter 0: arg_name | Localized argument name
US English text | Expected vector for {0}
Example | Expected vector for X
Index | 16
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_N_VALUES_IN_GROUP
Description | A conversion operation failed because the named scalar group has too few items
Parameter 0: arg_name | Localized argument name
Parameter 1: value_count | Number of values expected (always greater than 1)
US English text | Expected at least {1} values for {0}
Example | Expected at least 4 values for X
Index | 17
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_1_ROW_IN_MATRIX
Description | A conversion operation failed because the named matrix argument has a size that fails to match a constraint
Parameter 0: arg_name | Localized argument name
Parameter 1: row_count | Number of rows expected (always 1)
US English text | Expected 1 row in {0}
Example | Expected 1 row in X
Index | 18
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_N_ROWS_IN_MATRIX
Description | A conversion operation failed because the named matrix argument has a size that fails to match a constraint
Parameter 0: arg_name | Localized argument name
Parameter 1: row_count | Number of rows expected (always greater than 1)
US English text | Expected {1} rows in {0}
Example | Expected 4 rows in X
Index | 19
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_1_COL_IN_MATRIX
Description | A conversion operation failed because the named matrix argument has a size that fails to match a constraint
Parameter 0: arg_name | Localized argument name
Parameter 1: col_count | Number of columns expected (always 1)
US English text | Expected 1 column in {0}
Example | Expected 1 column in X
Index | 20
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_N_COLS_IN_MATRIX
Description | A conversion operation failed because the named matrix argument has a size that fails to match a constraint
Parameter 0: arg_name | Localized argument name
Parameter 1: col_count | Number of columns expected (always greater than 1)
US English text | Expected {1} columns in {0}
Example | Expected 3 columns in X
Index | 21
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_1_VALUE_IN_VECTOR
Description | A conversion operation failed because the named vector argument has a size that fails to match a constraint
Parameter 0: arg_name | Localized argument name
Parameter 1: value_count | Number of values expected (always 1)
US English text | Expected 1 value in {0}
Example | Expected 1 value in X
Index | 22
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_N_VALUES_IN_VECTOR
Description | A conversion operation failed because the named vector argument has a size that fails to match a constraint
Parameter 0: arg_name | Localized argument name
Parameter 1: value_count | Number of values expected (always greater than 1)
US English text | Expected {1} values in {0}
Example | Expected 4 values in X
Index | 23
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_1_VALUE_IN_ROW_M
Description | A conversion operation failed because the named grouped horizontal vector argument has a size that fails to match a constraint
Parameter 0: arg_name | Localized argument name
Parameter 1: value_count | Number of values expected (always 1)
US English text | Expected 1 value in row {2} of {0}
Example | Expected 1 value in row 2 of X
Index | 24
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_N_VALUES_IN_ROW_M
Description | A conversion operation failed because the named grouped horizontal vector argument has a size that fails to match a constraint
Parameter 0: arg_name | Localized argument name
Parameter 1: value_count | Number of values expected (always greater than 1)
US English text | Expected {1} values in row {2} of {0}
Example | Expected 101 values in row 2 of X
Index | 25
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_1_VALUE_IN_COL_M
Description | A conversion operation failed because the named grouped vertical vector argument has a size that fails to match a constraint
Parameter 0: arg_name | Localized argument name
Parameter 1: value_count | Number of values expected (always 1)
US English text | Expected 1 value in column {2} of {0}
Example | Expected 1 value in column 2 of X
Index | 26
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_N_VALUES_IN_COL_M
Description | A conversion operation failed because the named grouped vertical vector argument has a size that fails to match a constraint
Parameter 0: arg_name | Localized argument name
Parameter 1: value_count | Number of values expected (always greater than 1)
US English text | Expected {1} values in column {2} of {0}
Example | Expected 101 values in column 2 of X
Index | 27
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_N_ROWS_IN_GROUP
Description | A conversion operation failed because the named horizontal grouped vector argument has an insufficient number of items
Parameter 0: arg_name | Localized argument name
Parameter 1: row_count | Number of rows expected (always greater than 1)
US English text | Expected at least {1} rows for {0}
Example | Expected at least 3 rows for X
Index | 28
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_N_COLS_IN_GROUP
Description | A conversion operation failed because the named vertical grouped vector argument has an insufficient number of items
Parameter 0: arg_name | Localized argument name
Parameter 1: col_count | Number of columns expected (always greater than 1)
US English text | Expected at least {1} columns for {0}
Example | Expected at least 3 columns for X
Index | 29
Name | CONVERSION_EXCEPTION_CONVERT_TO_EXCEL_FAILED
Description | An attempt to set the value of a CXlOper from a native type or an array of native types failed
Parameter 0: variable_name | Name of input variable
Parameter 1: native_type | Localized name of native type
Parameter 2: excel_type | Localized name of Excel type
US English text | Failed to convert {0} from {1} to {2}
Example | Failed to convert value[12] from date to number
Index | 30
Name | OUT_OF_RANGE_EXCEPTION_DEFAULT
Description | An XLL+ run-time library method was called with an out-of-range index
US English text | Index out of range
Example | Index out of range
Index | 31
Name | ILLEGAL_ARGUMENT_EXCEPTION_DEFAULT
Description | An illegal argument was passed to an XLL+ run-time library method
US English text | Illegal argument
Example | Illegal argument
Index | 32
Name | BAD_OPER_TYPE_EXCEPTION_DEFAULT
Description | A CXlOper, passed to an XLL+ run-time library method, contained the wrong type of data
US English text | Bad XLOPER type
Example | Bad XLOPER type
Index | 33
Name | CHOICE_FAILED_EXCEPTION
Description | A conversion operation for a Choice argument failed, because the input did not match any of the expected types
Parameter 0: arg_name | Localized argument name
US English text | Failed to convert {0} to any of the permitted types
Example | Failed to convert X to any of the permitted types
Index | 34
Name | ELEMTRAITS_NOT_IMPLEMENTED_EXCEPTION
Description | System error occurred. A conversion operation was attempted with a native type that is not supported by the XLL+ run-time library.
US English text | XlElemTraits is not implemented for this type
Example | XlElemTraits is not implemented for this type
Index | 35
Name | ARRAY_TOO_LARGE_EXCEPTION_DEFAULT
Description | An attempt was made to populate a CXlOper with an array that is too large for the active version of Excel
US English text | Array is too large
Example | Array is too large
Index | 36
Name | EMPTY_ARRAY_EXCEPTION_DEFAULT
Description | An attempt was made to populate a CXlOper with an empty array
US English text | Array is empty
Example | Array is empty
Index | 37
Name | STRING_TOO_LONG_EXCEPTION_DEFAULT
Description | An attempt was made to populate a CXlOper with a string that is too long for the active version of Excel
US English text | String is too long
Example | String is too long
Index | 38
Name | ILLEGAL_ARGUMENT_EXCEPTION_BAD_EXTENDED_PARAM_INDEX
Description | A converter class attempted to use a run-time parameter that does not exist in the extended type definition
Parameter 0: param_type | Localized name of the parameter type: string, integer or boolean
Parameter 1: param_index | The parameter index used
Parameter 2: arg_name | Localized argument name
US English text | Extended {0} parameter index {1} for argument {2} is out of range
Examples | Extended integer parameter index 1 for argument X is out of range
 | Extended string parameter index 0 for argument X is out of range
 | Extended boolean parameter index 2 for argument X is out of range
Index | 39
Name | ILLEGAL_ARGUMENT_EXCEPTION_EXPECTED_SCALAR
Description | An attempt was made to populate a cell of a CXlOper with a non-scalar value, e.g. an array or a reference
US English text | Right-hand side of cell assignment must be a scalar value
Example | Right-hand side of cell assignment must be a scalar value
Index | 40
Name | ILLEGAL_ARGUMENT_EXCEPTION_BAD_IGNORE_ITEMS
Description | An illegal value for ignoreItems, ignoreRows or ignoreColumns was passed to a conversion function
Parameter 0: max_value | The highest acceptable value for the parameter under the active Excel version
US English text | Parameter ignoreItems is out of range (maximum = {0})
Example | Parameter ignoreItems is out of range (maximum = {0})
Index | 41
Name | ILLEGAL_ARGUMENT_EXCEPTION_BAD_SOURCE_TYPE
Description | An illegal cell value (e.g. an array or a reference) was passed as the fill value for an array
US English text | Source must be a scalar value
Example | Source must be a scalar value
Index | 42
Name | ILLEGAL_ARGUMENT_EXCEPTION_EXPECTED_EMPTY_ARRAY
Description | An attempt was made to fill an array that has already been populated, and has not been cleared
US English text | Expected all items in the array to be empty
Example | Expected all items in the array to be empty
Index | 43
Name | UNINITIALIZED_OPER_EXCEPTION
Description | An uninitialized CXlOper instance was passed to a run-time function that required an initialized instance
US English text | CXlOper instance is not initialized
Example | CXlOper instance is not initialized
Index | 44
Name | UNINITIALIZED_OPER_EXCEPTION_NAME
Description | The named argument has not been initialized
Parameter 0: arg_name | Localized argument name
US English text | {0} is not initialized
Example | X is not initialized
Index | 45
Name | UNINITIALIZED_OPER_EXCEPTION_NAME_SCALAR_TYPE
Description | The named scalar argument has not been initialized, and should contain the specified type
Parameter 0: arg_name | Localized argument name
Parameter 1: type | The expected type, as a localized string
US English text | {0} is not initialized. Expected {1}.
Example | X is not initialized. Expected number.
Index | 46
Name | UNINITIALIZED_OPER_EXCEPTION_NAME_VECTOR_TYPE
Description | The named vector argument has not been initialized, and should contain the specified type
Parameter 0: arg_name | Localized argument name
Parameter 1: type | The expected type, as a localized string
US English text | {0} is not initialized. Expected {1} vector.
Example | X is not initialized. Expected boolean vector.
Index | 47
Name | UNINITIALIZED_OPER_EXCEPTION_NAME_MATRIX_TYPE
Description | The named matrix argument has not been initialized, and should contain the specified type
Parameter 0: arg_name | Localized argument name
Parameter 1: type | The expected type, as a localized string
US English text | {0} is not initialized. Expected {1} matrix.
Example | X is not initialized. Expected number matrix.
Index | 48
Name | BAD_RETURN_OPER_PTR
Description | An illegal value was returned by an add-in function. The value returned to the wrapper function must be either 0, the address of the xloResult argument, or the value returned by CXlOper::RetError or CXlOper::RetString.
US English text | Illegal value for result of common function. Must be 0, &xloResult or static.
Example | Illegal value for result of common function. Must be 0, &xloResult or static.
Index | 49
Name | FUNCTION_REGISTRATION_FAILED
Description | The text of the error report generated when one or more add-in functions fail to register successfully
Parameter 0: lib_name | Localized library name
Parameter 1: fn_list | A list of function names, separated by new-lines
US English text | The following functions in {0} failed to register:\n{1}\nDo you wish to continue loading the add-in?
Example |
Index | 50
Name | FUNCTION_REGISTRATION_FAILED_CAPTION
Description | The title of the error report generated when one or more add-in functions fail to register successfully
US English text | Add-in Load Failure
Example | Add-in Load Failure
Index | 51
Name | MEMORY_ALLOCATION_FAILED_DEFAULT
Description | There was not enough memory available for the requested allocation
US English text | Memory allocation failed
Example | Memory allocation failed
Index | 52
Name | API_CALL_FAILED_DEFAULT
Description | A call to an Excel API function failed
US English text | Excel API call failed
Example | Excel API call failed
Index | 53
Name | API_CALL_FAILED
Description | A call to the named Excel API function failed, with the specified error code
Parameter 0: api_call | Function name
Parameter 1: rc | Numeric error code returned by Excel
US English text | Excel API call {0} failed with error code {1}
Example | Excel API call DATE failed with error code 32
Index | 54
Name | STRUCTURED_EXCEPTION_DEFAULT
Description | A 'C' structured exception occurred during an add-in function
US English text | 'C' structured exception occurred
Example | 'C' structured exception occurred
Index | 55
Name | STRUCTURED_EXCEPTION
Description | The specified 'C' structured exception occurred during an add-in function
Parameter 0: rc | Exception type as a hex number
US English text | 'C' exception {0}
Example | 'C' exception 0xC0000094
Index | 56
Name | XLERROR_EXCEPTION
Description | An exception of type CXlErrorException was thrown. This text will not be returned to Excel; instead the specified error value will be returned.
Parameter 0: xlerr | Excel error code
US English text | Threw Excel error {0}
Example | Threw Excel error #DIV0!
Index | 57
Name | COM_CALL_FAILED_DEFAULT
Description | A call to the COM sub-system failed
US English text | COM call failed
Example | COM call failed
Index | 58
Name | COM_CALL_FAILED
Description | A call to the named COM system function failed, with the specifed result code
Parameter 0: api_call | Function name
Parameter 1: hr | COM result code, as a hex integer
US English text | {0} failed with error code {1}
Example | CoInitialize failed with error code 0x8007000E
Index | 59
Name | TYPE_SHORT
Description | Name used for 16-bit signed integers
US English text | short integer
Example | short integer
Index | 60
Name | TYPE_USHORT
Description | Name used for 16-bit unsigned integers
US English text | unsigned short integer
Example | unsigned short integer
Index | 61
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_1_VALUE_IN_GROUP
Description | A conversion operation failed because the named scalar group has too few items
Parameter 0: arg_name | Localized argument name
US English text | Expected at least 1 value for {0}
Example | Expected at least 1 value for X
Index | 62
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_1_ROW_IN_GROUP
Description | A conversion operation failed because the named horizontal grouped vector argument has an insufficient number of items
Parameter 0: arg_name | Localized argument name
US English text | Expected at least 1 row for {0}
Example | Expected at least 1 row for {0}
Index | 63
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_1_COL_IN_GROUP
Description | A conversion operation failed because the named vertical grouped vector argument has an insufficient number of items
Parameter 0: arg_name | Localized argument name
US English text | Expected at least 1 column for {0}
Example | Expected at least 1 column for X
Index | 64
Name | CONVERSION_EXCEPTION_NAME_EXPECTED_1_OF_LIST
Description | A conversion operation failed because the named argument was not a member of the specified list of values
Parameter 0: arg_name | Localized argument name
Parameter 1: value_list | Comma-separated list of values
US English text | Expected one of {1} for {0}
Example | Expected one of 1, 2, 3 for X
Index | 65
Name | TYPE_HANDLE_TO
Description | Name used for a handle to an object of the specifed type
Parameter 0: object_type | C++ object type
US English text | handle to {0}
Example | handle to YieldCurve


Runtime libraries

Categories

There are many different versions of the XLL+ run-time libraries, each suiting a different set of requirements. The categories of choice are listed below. Some of these choices are made when the XLL+ AppWizard is run; others can be made later, by changing the configuration settings of the project.

Class library
The runtime libraries make use of a number of C++ string and collection classes. If you need to use the Microsoft Foundation Classes in your add-in, you should choose MFC; otherwise, choose STL.
C Runtime Libraries (CRT)
You can choose to use the C runtime libraries in a shared DLL (Multithreaded DLL), or you can choose to have all the required C runtime functions built into your add-in (Multithreaded).
CLR support
You can choose to use the Common Language Runtime (.NET) libraries. If you do so, you must use the shared DLL C Runtime Libraries.
Character set
You can select the Unicode character set or the standard MBCS character set for your add-in.
Configuration
There are different runtime libraries for Debug and for Release configurations.

Library inclusion

Generally, the correct XLL+ run-time library will be included automatically. The header file xlplib.h is included as part of xllplus.h. It contains a list of #pragma comment(lib, [libname]) statements, which select the appropriate library and bind it to the add-in.

The selection is driven by the macros listed below. Note that one of XLL_LIB_MFC or XLL_LIB_STL must be defined. If neither is defined, then the project will not build. One these two macros is defined when you create the project using the XLL+ AppWizard.

Macro | Effect
XLL_LIB_MFC | Causes one of the MFC libraries to be selected.
XLL_LIB_STL | Causes one of the STL libraries to be selected.
XLL_NO_LIBS | Excludes xlplib.h. No XLL+ runtime library will be automatically included.
_DLL | This Microsoft macro is automatically defined when /MD or /MDd (Multithreaded DLL) is specified.
_MT | This Microsoft macro is automatically defined when /MD or /MDd (Multithreaded DLL) or /MT or /MTd (Multithreaded) is specified.
_MANAGED | This Microsoft macro is automatically defined when Common Language Runtime Support (/clr) is specified. This will cause one of the CLR XLL+ runtime libraries to be included.

If you wish to use a different run-time library (or a special build), then you should add XLL_NO_LIBS to the list of C/C++ Preprocessor Definitions for the project, and you should add the name of the desired library in the list of Linker Additional Dependencies.

Libraries

The table below lists all the standard builds of the runtime libraries. Click on the library name for full details of the configuration settings.

Class library | C Runtime Libraries | Character set | Configuration | Library file
MFC | Multithreaded DLL | MBCS | Debug | xlllibd.lib
 |  |  | Release | xlllibr.lib
 |  | Unicode | Debug | xlllibdw.lib
 |  |  | Release | xlllibrw.lib
 | Multithreaded | MBCS | Debug | xlllibpd.lib
 |  |  | Release | xlllibpr.lib
 |  | Unicode | Debug | xlllibpdw.lib
 |  |  | Release | xlllibprw.lib
STL | Multithreaded | MBCS | Debug | xlllibsd.lib
 |  |  | Release | xlllibsr.lib
 |  | Unicode | Debug | xlllibsdw.lib
 |  |  | Release | xlllibsrw.lib
 | Multithreaded DLL | MBCS | Debug | xlllibsmd.lib
 |  |  | Release | xlllibsmr.lib
 |  | Unicode | Debug | xlllibsmdw.lib
 |  |  | Release | xlllibsmrw.lib
STL/CLR | Multithreaded DLL | MBCS | Debug | xlllibscd.lib
 |  |  | Release | xlllibscr.lib
 |  | Unicode | Debug | xlllibscdw.lib
 |  |  | Release | xlllibscrw.lib

xlllibd.lib

Class library | MFC
C Runtime Libraries | Multithreaded DLL
Use of MFC | Shared DLL
Character set | MBCS
Configuration | Debug
Compiler command lines |
VS 2005 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "_AFXDLL" /D "_MBCS" /FD /EHa /RTC1 /MDd /W3 /TP
VS 2008 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "_AFXDLL" /D "_MBCS" /FD /EHa /RTC1 /MDd /W3 /TP
VS 2010 | /WX- /Od /Oy- /D "WIN32" /D "_DEBUG" /D "XLL_LIB_MFC" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0501" /D "_WIN32_WINNT=0x0501" /D "_WIN32_IE=0x0501" /D "_MBCS" /D "_AFXDLL" /Gm- /EHa /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibr.lib

Class library | MFC
C Runtime Libraries | Multithreaded DLL
Use of MFC | Shared DLL
Character set | MBCS
Configuration | Release
Compiler command lines |
VS 2005 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "_AFXDLL" /D "_MBCS" /FD /EHa /MD /W3 /TP
VS 2008 | /Od /D "WIN32" /D "NDEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "_AFXDLL" /D "_MBCS" /FD /EHa /MD /W3 /TP
VS 2010 | /Zi /WX- /O2 /Oy- /D "WIN32" /D "NDEBUG" /D "XLL_LIB_MFC" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0501" /D "_WIN32_WINNT=0x0501" /D "_WIN32_IE=0x0501" /D "_MBCS" /D "_AFXDLL" /Gm- /EHa /MD /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibdw.lib

Class library | MFC
C Runtime Libraries | Multithreaded DLL
Use of MFC | Shared DLL
Character set | Unicode
Configuration | Debug
Compiler command lines |
VS 2005 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "UNICODE" /D "_UNICODE" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "_AFXDLL" /FD /EHa /RTC1 /MDd /W3 /TP
VS 2008 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "UNICODE" /D "_UNICODE" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "_AFXDLL" /FD /EHa /RTC1 /MDd /W3 /TP
VS 2010 | /WX- /Od /Oy- /D "WIN32" /D "_DEBUG" /D "XLL_LIB_MFC" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0501" /D "_WIN32_WINNT=0x0501" /D "_WIN32_IE=0x0501" /D "_UNICODE" /D "UNICODE" /D "_AFXDLL" /Gm- /EHa /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibrw.lib

Class library | MFC
C Runtime Libraries | Multithreaded DLL
Use of MFC | Shared DLL
Character set | Unicode
Configuration | Release
Compiler command lines |
VS 2005 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "UNICODE" /D "_UNICODE" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "_AFXDLL" /FD /EHa /MD /W3 /TP
VS 2008 | /Od /D "WIN32" /D "NDEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "UNICODE" /D "_UNICODE" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "_AFXDLL" /FD /EHa /MD /W3 /TP
VS 2010 | /Zi /WX- /O2 /Oy- /D "WIN32" /D "NDEBUG" /D "XLL_LIB_MFC" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0501" /D "_WIN32_WINNT=0x0501" /D "_WIN32_IE=0x0501" /D "_UNICODE" /D "UNICODE" /D "_AFXDLL" /Gm- /EHa /MD /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibpd.lib

Class library | MFC
C Runtime Libraries | Multithreaded
Use of MFC | Static Library
Character set | MBCS
Configuration | Debug
Compiler command lines |
VS 2005 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "_MBCS" /FD /EHa /RTC1 /MTd /W3 /TP
VS 2008 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "_MBCS" /FD /EHa /RTC1 /MTd /W3 /TP
VS 2010 | /WX- /Od /Oy- /D "WIN32" /D "_DEBUG" /D "XLL_LIB_MFC" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0501" /D "_WIN32_WINNT=0x0501" /D "_WIN32_IE=0x0501" /D "_MBCS" /Gm- /EHa /RTC1 /MTd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibpr.lib

Class library | MFC
C Runtime Libraries | Multithreaded
Use of MFC | Static Library
Character set | MBCS
Configuration | Release
Compiler command lines |
VS 2005 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "_MBCS" /FD /EHa /MT /W3 /TP
VS 2008 | /Od /D "WIN32" /D "NDEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "_MBCS" /FD /EHa /MT /W3 /TP
VS 2010 | /Zi /WX- /O2 /Oy- /D "WIN32" /D "NDEBUG" /D "XLL_LIB_MFC" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0501" /D "_WIN32_WINNT=0x0501" /D "_WIN32_IE=0x0501" /D "_MBCS" /Gm- /EHa /MT /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibpdw.lib

Class library | MFC
C Runtime Libraries | Multithreaded
Use of MFC | Static Library
Character set | Unicode
Configuration | Debug
Compiler command lines |
VS 2005 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "UNICODE" /D "_UNICODE" /FD /EHa /RTC1 /MTd /W3 /TP
VS 2008 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "UNICODE" /D "_UNICODE" /FD /EHa /RTC1 /MTd /W3 /TP
VS 2010 | /WX- /Od /Oy- /D "WIN32" /D "_DEBUG" /D "XLL_LIB_MFC" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0501" /D "_WIN32_WINNT=0x0501" /D "_WIN32_IE=0x0501" /D "_UNICODE" /D "UNICODE" /Gm- /EHa /RTC1 /MTd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibprw.lib

Class library | MFC
C Runtime Libraries | Multithreaded
Use of MFC | Static Library
Character set | Unicode
Configuration | Release
Compiler command lines |
VS 2005 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "UNICODE" /D "_UNICODE" /FD /EHa /MT /W3 /TP
VS 2008 | /Od /D "WIN32" /D "NDEBUG" /D "XLL_LIB_MFC" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0500" /D "_WIN32_IE=0x0500" /D "UNICODE" /D "_UNICODE" /FD /EHa /MT /W3 /TP
VS 2010 | /Zi /WX- /O2 /Oy- /D "WIN32" /D "NDEBUG" /D "XLL_LIB_MFC" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "WINVER=0x0501" /D "_WIN32_WINNT=0x0501" /D "_WIN32_IE=0x0501" /D "_UNICODE" /D "UNICODE" /Gm- /EHa /MT /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibsd.lib

Class library | STL
C Runtime Libraries | Multithreaded
Use of MFC | None
Character set | MBCS
Configuration | Debug
Compiler command lines |
VS 2005 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /FD /EHa /RTC1 /MTd /W3 /TP
VS 2008 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /FD /EHa /RTC1 /MTd /W3 /TP
VS 2010 | /WX- /Od /Oy- /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /Gm- /EHa /RTC1 /MTd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibsr.lib

Class library | STL
C Runtime Libraries | Multithreaded
Use of MFC | None
Character set | MBCS
Configuration | Release
Compiler command lines |
VS 2005 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /FD /EHa /MT /W3 /TP
VS 2008 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /FD /EHa /MT /W3 /TP
VS 2010 | /Zi /WX- /O2 /Oy- /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /Gm- /EHa /MT /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibsdw.lib

Class library | STL
C Runtime Libraries | Multithreaded
Use of MFC | None
Character set | Unicode
Configuration | Debug
Compiler command lines |
VS 2005 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_UNICODE" /D "UNICODE" /FD /EHa /RTC1 /MTd /W3 /TP
VS 2008 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_UNICODE" /D "UNICODE" /FD /EHa /RTC1 /MTd /W3 /TP
VS 2010 | /WX- /Od /Oy- /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "_UNICODE" /D "UNICODE" /Gm- /EHa /RTC1 /MTd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibsrw.lib

Class library | STL
C Runtime Libraries | Multithreaded
Use of MFC | None
Character set | Unicode
Configuration | Release
Compiler command lines |
VS 2005 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "UNICODE" /D "_UNICODE" /FD /EHa /MT /W3 /TP
VS 2008 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "UNICODE" /D "_UNICODE" /FD /EHa /MT /W3 /TP
VS 2010 | /Zi /WX- /O2 /Oy- /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "_UNICODE" /D "UNICODE" /Gm- /EHa /MT /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibsmd.lib

Class library | STL
C Runtime Libraries | Multithreaded DLL
Use of MFC | None
Character set | MBCS
Configuration | Debug
Compiler command lines |
VS 2005 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /FD /EHa /RTC1 /MDd /W3 /TP
VS 2008 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /FD /EHa /RTC1 /MDd /W3 /TP
VS 2010 | /Zi /WX- /Od /Oy- /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "_LIB" /D "_MBCS" /Gm- /EHa /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibsmr.lib

Class library | STL
C Runtime Libraries | Multithreaded DLL
Use of MFC | None
Character set | MBCS
Configuration | Release
Compiler command lines |
VS 2005 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /FD /EHa /MD /W3 /TP
VS 2008 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /FD /EHa /MD /W3 /TP
VS 2010 | /Zi /WX- /O2 /Oy- /D "WIN32" /D "NDEBUG" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "XLL_LIB_STL" /D "_MBCS" /Gm- /EHa /MD /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibsmdw.lib

Class library | STL
C Runtime Libraries | Multithreaded DLL
Use of MFC | None
Character set | Unicode
Configuration | Debug
Compiler command lines |
VS 2005 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_UNICODE" /D "UNICODE" /FD /EHa /RTC1 /MDd /W3 /TP
VS 2008 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_UNICODE" /D "UNICODE" /FD /EHa /RTC1 /MDd /W3 /TP
VS 2010 | /WX- /Od /Oy- /D "WIN32" /D "_DEBUG" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "XLL_LIB_STL" /D "_VC80_UPGRADE=0x0710" /D "_UNICODE" /D "UNICODE" /Gm- /EHa /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibsmrw.lib

Class library | STL
C Runtime Libraries | Multithreaded DLL
Use of MFC | None
Character set | Unicode
Configuration | Release
Compiler command lines |
VS 2005 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "UNICODE" /D "_UNICODE" /FD /EHa /MD /W3 /TP
VS 2008 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "UNICODE" /D "_UNICODE" /FD /EHa /MD /W3 /TP
VS 2010 | /Zi /WX- /O2 /Oy- /D "WIN32" /D "NDEBUG" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "XLL_LIB_STL" /D "_UNICODE" /D "UNICODE" /Gm- /EHa /MD /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibscd.lib

Class library | STL
C Runtime Libraries | Multithreaded DLL
Use of MFC | None
Common Language Runtime support | Common Language Runtime Support (/clr)
Character set | MBCS
Configuration | Debug
Compiler command lines |
VS 2005 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /FD /EHa /MDd /W3 /clr /TP
VS 2008 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /FD /EHa /MDd /W3 /clr /TP
VS 2010 | /WX- /Od /Oy- /D "WIN32" /D "_DEBUG" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "XLL_LIB_STL" /D "_MBCS" /Gm- /EHa /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibscr.lib

Class library | STL
C Runtime Libraries | Multithreaded DLL
Use of MFC | None
Common Language Runtime support | Common Language Runtime Support (/clr)
Character set | MBCS
Configuration | Release
Compiler command lines |
VS 2005 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /FD /EHa /MD /W3 /clr /TP
VS 2008 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_MBCS" /FD /EHa /MD /W3 /clr /TP
VS 2010 | /Zi /WX- /O2 /Oy- /D "WIN32" /D "NDEBUG" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "XLL_LIB_STL" /D "_MBCS" /Gm- /EHa /MD /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibscdw.lib

Class library | STL
C Runtime Libraries | Multithreaded DLL
Use of MFC | None
Common Language Runtime support | Common Language Runtime Support (/clr)
Character set | Unicode
Configuration | Debug
Compiler command lines |
VS 2005 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_UNICODE" /D "UNICODE" /FD /EHa /MDd /W3 /clr /TP
VS 2008 | /Od /D "WIN32" /D "_DEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "_UNICODE" /D "UNICODE" /FD /EHa /MDd /W3 /clr /TP
VS 2010 | /WX- /Od /Oy- /D "WIN32" /D "_DEBUG" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "XLL_LIB_STL" /D "_UNICODE" /D "UNICODE" /Gm- /EHa /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

xlllibscrw.lib

Class library | STL
C Runtime Libraries | Multithreaded DLL
Common Language Runtime support | Common Language Runtime Support (/clr)
Use of MFC | None
Character set | Unicode
Configuration | Release
Compiler command lines |
VS 2005 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "UNICODE" /D "_UNICODE" /FD /EHa /MD /W3 /clr /TP
VS 2008 | /O2 /D "WIN32" /D "NDEBUG" /D "XLL_LIB_STL" /D "ISOLATION_AWARE_ENABLED=1" /D "UNICODE" /D "_UNICODE" /FD /EHa /MD /W3 /clr /TP
VS 2010 | /Zi /WX- /O2 /Oy- /D "WIN32" /D "NDEBUG" /D "_LIB" /D "ISOLATION_AWARE_ENABLED=1" /D "XLL_LIB_STL" /D "_UNICODE" /D "UNICODE" /Gm- /EHa /MD /GS /fp:precise /Zc:wchar_t /Zc:forScope /Gd

See Also

XLL+ Class Reference | Runtime dependencies | Project Settings | Class Reference


xllplus.h

Overview

xllplus.h contains all the core classes and definitions for XLL+ add-in projects.

The file is automatically included in the project files when the AppWizard creates the XLL+ project.

Classes

The table below lists the C++ object classes declared in the header file.

Class | Description
CXllApp | The object representing the add-in library itself. It can be used to store data that is global to the library.
CXlOper | A result sent back to Excel by an add-in function.
CXlRef | A reference to a rectangular block of cells.
CXllFn | A representation of a single add-in function.
CExcelWnd | An MFC window class that provides access to the Excel application window.
CXlArray | An array of floating-point numbers passed by or returned to Excel.
CXlBinaryNameData | A memory-managing data holder for BinaryName data.
CXlCell | A reference to a single cell within a CXlOper which holds an array.
CXlConstCell | A read-only reference to a single cell within a CXlOper which holds an array.

Functions & Macros

The table below lists the principal functions and macros declared in the header file.

Name | Description
IMPLEMENT_XLLFN4 | Declare and describe an add-in function.
XllGetApp | Get a pointer to the global data block.

Enumerations

The table below lists the enumerations declared in the header file.

Enumeration | Description
XlErrorType | A list of Excel's error values.
XlMessageBoxTypes | The set of message box types that can be used to show Excel modal message boxes.


CExcelWnd Class

Used to link MFC dialogs to Excel.

class CExcelWnd

Overview

The CExcelWnd class establishes a link between the Excel application window and the Microsoft Foundation Classes. In order to show a modal dialog during an add-in function (or during an add-in library event handler), you should construct a CExcelWnd to use as the parent of your own window.

See the Tutorial for an example of using CExcelWnd as the parent of an MFC dialog window.

Requirements

Header: xllplus.h

See Also

CExcelWnd Methods | xllplus.h | CXllFn object


CExcelWnd Methods

The methods of the CExcelWnd class are listed here.

Construction

public method CExcelWnd Constructs a CExcelWnd object and attaches it to Excel's application window

Requirements

Header: xllplus.h

See Also

CExcelWnd Class | xllplus.h | CXllFn object


CExcelWnd::CExcelWnd

Constructs a CExcelWnd object and attaches it to Excel's application window

CExcelWnd( );

Remarks

This constructor is all that is required to initialise the object.

Requirements

Header: xllplus.h

See Also

CExcelWnd Class | CExcelWnd Methods


CXlArray Class

class CXlArray

Overview

A CXlArray object encapsulates the XLARRAY structure. This structure is used by the Excel SDK, to pass data containing arrays of floating-point numbers.

CXlArray versus CXlOper

Both CXlOper and CXlArray can be used to pass floating-point arrays to add-in functions. We prefer to use CXlOper for two reasons:

  • Using CXlOper, it is possible for the add-in function to truncate any empty cells. If you use CXlArray, then all empty cells are filled with zeroes by Excel before the argument is passed to the add-in function. This may not be acceptable behaviour.
  • Using CXlOper, you can return a helpful error message if data is of the wrong type, e.g. "Expected number in Arg1(278)" for an error in the 278th cell of an array. Using CXlArray, Excel will merely return "#VALUE!", instead of calling the add-in function, which is much less helpful to the user, especially if the array is very large.

See also Comparison of CXlOper and CXlArray types.

Requirements

Header: xllplus.h

See Also

CXlArray Methods | xllplus.h


CXlArray Methods

The methods of the CXlArray class are listed here.

Construction

public method | Alloc | Resizes a CXlArray object
public method | AllocInit | Resizes a CXlArray object and initializes its members to zero
public method | Create | Creates and populates a CXlArray object
public method | CreateFromCols | Creates and populates a CXlArray object
public method | CreateFromRows | Creates and populates a CXlArray object
public method | CXlArray | Constructs a CXlArray object

Operations

public method | Clear | Reclaim resources from CXlArray
public method | Copy | Copies the contents of an CXlArray
public method | InitZero | Initialise the CXlArray contents

Comparisons

public method | Compare | Compare the contents of this CXlArray with another
public method | operator != | Compare the contents of this CXlArray with another
public method | operator < | Compare the contents of this CXlArray with another
public method | operator <= | Compare the contents of this CXlArray with another
public method | operator == | Compare the contents of this CXlArray with another
public method | operator > | Compare the contents of this CXlArray with another
public method | operator >= | Compare the contents of this CXlArray with another

Assignment operator

public method operator = Assigns a new value to the CXlArray

Access functions

public method | Cell | Returns a reference to an item in an array
public method | Cols | Returns the number of columns in an array
public method | Count | Returns the number of cells in an array
public method | GetDims | Gets the number of rows and columns in an array
public method | GetHeight | Returns the number of rows in an array
public method | GetPointer | Returns a pointer to the array of numbers
public method | GetWidth | Returns the number of columns in an array
public method | Row | Returns a pointer to a row of items in the array
public method | Rows | Returns the number of rows in an array

Internals

public method | GetArray12 | Returns a pointer to the internal XLARRAY12 structure
public method | GetArray4 | Returns a pointer to the internal XLARRAY4 structure
public method | Owned | Returns whether the internal XLARRAY structures are owned by the CXlArray object

Access functions

public method | Cell | Returns a reference to an item in an array
public method | Cols | Returns the number of columns in an array
public method | Count | Returns the number of cells in an array
public method | GetDims | Gets the number of rows and columns in an array
public method | GetHeight | Returns the number of rows in an array
public method | GetPointer | Returns a pointer to the array of numbers
public method | GetWidth | Returns the number of columns in an array
public method | Row | Returns a pointer to a row of items in the array
public method | Rows | Returns the number of rows in an array

Matrix & vector functions

public method | ReadMatrix | Reads data from a 2-dimensional array into a matrix of numbers
public method | ReadVector | Reads a row or a column from an array into a vector of numbers

Requirements

Header: xllplus.h

See Also

CXlArray Class | xllplus.h


CXlArray::Alloc

Resizes a CXlArray object

void Alloc(
   size_t cRows,
   size_t cCols
);

Parameters

cRows

The number of rows a newly created array object should contain.
cCols

The number of columns a newly created array object should contain.

Remarks

The array will be resized and all its values will be set to arbitrary values.

Exceptions

If memory allocation fails, then an exception of type CXlMemoryAllocationFailedException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods | CXlArray::AllocInit()


CXlArray::AllocInit

Resizes a CXlArray object and initializes its members to zero

void AllocInit(
   size_t cRows,
   size_t cCols
);

Parameters

cRows

The number of rows a newly created array object should contain.
cCols

The number of columns a newly created array object should contain.

Remarks

The array will be resized and all its values will be set to zero.

Exceptions

If memory allocation fails, then an exception of type CXlMemoryAllocationFailedException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods | CXlArray::Alloc()


CXlArray::Cell

Returns a reference to an item in an array

double& Cell(
   size_t row,
   size_t col
);
const double& Cell(
   size_t row,
   size_t col
) const;

Parameters

row

The row containing the item of interest (the top row is 0).
col

The column containing the item of interest (the leftmost column is 0).

Remarks

The reference returned by this function can be used to read the item and to update it.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::Clear

Reclaim resources from CXlArray

void Clear( );

Remarks

Clear the values in the CXlArray. This function is called automatically by the destructor when necessary.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods | CXlArray::InitZero()


CXlArray::Cols

Returns the number of columns in an array

size_t Cols( ) const;

Return Value

This function returns the width of an array.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::Compare

Compare the contents of this CXlArray with another

int Compare(
   const CXlArray& xla
) const;

Parameters

xla

A reference to a CXlArray object.

Return Value

Returns 1 if the value in this object is greater than that in xla, -1 if xla is less and 0 if the two are equal.

Remarks

This function acts like strcmp() and similar 'C' library functions.

Note that CXlArrays are sorted by size first and then by value.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::Copy

Copies the contents of an CXlArray

void Copy(
   const CXlArray& xla
);
void Copy(
   LPCXLARRAY4 pxla4
);
void Copy(
   LPCXLARRAY12 pxla12
);

Parameters

xla

An initialised CXlArray, whose contents will be copied to this CXlArray.
pxla4

An initialised XLARRAY4 structure, whose contents will be copied to this CXlArray.
pxla12

An initialised XLARRAY12 structure, whose contents will be copied to this CXlArray.

Remarks

This method assigns a new size and new values to the CXlArray. If the target CXlArray already contains data, then it will be appropriately cleared before the assignment.

Exceptions

If memory allocation fails, then an exception of type CXlMemoryAllocationFailedException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::Count

Returns the number of cells in an array

unsigned long long Count( ) const;

Return Value

This function returns the total number of cells contained in an CXlArray.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::Create

Creates and populates a CXlArray object

void Create(
   size_t cRows,
   size_t cCols,
   const double* pd
);

Parameters

cRows

The number of rows a newly created array object should contain.
cCols

The number of columns a newly created array object should contain.
pd

An array of double's, containing (cRows x cCols) items.

Exceptions

If memory allocation fails, then an exception of type CXlMemoryAllocationFailedException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods | CXlArray::CreateFromCols() | CXlArray::CreateFromRows()


CXlArray::CreateFromCols

Creates and populates a CXlArray object

void CreateFromCols(
   size_t cRows,
   size_t cCols,
   const double* const* apd
);

Parameters

cRows

The number of rows a newly created array object should contain.
cCols

The number of columns a newly created array object should contain.
apd

An array of cRows pointers to double arrays, each array containing cCols items.

Exceptions

If memory allocation fails, then an exception of type CXlMemoryAllocationFailedException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods | CXlArray::Create() | CXlArray::CreateFromRows()


CXlArray::CreateFromRows

Creates and populates a CXlArray object

void CreateFromRows(
   size_t cRows,
   size_t cCols,
   const double* const* apd
);

Parameters

cRows

The number of rows a newly created array object should contain.
cCols

The number of columns a newly created array object should contain.
apd

An array of cCols pointers to double arrays, each array containing cRows items.

Exceptions

If memory allocation fails, then an exception of type CXlMemoryAllocationFailedException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods | CXlArray::Create() | CXlArray::CreateFromCols()


CXlArray::CXlArray

Constructs a CXlArray object

CXlArray( );
CXlArray(
   LPCXLARRAY4 pxla4
);
CXlArray(
   LPCXLARRAY12 pxla12
);
CXlArray(
   const CXlArray& xla
);
CXlArray(
   size_t cRows,
   size_t cCols
);
CXlArray(
   const double* pd,
   size_t cItems,
   BOOL bRow = FALSE
);
CXlArray(
   double* pd,
   size_t cRows,
   size_t cCols,
   BOOL bByRows = FALSE
);
CXlArray(
   const double* const* apd,
   size_t cRows,
   size_t cCols,
   BOOL bByRows = FALSE
);
CXlArray(
   const xlp::matrix<double>& dmat,
   size_t usIgnoreRows = 0,
   size_t cIgnoreCols = 0,
   BOOL bTranspose = FALSE
);
CXlArray(
   const std::vector<double>& dvec,
   BOOL bRow,
   size_t cIgnoreCols = 0
);

Parameters

pxla4

A pointer to an XLARRAY4 structure, usually passed into an add-in function by Excel 2003 and below.
pxla12

A pointer to an XLARRAY12 structure, usually passed into an add-in function by Excel 2007 and above.
xla

An reference to an initialised CXlArray object, which will be copied.
cRows

The number of rows a newly created array object should contain.
cCols

The number of columns a newly created array object should contain.
pd

An array of double's, containing either cRows items, or (cRows x cCols) items, depending on the function variant used. For the latter type, the values should be arranged in the order specified by the bByRows parameter.
cItems

The number of rows contained in the supplied array of doubles.
bRow

If this is true, then a one-dimensional array will be created as a row; if FALSE, the array will be a column.
cCols

The number of columns contained in the supplied array of doubles.
bByRows

Storage order of arrays of double's. If TRUE, then values in the same row are stored contiguously, otherwise values in the same column are assumed to be stored contiguously.
apd

An array of pointers to double, containing either cRows arrays each of size cCols, or cCols arrays each of size cRows, depending on the order specified by the bByRows parameter.
dmat

A reference to a matrix of doubles. The array in the CXlArray will contain a copy of the matrix.
usIgnoreRows

The number of rows in the supplied matrix to be ignored. This feature is useful if the matrix has been populated by a function which uses 1-based arrays.
cIgnoreCols

The number of columns in the supplied matrix to be ignored. This feature is useful if the matrix has been populated by a function which uses 1-based arrays.
bTranspose

If TRUE, then the data in the matrix is transposed before it is placed in the CXlArray. If FALSE, it is not.
dvec

A reference to a vector of doubles. The array in the CXlArray will contain a copy of the matrix.
cIgnoreCols

The number of items in the supplied vector to be ignored. This feature is useful if the vector has been populated by a function which uses 1-based arrays.

Exceptions

If memory allocation fails, then an exception of type CXlMemoryAllocationFailedException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::GetArray12

Returns a pointer to the internal XLARRAY12 structure

LPXLARRAY12 GetArray12( );
LPCXLARRAY12 GetArray12( ) const;

Remarks

This function returns a pointer to the internal XLARRAY12 structure.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::GetArray4

Returns a pointer to the internal XLARRAY4 structure

LPXLARRAY4 GetArray4( );
LPCXLARRAY4 GetArray4( ) const;

Remarks

This function returns a pointer to the internal XLARRAY4 structure.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::GetDims

Gets the number of rows and columns in an array

void GetDims(
   size_t& rows,
   size_t& columns
) const;

Parameters

rows

Reference to a variable which will contain the number of rows in the array.
columns

Reference to a variable that will contain the number of columns in the array.

Remarks

This function gets the height and width of an array.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::GetHeight

Returns the number of rows in an array

size_t GetHeight( ) const;

Return Value

This function returns the height of an array.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::GetPointer

Returns a pointer to the array of numbers

double* GetPointer( );
const double* GetPointer( ) const;

Remarks

This function returns a pointer to the array of numbers within the CXlArray.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::GetWidth

Returns the number of columns in an array

size_t GetWidth( ) const;

Return Value

This function returns the width of an array.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::InitZero

Initialise the CXlArray contents

void InitZero( );

Remarks

This function initialises all the values in the CXlArray to zero.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods | CXlArray::Clear()


CXlArray::operator !=

Compare the contents of this CXlArray with another

int operator !=(
   const CXlArray& xla
) const;

Parameters

xla

A reference to a CXlArray object.

Return Value

Returns TRUE if the value in this object is not equal to that in xla; returns FALSE otherwise.

Remarks

Note that CXlArrays are sorted by size first and then by value.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::operator <

Compare the contents of this CXlArray with another

int operator <(
   const CXlArray& xla
) const;

Parameters

xla

A reference to a CXlArray object.

Return Value

Returns TRUE if the value in this object is less than that in xla; returns FALSE otherwise.

Remarks

Note that CXlArrays are sorted by size first and then by value.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::operator <=

Compare the contents of this CXlArray with another

int operator <=(
   const CXlArray& xla
) const;

Parameters

xla

An initialised XLOPER, or a reference to CXlArray.

Return Value

Returns TRUE if the value in this object is less than or equal to that in xla; returns FALSE otherwise.

Remarks

Note that CXlArrays are sorted by size first and then by value.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::operator =

Assigns a new value to the CXlArray

const CXlArray& operator =(
   const CXlArray& xla
);

Parameters

xla

An initialised CXlArray, whose contents will be copied to this CXlArray.

Remarks

This operator assigns a new value to the CXlArray. If the target CXlArray already contains data, then it will be appropriately cleared before the assignment.

Exceptions

If memory allocation fails, then an exception of type CXlMemoryAllocationFailedException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::operator ==

Compare the contents of this CXlArray with another

int operator ==(
   const CXlArray& xla
) const;

Parameters

xla

A reference to a CXlArray object.

Return Value

Returns TRUE if the value in this object is equal to that in xla; returns FALSE otherwise.

Remarks

Note that CXlArrays are sorted by size first and then by value.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::operator >

Compare the contents of this CXlArray with another

int operator >(
   const CXlArray& xla
) const;

Parameters

xla

A reference to a CXlArray object.

Return Value

Returns TRUE if the value in this object is greater than that in xla; returns FALSE otherwise.

Remarks

Note that CXlArrays are sorted by size first and then by value.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::operator >=

Compare the contents of this CXlArray with another

int operator >=(
   const CXlArray& xla
) const;

Parameters

xla

A reference to a CXlArray object.

Return Value

Returns TRUE if the value in this object is greater than or equal to that in xla; returns FALSE otherwise.

Remarks

Note that CXlArrays are sorted by size first and then by value.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::Owned

Returns whether the internal XLARRAY structures are owned by the CXlArray object

BOOL Owned( ) const;

Remarks

This function returns TRUE if the internal XLARRAY structures are owned by the CXlArray object and FALSE if a structures was passed in by Excel.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::ReadMatrix

Reads data from a 2-dimensional array into a matrix of numbers

BOOL ReadMatrix(
   ple::imtx<double>& mat1,
   const char* pszArgName,
   CString& strError,
   long* plUBound1 = 0,
   long* plUBound2 = 0,
   long lFlags = XLA_ARRAY_FLAGS_STD,
   long lLBound1 = 0,
   long lLBound2 = 0,
   long lIgnoreRows = 0,
   long lIgnoreCols = 0
) const;
BOOL ReadMatrix(
   ple::imtx<double>& mat1,
   const char* pszArgName,
   CXlOper& xloError,
   long* plUBound1 = 0,
   long* plUBound2 = 0,
   long lFlags = XLA_ARRAY_FLAGS_STD,
   long lLBound1 = 0,
   long lLBound2 = 0,
   long lIgnoreRows = 0,
   long lIgnoreCols = 0
) const;
BOOL ReadMatrix(
   xlp::matrix<double>& mat2,
   const char* pszArgName,
   CString& strError,
   long* plUBound1 = 0,
   long* plUBound2 = 0,
   long lFlags = XLA_ARRAY_FLAGS_STD,
   long lLBound1 = 0,
   long lLBound2 = 0,
   long lIgnoreRows = 0,
   long lIgnoreCols = 0
) const;
BOOL ReadMatrix(
   xlp::matrix<T>& mat2,
   const char* pszArgName,
   CXlOper& xloError,
   long* plUBound1 = 0,
   long* plUBound2 = 0,
   long lFlags = XLA_ARRAY_FLAGS_STD,
   long lLBound1 = 0,
   long lLBound2 = 0,
   long lIgnoreRows = 0,
   long lIgnoreCols = 0
) const;

Parameters

mat1

A matrix containing data of type double, whose contents will be replaced by the contents of the CXlArray.
pszArgName

The name of the argument that is being read. This will be used in any error strings that are generated.
strError

Reference to an error string buffer. If the function fails for any reason, a useful error string will be placed here, e.g. "MyArgName: expected number in cell 3, 2".
plUBound1

Pointer to upper bound of first dimension (height). If it is null, then it is ignored. If it is not null then it is used to check that the upper bounds of various arrays are consistent.

See Bounded input arrays for more information on the use of upper bounds.
plUBound2

Pointer to upper bound of second dimension (width). If it is null, then it is ignored. If it is not null then it is used to check that the upper bounds of various arrays are consistent.

See Bounded input arrays for more information on the use of upper bounds.
lFlags

Flags controlling the conversion. See matrix & vector flags for a full list of flag values.
lLBound1

This will be used as a lower bound in the output matrix. lLBound rows containing default values (zero or blank) will be inserted at the start of the output matrix.
lLBound2

This will be used as a lower bound in the output matrix. lLBound columns containing default values (zero or blank) will be inserted at the start of the output matrix.
lIgnoreRows

The first lIgnoreRows rows of input will be ignored. This option can be useful for excluding labels.
lIgnoreCols

The first lIgnoreCols columns of input will be ignored. This option can be useful for excluding labels.
xloError

If any error occurs, a description will be put into xloError. It can then conveniently be returned as the result of the add-in function.
mat2

A matrix of the deprecated class matrix<double>, containing items of type double, whose contents will be replaced by the contents of the CXlArray.

Return Value

The function returns TRUE if the conversion was successful, FALSE if it failed for any reason.

If it fails, an explanatory error string will be written to strError or xloError. This should be returned to the user.

Remarks

This function extracts a rectangular range of numbers from an array argument.

However, a wide variety of other options are available, if you use other flag values and optional arguments. See matrix & vector flags for a full list of flag values.

See Bounded input arrays for more information on the use of upper bounds.

Note Note:

This method is deprecated. Use XlReadMatrix instead.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::ReadVector

Reads a row or a column from an array into a vector of numbers

BOOL ReadVector(
   std::vector<double>& dvec,
   const TCHAR* pszArgName,
   CString& strError = 0,
   long* plUBound = 0,
   long lRowOrCol = XLA_UNIQUE_VECTOR,
   long lFlags = XLA_ARRAY_FLAGS_STD,
   long lLBound = 0,
   long lIgnoreItems = 0
) const;
BOOL ReadVector(
   std::vector<double>& dvec,
   const char* pszArgName,
   CXlOper& xloError,
   long* plUBound = 0,
   long lRowOrCol = XLA_UNIQUE_VECTOR,
   long lFlags = XLA_ARRAY_FLAGS_STD,
   long lLBound = 0,
   long lIgnoreItems = 0
) const;

Parameters

dvec

A vector of double, whose contents will be replaced by the contents of the OPER array.
pszArgName

The name of the argument that is being read. This will be used in any error strings that are generated.
strError

Reference to an error string buffer. If the function fails for any reason, a useful error string will be placed here, e.g. "MyArgName: expected number in cell 3".
plUBound

Pointer to upper bound. If it is null, then it is ignored. If it is not null then it is used to check that the upper bounds of various arrays are consistent. The value of the bound should be set to -1 before it is used.

If the value is found to be -1, then it will be set to the upper bound of the vector being read (i.e. the first vector that uses this bound). Thereafter (i.e. on all vectors that use this bound, other than the first) the value will be compared against the upper bound of the vector being read. If the two bounds are not identical, then an error will be reported and the function will return FALSE.

Depending on value of the XLA_BOUND_MASK bit of lFlags, the upper bound will be set either to the index of the last member of the array (XLA_BOUND_UBOUND_INNER) or the index + 1 (XLA_BOUND_UBOUND_OUTER).
lRowOrCol

Zero-based index of row or column to be extracted. If it is out of range, the function will fail.

If lRowOrCol is set to XLA_UNIQUE_VECTOR, then the only row of a single-row array (or the only column of a one-column array) will be returned: if the array has more than one row and more than one column, the function will report an error and return FALSE.
lFlags

Flags controlling the conversion. See matrix & vector flags for a full list of flag values.
lLBound

This will be used as a lower bound in the output vector. lLBound cells containing the default value will be inserted at the start of the output vector.
lIgnoreItems

The first lIgnoreItems of input will be ignored. This option can be useful for excluding labels.
xloError

If any error occurs, a description will be put into xloError. It can then conveniently be returned as the result of the add-in function.

Return Value

The function returns TRUE if the conversion was successful, FALSE if it failed for any reason.

If it fails, an explanatory error string will be written to *psErrorString. This should be returned to the user, along with the name of the argument that failed. See the example for more details.

Remarks

This function extracts a single row of numbers from an array argument. A wide variety of other options are available, if you use other flag values and optional arguments. See matrix & vector flags for a full list of flag values.

Note Note:

This method is deprecated. Use XlReadVector instead.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::Row

Returns a pointer to a row of items in the array

double* Row(
   size_t row
);
const double* Row(
   size_t row
) const;

Parameters

row

The row containing the item of interest (the top row is 0).

Remarks

The pointer returned by this function can be used to read the items in a row and to update them.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlArray::Rows

Returns the number of rows in an array

size_t Rows( ) const;

Return Value

This function returns the height of an array.

Requirements

Header: xllplus.h

See Also

CXlArray Class | CXlArray Methods


CXlBinaryNameData Class

Data holder for BinaryName data held persistently in workbooks.

class CXlBinaryNameData

Overview

The CXlBinaryNameData class is a data holder for BinaryName data.

Data held by Excel in a BinaryName is held in global moveable Windows memory and must be accessed with GlobalAlloc() and GlobalFree(). The CXlBinaryNameData object hides this implementation, and its destructor ensures that any locked memory is unlocked.

See CXllApp::GetBinaryName for an example of use.

Requirements

Header: xllplus.h

See Also

CXlBinaryNameData Methods | xllplus.h | CXllApp::DefineBinaryName | CXllApp::GetBinaryName


CXlBinaryNameData Methods

The methods of the CXlBinaryNameData class are listed here.

Construction

public method | ~CXlBinaryNameData | Destroys a CXlBinaryNameData object
public method | CXlBinaryNameData | Constructs an empty CXlBinaryNameData object

Accessor functions

public method | GetCount | Returns the number of bytes in the BinaryName data block
public method | GetData | Returns a pointer to the BinaryName data block

Requirements

Header: xllplus.h

See Also

CXlBinaryNameData Class | xllplus.h | CXllApp::DefineBinaryName | CXllApp::GetBinaryName


CXlBinaryNameData::~CXlBinaryNameData

Destroys a CXlBinaryNameData object

~CXlBinaryNameData( );

Remarks

This destructor ensures that any locked memory is unlocked.

Requirements

Header: xllplus.h

See Also

CXlBinaryNameData Class | CXlBinaryNameData Methods


CXlBinaryNameData::CXlBinaryNameData

Constructs an empty CXlBinaryNameData object

CXlBinaryNameData( );

Remarks

This constructor initialises the CXlBinaryNameData with null values.

Requirements

Header: xllplus.h

See Also

CXlBinaryNameData Class | CXlBinaryNameData Methods


CXlBinaryNameData::GetCount

Returns the number of bytes in the BinaryName data block

size_t GetCount( ) const;

Remarks

If no BinaryName data block has yet been assigned, this method returns zero.

Requirements

Header: xllplus.h

See Also

CXlBinaryNameData Class | CXlBinaryNameData Methods | CXlBinaryNameData::GetData


CXlBinaryNameData::GetData

Returns a pointer to the BinaryName data block

const void* GetData( ) const;

Remarks

If no BinaryName data block has yet been assigned, this method returns a null pointer.

Requirements

Header: xllplus.h

See Also

CXlBinaryNameData Class | CXlBinaryNameData Methods | CXlBinaryNameData::GetCount


CXlCell Class

A reference to a single item within an array CXlOper.

class CXlCell

Overview

A CXlCell object represents a single item within a CXlOper array. It is created by calling CXlOper::Cell which, if it succeeds, returns a new CXlCell object.

You can use the CXlCell object to read and write the contents of the item within the CXlOper array. Many of the same methods as offered by CXlOper are available to CXlCell. Many are excluded, including methods that deal with arrays (CXlCell can only refer to a single cell), references (CXlCell must contain a value - it cannot contain a reference) and SDK calls.

Because Excel 2007 and earlier versions of Excel use different XLOPER structures, code that directly reads or writes the structure must be aware of which version of Excel it is using. The CXlCell class wraps these differences, so that you can ignore which version of Excel is being run.

Data types

The table below lists the data types supported by the CXlCell class.

Type | 'C' type | Description
xltypeNum | double | IEEE floating-point number (8 bytes)
xltypeStr | LPSTR | Under Excel 2003 and below: an ASCII string (limited to 255 characters)
xltypeStr | LPWSTR | Under Excel 2007 and above: a Unicode string (limited to 32,767 characters)
xltypeBool | BOOL | Boolean
xltypeInt | short int | Under Excel 2003 and below: a 16-bit integer
xltypeInt | int | Under Excel 2007 and above: a 32-bit integer

Requirements

Header: xllplus.h

See Also

CXlCell Methods | xllplus.h | CXlConstCell | CXlOper::Cell | CXlOper


CXlCell Methods

The methods of the CXlCell class are listed here.

Comparisons

public method | Compare | Compare the contents of this CXlCell with another cell
public method | operator != | Compare the contents of this CXlCell with another cell
public method | operator < | Compare the contents of this CXlCell with another cell
public method | operator <= | Compare the contents of this CXlCell with another cell
public method | operator == | Compare the contents of this CXlCell with another cell
public method | operator > | Compare the contents of this CXlCell with another cell
public method | operator >= | Compare the contents of this CXlCell with another cell

Type inspection

public method | IsBool | Does the CXlCell contain a boolean?
public method | IsDouble | Does the CXlCell contain a double-precision floating point number?
public method | IsEmpty | Is the CXlCell empty?
public method | IsError | Does the CXlCell contain an error?
public method | IsInt | Does the CXlCell contain an integer?
public method | IsOfType | Is the CXlCell of the specified type?
public method | IsString | Does the CXlCell contain a string?

Assignment operators

public method operator = Assigns a new value to the CXlOper, using a variety of input types

Output casting operators

public method | operator BOOL | Returns a boolean value
public method | operator bool | Returns a boolean value
public method | operator CString | Returns a string value
public method | operator double | Returns a numeric value

Input functions

public method | FromBool | Assigns a boolean value and data type to the CXlCell
public method | FromDouble | Assigns an floating-point numeric value and data type to the CXlCell
public method | FromError | Assigns an error value and data type to the CXlCell
public method | FromInt | Assigns a single integer to the CXlCell
public method | FromString | Assigns a string value and data type to the CXlCell

Output functions

public method | ToBool | Returns a boolean value
public method | ToDouble | Retrieves a numeric value from the CXlCell
public method | ToInt | Returns an integer value
public method | ToString | Returns a string value

Construction

public method CXlCell Constructs a CXlCell object

Requirements

Header: xllplus.h

See Also

CXlCell Class | xllplus.h | CXlConstCell | CXlOper::Cell | CXlOper


CXlCell::Compare

Compare the contents of this CXlCell with another cell

int Compare(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns 1 if the value in this object is greater than that in xlo, -1 if xlo is less and 0 if the two are equal.

Remarks

This function acts like strcmp() and similar 'C' library functions.

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::CXlCell

Constructs a CXlCell object

CXlCell( );

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::FromBool

Assigns a boolean value and data type to the CXlCell

void FromBool(
   bool boolVal
);

Parameters

boolVal

Value to be applied to the CXlCell.

Remarks

This function assigns the value of boolVal to the CXlCell, and sets the type of the CXlCell to be xltypeBool.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::FromDouble

Assigns an floating-point numeric value and data type to the CXlCell

void FromDouble(
   double d
);

Parameters

d

Value to be applied to the CXlCell.

Remarks

This function assigns the value of d to the CXlCell, and sets the type of the CXlCell to be xltypeNum.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::FromError

Assigns an error value and data type to the CXlCell

void FromError(
   XlErrorType xlerr
);

Parameters

xlerr

Value to be applied to the CXlCell. See also Error Values for a description of error values.

Remarks

This function assigns the value of xlerr to the CXlCell, and sets the type of the CXlCell to be xltypeErr.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::FromInt

Assigns a single integer to the CXlCell

const CXlCell& FromInt(
   int i
);

Parameters

i

Integer value to be applied to the CXlOper.

Remarks

This function assigns the value i to the CXlCell, and sets the type of the CXlCell to be xltypeInt. This data type is only normally used as an argument to SDK calls.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::FromString

Assigns a string value and data type to the CXlCell

void FromString(
   const char* psz
);
void FromString(
   const std::string& str
);
void FromString(
   const wchar_t* wpsz
);
void FromString(
   const std::wstring& wstr
);

Parameters

psz

Value to be applied to the CXlCell. Note that under Excel 2007 and above, the string will be converted to Unicode.

str

STL ASCII string to be applied to the CXlCell. Note that under Excel 2007 and above, the string will be converted to Unicode.

wpsz

A null-terminated Unicode string which will be copied to the CXlCell. Note that under Excel 2003 and below, the string will be converted to a multibyte character ASCII string, and limited to 255 bytes.

wstr

A reference to an STL Unicode string which will be copied to the CXlCell. Note that under Excel 2003 and below, the string will be converted to a multibyte character ASCII string, and limited to 255 bytes.

Remarks

This function assigns the value of psz to the CXlCell, and sets the type of the CXlCell to be xltypeStr.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::IsBool

Does the CXlCell contain a boolean?

BOOL IsBool( ) const;

Return Value

Returns TRUE if the CXlCell contains a boolean value, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods | CXlCell::IsOfType() | CXlCell::IsDouble() | CXlCell::IsError() | CXlCell::IsString() | CXlCell::IsEmpty() | CXlCell::IsInt()


CXlCell::IsDouble

Does the CXlCell contain a double-precision floating point number?

BOOL IsDouble( ) const;

Return Value

Returns TRUE if the CXlCell contains a single floating point value, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods | CXlCell::IsOfType() | CXlCell::IsError() | CXlCell::IsBool() | CXlCell::IsString() | CXlCell::IsEmpty() | CXlCell::IsInt()


CXlCell::IsEmpty

Is the CXlCell empty?

BOOL IsEmpty( ) const;

Return Value

Returns TRUE if the CXlCell is uninitialised, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods | CXlCell::IsOfType() | CXlCell::IsDouble() | CXlCell::IsBool() | CXlCell::IsError() | CXlCell::IsInt()


CXlCell::IsError

Does the CXlCell contain an error?

BOOL IsError( ) const;

Return Value

Returns TRUE if the CXlCell contains an error value, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods | CXlCell::IsOfType() | CXlCell::IsDouble() | CXlCell::IsBool() | CXlCell::IsString() | CXlCell::IsEmpty() | CXlCell::IsInt()


CXlCell::IsInt

Does the CXlCell contain an integer?

BOOL IsInt( ) const;

Return Value

Returns TRUE if the CXlCell contains an integer type, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods | CXlCell::IsOfType() | CXlCell::IsDouble() | CXlCell::IsBool() | CXlCell::IsError() | CXlCell::IsString() | CXlCell::IsEmpty()


CXlCell::IsOfType

Is the CXlCell of the specified type?

BOOL IsOfType(
   WORD xltype
) const;

Parameters

xltype

A xltype value. This should be one of the xltype values listed in CXlOper data types.

Return Value

Returns TRUE if the CXlCell is of the specified type, FALSE if it is of any other type.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods | CXlCell::IsDouble() | CXlCell::IsError() | CXlCell::IsBool() | CXlCell::IsString() | CXlCell::IsEmpty() | CXlCell::IsInt()


CXlCell::IsString

Does the CXlCell contain a string?

BOOL IsString( ) const;

Return Value

Returns TRUE if the CXlCell contains a string value, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods | CXlCell::IsOfType() | CXlCell::IsDouble() | CXlCell::IsError() | CXlCell::IsEmpty() | CXlCell::IsInt()


CXlCell::operator !=

Compare the contents of this CXlCell with another cell

int operator !=(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns TRUE if the value in this object is not equal to that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are compared by type first and then by value. Thus a string containing "123" will not be equal to an integer containing 123.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::operator <

Compare the contents of this CXlCell with another cell

int operator <(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns TRUE if the value in this object is less than that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::operator <=

Compare the contents of this CXlCell with another cell

int operator <=(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns TRUE if the value in this object is less than or equal to that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::operator =

Assigns a new value to the CXlOper, using a variety of input types

const CXlCell& operator =(
   const CXlOper& xlo
);
const CXlCell& operator =(
   const CXlCell& cell
);
const CXlCell& operator =(
   const CXlConstCell& ccell
);
const CXlCell& operator =(
   double d
);
const CXlCell& operator =(
   XlErrorType xlerr
);
const CXlCell& operator =(
   BOOL wboolean
);
const CXlCell& operator =(
   bool boolean
);
const CXlCell& operator =(
   const char* psz
);
const CXlCell& operator =(
   const wchar_t* wpsz
);
const CXlCell& operator =(
   const std::string& str_stl
);
const CXlCell& operator =(
   const std::wstring& wstr_stl
);
const CXlCell& operator =(
   const CString& str
);
const CXlCell& operator =(
   const CStringA& astr
);
const CXlCell& operator =(
   const CStringW& wstr
);

Parameters

xlo

An initialised CXlOper, whose contents will be copied to this object, if it contains a single value.
cell

An initialised CXlCell, which points to a cell in a CXlOper whose contents will be copied to this object. See CXlCell.

ccell

An initialised CXlConstCell, which points to a cell in a CXlOper whose contents will be copied to this object. See CXlConstCell.

d

A double-precision floating-point number.
xlerr

An error number (see also Error Values).
wboolean

A boolean value: TRUE (1) or FALSE (0).
boolean

A boolean value: true or false.
psz

A pointer to a null-terminated ASCII string. Note that under Excel 2007 and above, the string wil be converted to Unicode.
wpsz

A pointer to a null-terminated Unicode string. Note that under Excel 2003 and below, the string will be converted to a multibyte ASCII string, and limited to 255 bytes.
str_stl

A reference to an STL ASCII string. Note that under Excel 2007 and above, the string will be converted to Unicode.

wstr_stl

A reference to an STL Unicode string. Note that under Excel 2003 and below, the string will be converted to a multibyte character ASCII string, and limited to 255 bytes.

str

A reference to a compiler-dependent string. Note that under Excel 2007 and above, the string will be converted to Unicode if necessary. Under Excel 2003 and below, the string will be converted to a multibyte character ASCII string if necessary, and limited to 255 bytes.

astr

A reference to an ASCII string. Note that under Excel 2007 and above, the string will be converted to Unicode.

wstr

A reference to a Unicode string. Note that under Excel 2003 and below, the string will be converted to a multibyte character ASCII string, and limited to 255 bytes.

Remarks

These operators assign a new value to the item referenced by the CXlCell. If the item already contains data, then it will be appropriately cleared before the assignment.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::operator ==

Compare the contents of this CXlCell with another cell

int operator ==(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns TRUE if the value in this object is equal to that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are compared by type first and then by value. Thus a string containing "123" will not be equal to an integer containing 123.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::operator >

Compare the contents of this CXlCell with another cell

int operator >(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns TRUE if the value in this object is greater than that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::operator >=

Compare the contents of this CXlCell with another cell

int operator >=(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns TRUE if the value in this object is greater than or equal to that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::operator BOOL

Returns a boolean value

operator BOOL( ) const;

Return Value

This function returns the value of a boolean contained in a CXlCell, or throws an exception of type CXlConversionException if the CXlCell contains any other data type.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::operator bool

Returns a boolean value

operator bool( ) const;

Return Value

This function returns the value of a boolean contained in a CXlCell, or throws an exception of type CXlConversionException if the CXlCell contains any other data type.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::operator CString

Returns a string value

operator CString( ) const;

Return Value

This function returns the value of a string contained in a CXlCell, or throws an exception of type CXlConversionException if the CXlCell contains any other data type.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::operator double

Returns a numeric value

operator double( ) const;

Return Value

This function returns the value of a double contained in a CXlCell, or throws an exception of type CXlConversionException if the CXlCell contains any other data type.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::ToBool

Returns a boolean value

bool ToBool(
   bool bStrict = FALSE
) const;

Parameters

bStrict

If bStrict is false (the default) then, if the CXlCell does not contain a boolean value, the function will safely return an appropriate converted value.

If bStrict is true then the function will throw an exception of type CXlConversionException unless the CXlCell contains a boolean.

Return Value

This function returns the boolean value contained in a CXlCell.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::ToDouble

Retrieves a numeric value from the CXlCell

double ToDouble(
   bool bStrict = FALSE
) const;

Parameters

bStrict

If bStrict is false (the default) then, if the CXlCell does not contain a double, the function will safely return an appropriate converted double (0 for blanks).

If bStrict is true then the function will throw an exception of type CXlConversionException unless the CXlCell contains a double.

Return Value

This function returns the double value contained in a CXlCell.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::ToInt

Returns an integer value

short int ToInt(
   bool bStrict = FALSE
) const;

Parameters

bStrict

If bStrict is false (the default) then, if the CXlCell does not contain an integer value, the function will safely return an appropriate converted value.

If bStrict is true then the function will throw an exception of type CXlConversionException unless the CXlCell contains an integer.

Return Value

This function returns the integer value contained in a CXlCell.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlCell::ToString

Returns a string value

CString ToString(
   bool bStrict = FALSE
) const;

Parameters

bStrict

If bStrict is false (the default) then, if the CXlCell does not contain a string, the function will safely return an appropriate converted string.

If bStrict is true then the function will throw an exception of type CXlConversionException unless the CXlCell contains a string.

Return Value

This function returns the string value contained in a CXlCell.

Requirements

Header: xllplus.h

See Also

CXlCell Class | CXlCell Methods


CXlConstCell Class

A read-only reference to a single item within an array CXlOper.

class CXlConstCell

Overview

A CXlConstCell object represents a single item within a CXlOper array. It is created by calling CXlOper::Cell on a read-only CXlOper which, if it succeeds, returns a new CXlConstCell object.

You can use the CXlConstCell object to read the contents of the item within the CXlOper array. Many of the same methods as offered by CXlCell are available to CXlCell. Many are excluded, including all methods that write to the cell.

Because Excel 2007 and earlier versions of Excel use different XLOPER structures, code that directly reads or writes the structure must be aware of which version of Excel it is using. The CXlConstCell class wraps these differences, so that you can ignore which version of Excel is being run.

Data types

The table below lists the data types supported by the CXlConstCell class.

Type | 'C' type | Description
xltypeNum | double | IEEE floating-point number (8 bytes)
xltypeStr | LPSTR | Under Excel 2003 and below: an ASCII string (limited to 255 characters)
xltypeStr | LPWSTR | Under Excel 2007 and above: a Unicode string (limited to 32,767 characters)
xltypeBool | BOOL | Boolean
xltypeInt | short int | Under Excel 2003 and below: a 16-bit integer
xltypeInt | int | Under Excel 2007 and above: a 32-bit integer

Requirements

Header: xllplus.h

See Also

CXlConstCell Methods | xllplus.h | CXlCell | CXlOper::Cell | CXlOper


CXlConstCell Methods

The methods of the CXlConstCell class are listed here.

Comparisons

public method | Compare | Compare the contents of this CXlConstCell with another cell
public method | operator != | Compare the contents of this CXlConstCell with another cell
public method | operator < | Compare the contents of this CXlConstCell with another cell
public method | operator <= | Compare the contents of this CXlConstCell with another cell
public method | operator == | Compare the contents of this CXlConstCell with another cell
public method | operator > | Compare the contents of this CXlConstCell with another cell
public method | operator >= | Compare the contents of this CXlConstCell with another cell

Type inspection

public method | IsBool | Does the CXlConstCell contain a boolean?
public method | IsDouble | Does the CXlConstCell contain a double-precision floating point number?
public method | IsEmpty | Is the CXlConstCell empty?
public method | IsError | Does the CXlConstCell contain an error?
public method | IsInt | Does the CXlConstCell contain an integer?
public method | IsOfType | Is the CXlConstCell of the specified type?
public method | IsString | Does the CXlConstCell contain a string?

Output casting operators

public method | operator BOOL | Returns a boolean value
public method | operator bool | Returns a boolean value
public method | operator CString | Returns a string value
public method | operator double | Returns a numeric value

Output functions

public method | ToBool | Returns a boolean value
public method | ToDouble | Retrieves a numeric value from the CXlConstCell
public method | ToInt | Returns an integer value
public method | ToString | Returns a string value

Construction

public method CXlConstCell Constructs a CXlConstCell object

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | xllplus.h | CXlCell | CXlOper::Cell | CXlOper


CXlConstCell::Compare

Compare the contents of this CXlConstCell with another cell

int Compare(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns 1 if the value in this object is greater than that in xlo, -1 if xlo is less and 0 if the two are equal.

Remarks

This function acts like strcmp() and similar 'C' library functions.

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::CXlConstCell

Constructs a CXlConstCell object

CXlConstCell( );

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::IsBool

Does the CXlConstCell contain a boolean?

BOOL IsBool( ) const;

Return Value

Returns TRUE if the CXlConstCell contains a boolean value, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods | CXlConstCell::IsOfType() | CXlConstCell::IsDouble() | CXlConstCell::IsError() | CXlConstCell::IsString() | CXlConstCell::IsEmpty() | CXlConstCell::IsInt()


CXlConstCell::IsDouble

Does the CXlConstCell contain a double-precision floating point number?

BOOL IsDouble( ) const;

Return Value

Returns TRUE if the CXlConstCell contains a single floating point value, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods | CXlConstCell::IsOfType() | CXlConstCell::IsError() | CXlConstCell::IsBool() | CXlConstCell::IsString() | CXlConstCell::IsEmpty() | CXlConstCell::IsInt()


CXlConstCell::IsEmpty

Is the CXlConstCell empty?

BOOL IsEmpty( ) const;

Return Value

Returns TRUE if the CXlConstCell is uninitialised, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods | CXlConstCell::IsOfType() | CXlConstCell::IsDouble() | CXlConstCell::IsBool() | CXlConstCell::IsError() | CXlConstCell::IsInt()


CXlConstCell::IsError

Does the CXlConstCell contain an error?

BOOL IsError( ) const;

Return Value

Returns TRUE if the CXlConstCell contains an error value, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods | CXlConstCell::IsOfType() | CXlConstCell::IsDouble() | CXlConstCell::IsBool() | CXlConstCell::IsString() | CXlConstCell::IsEmpty() | CXlConstCell::IsInt()


CXlConstCell::IsInt

Does the CXlConstCell contain an integer?

BOOL IsInt( ) const;

Return Value

Returns TRUE if the CXlConstCell contains an integer type, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods | CXlConstCell::IsOfType() | CXlConstCell::IsDouble() | CXlConstCell::IsBool() | CXlConstCell::IsError() | CXlConstCell::IsString() | CXlConstCell::IsEmpty()


CXlConstCell::IsOfType

Is the CXlConstCell of the specified type?

BOOL IsOfType(
   WORD xltype
) const;

Parameters

xltype

A xltype value. This should be one of the xltype values listed in CXlOper data types.

Return Value

Returns TRUE if the CXlConstCell is of the specified type, FALSE if it is of any other type.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods | CXlConstCell::IsDouble() | CXlConstCell::IsError() | CXlConstCell::IsBool() | CXlConstCell::IsString() | CXlConstCell::IsEmpty() | CXlConstCell::IsInt()


CXlConstCell::IsString

Does the CXlConstCell contain a string?

BOOL IsString( ) const;

Return Value

Returns TRUE if the CXlConstCell contains a string value, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods | CXlConstCell::IsOfType() | CXlConstCell::IsDouble() | CXlConstCell::IsError() | CXlConstCell::IsEmpty() | CXlConstCell::IsInt()


CXlConstCell::operator !=

Compare the contents of this CXlConstCell with another cell

int operator !=(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns TRUE if the value in this object is not equal to that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are compared by type first and then by value. Thus a string containing "123" will not be equal to an integer containing 123.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::operator <

Compare the contents of this CXlConstCell with another cell

int operator <(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns TRUE if the value in this object is less than that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::operator <=

Compare the contents of this CXlConstCell with another cell

int operator <=(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns TRUE if the value in this object is less than or equal to that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::operator ==

Compare the contents of this CXlConstCell with another cell

int operator ==(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns TRUE if the value in this object is equal to that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are compared by type first and then by value. Thus a string containing "123" will not be equal to an integer containing 123.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::operator >

Compare the contents of this CXlConstCell with another cell

int operator >(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns TRUE if the value in this object is greater than that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::operator >=

Compare the contents of this CXlConstCell with another cell

int operator >=(
   const CXlOperBase& xlo
) const;

Parameters

xlo

A reference to another CXlCell, CXlConstCell or CXlOper.

Return Value

Returns TRUE if the value in this object is greater than or equal to that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::operator BOOL

Returns a boolean value

operator BOOL( ) const;

Return Value

This function returns the value of a boolean contained in a CXlConstCell, or throws an exception of type CXlConversionException if the CXlConstCell contains any other data type.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::operator bool

Returns a boolean value

operator bool( ) const;

Return Value

This function returns the value of a boolean contained in a CXlConstCell, or throws an exception of type CXlConversionException if the CXlConstCell contains any other data type.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::operator CString

Returns a string value

operator CString( ) const;

Return Value

This function returns the value of a string contained in a CXlConstCell, or throws an exception of type CXlConversionException if the CXlConstCell contains any other data type.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::operator double

Returns a numeric value

operator double( ) const;

Return Value

This function returns the value of a double contained in a CXlConstCell, or throws an exception of type CXlConversionException if the CXlConstCell contains any other data type.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::ToBool

Returns a boolean value

bool ToBool(
   bool bStrict = FALSE
) const;

Parameters

bStrict

If bStrict is false (the default) then, if the CXlConstCell does not contain a boolean value, the function will safely return an appropriate converted value.

If bStrict is true then the function will throw an exception of type CXlConversionException unless the CXlConstCell contains a boolean.

Return Value

This function returns the boolean value contained in a CXlConstCell.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::ToDouble

Retrieves a numeric value from the CXlConstCell

double ToDouble(
   bool bStrict = FALSE
) const;

Parameters

bStrict

If bStrict is false (the default) then, if the CXlConstCell does not contain a double, the function will safely return an appropriate converted double (0 for blanks).

If bStrict is true then the function will throw an exception of type CXlConversionException unless the CXlConstCell contains a double.

Return Value

This function returns the double value contained in a CXlConstCell.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::ToInt

Returns an integer value

short int ToInt(
   bool bStrict = FALSE
) const;

Parameters

bStrict

If bStrict is false (the default) then, if the CXlConstCell does not contain an integer value, the function will safely return an appropriate converted value.

If bStrict is true then the function will throw an exception of type CXlConversionException unless the CXlConstCell contains an integer.

Return Value

This function returns the integer value contained in a CXlConstCell.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXlConstCell::ToString

Returns a string value

CString ToString(
   bool bStrict = FALSE
) const;

Parameters

bStrict

If bStrict is false (the default) then, if the CXlConstCell does not contain a string, the function will safely return an appropriate converted string.

If bStrict is true then the function will throw an exception of type CXlConversionException unless the CXlConstCell contains a string.

Return Value

This function returns the string value contained in a CXlConstCell.

Requirements

Header: xllplus.h

See Also

CXlConstCell Class | CXlConstCell Methods


CXllApp Class

Represents an add-in library.

class CXllApp

Overview

The CXllApp class represents your XLL add-in. It is a singleton class: only one instance may exist in any application.

Your implementation class, which is generated by the XLL Plus AppWizard, is descended from CXllApp, and contains methods and data that are unique to your specific add-in.

The CXllApp class implements most of the functionality necessary for a DLL to be accepted by Excel as an add-in library.

One and only one instance of CXllApp exists in any XLL. You can retrieve a pointer to it using the CXllApp::Instance method.

You can use your derived application class as a place to store data that must have a lifetime as long as that of the library (i.e. 'global' data). Database connections, logon details and performance statistics all fall into this category, and can usefully be stored in the application object. However, if any of your functions are marked as thread-safe you should also ensure that any data members used by thread-safe functions are also thread-safe themselves.

Data that lives in the application class exists once for each instance of the library. Thus, if you have three instances of Excel using the add-in, you will have three separate copies of the data contained in the application class.

MFC Considerations

The CXllApp class is descended from CWinApp. Your implementation class, which is generated by the XLL Plus AppWizard, is in turn descended from CXllApp.

See XLL_FIX_STATE for constraints on using the CXllAppp instance.

Common Language Runtime

Some methods that are used by the Common Language Runtime (.NET) builds are only available in those builds. These are:

CXllApp::GetApplicationObject()
CXllApp::ClrExceptionToText()

In addition, the following methods have no effect except undr CLR builds:

CXllApp::SetPrivateBinPath()
CXllApp::GetPrivateBinPath()

Requirements

Header: xllplus.h

See Also

CXllApp Methods | xllplus.h | CXllFn object


CXllApp Methods

The methods of the CXllApp class are listed here.

Construction

public method CXllApp Constructs a CXllApp object

Singleton

Instance Return the single instance of CXllApp

Attributes

public method | GetFnCount | Get a count of the add-in functions in the library
public method | GetNextFnAssoc | Iterate the function map
public method | GetNextFnAssocA | Iterate the function map
public method | GetNextFnAssocW | Iterate the function map
public method | GetStartFnPosition | Get the starting position for iterating the function map

Function list operations

public method | AddFn | Add a function to the list of functions to be registered
public method | AddStaticFns | Adds the XLL's functions to the global list of Excel add-in functions to be registered
public method | FindFn | Find a function in the function list
public method | FindFnA | Find a function in the function list
public method | FindFnW | Find a function in the function list
public method | GetAllFns | Get all functions in the function list
public method | GetHideArgumentBoxForNoArgs | Get the value of the property that controls the behavior of the Excel Formula Wizard for functions with no arguments
public method | PrefixFunctions | Add a string prefix to all the library's add-in functions
public method | PrefixFunctionsA | Add a string prefix to all the library's add-in functions
public method | PrefixFunctionsW | Add a string prefix to all the library's add-in functions
public method | RemoveFn | Remove a function from the list of functions to be registered
public method | RemoveFnA | Remove a function from the list of functions to be registered
public method | RemoveFnW | Remove a function from the list of functions to be registered
public method | SetHideArgumentBoxForNoArgs | Set the behavior of the Excel Formula Wizard for functions with no arguments

SDK interface

CancelUserAbort | Cancels pending abort request
Excel | Invoke the Excel SDK
GetCalculationMode | Get Excel's calculation mode
GetCallerDims | Get the dimensions of the range from which this add-in function was called
GetInternational | Returns information about the current country and international settings.
GetSheetId | Get the sheet ID of a named sheet
GetSheetName | Get the name of sheet from its sheet ID
GetSheetNameA | Get the name of sheet from its sheet ID
GetSheetNameW | Get the name of sheet from its sheet ID
GetUserAbort | Returns whether user has aborted operation
GetXlVersion | Return the Excel version number
IsInFormulaWizard | Is Excel currently showing the Formula Wizard ?
MakeSheetName | Combine a workbook and sheet name to [book]sheet format
SetCalculationMode | Set Excel's calculation mode
SetErrorHandling | Switch on or off XLM4 macro error handling
SplitSheetName | Get a workbook and sheet name from [book]sheet format
WinMessageBox | Display the standard Windows message box
WinMessageBoxA | Display the standard Windows message box
WinMessageBoxW | Display the standard Windows message box
XlGetStackSpace | Gets the number of bytes of remaining stack space
XlGetStackSpace2 | Gets the number of bytes of remaining stack space
XlHwnd | Return Excel's application window handle
XlMessageBox | Display the Excel message box
XlMessageBoxA | Display the Excel message box
XlMessageBoxW | Display the Excel message box
XlVersion | Return the Excel version number

Miscellaneous

 | ConvertTypeToError | Translates exception types to standard Excel error values
 | ErrorToString | Convert an error value to a string.
 | ErrorToStringA | Convert an error value to a string.
 | ErrorToStringW | Convert an error value to a string.
public method | GetColumnPrefix | Return the character used for columns in R1C1 format
 | GetLibraryVersion | Return the XLL+ run-time library version.
public method | GetListSeparator | Return the character used for separating arguments
 | GetNumericToStringConversionMethod | Return the value of the NumericToStringConversionMethod flag.
public method | GetObserverFunctionName | Return the name of the add-in function that observes COM events.
public method | GetRibbonCallbackFunctionName | Return the name of the add-in function that observes Ribbon events.
public method | GetRowPrefix | Return the character used for rows in R1C1 format
public method | GetRtdAsyncManager | Return a pointer to the RTD asynchronous function manager.
 | GetVersionInfo | Return the version info of the XLL, including version number, copyright and build information.
 | GetVersionInfoA | Return the version info of the XLL, including version number, copyright and build information.
 | GetVersionInfoW | Return the version info of the XLL, including version number, copyright and build information.
public method | GetXlAsyncManager | Return a pointer to the queued function manager.
public method | GetXllDir | Return the directory containing the XLL.
public method | GetXllFileName | Return the file name of the XLL.
public method | GetXllFileNameOnly | Return the file name of the XLL, excluding extension.
 | GetXllName | Return the full path of the XLL.
 | GetXllNameA | Return the full path of the XLL.
 | GetXllNameW | Return the full path of the XLL.
 | RetString | Return a string value to Excel.
 | SetNumericToStringConversionMethod | Set the value of the NumericToStringConversionMethod flag.

Overridables

public method | AfterXllOpen | Called by the framework when Excel opens the XLL, after all other processing is complete.
public method | DisplayException | Called by wrapper functions to translate caught exceptions to error messages
public method | ExitInstance | Called by the framework when the XLL is unloaded from memory
public method | GetDllName | Called by the framework to get the name of the DLL containing the add-in functions when they are registered
public method | GetRegDllName | Called by the framework to get the name of the DLL containing the add-in functions when they are registered
public method | InitInstance | Called by the framework when the XLL is loaded into memory
public method | OnXllClose | Called by the framework when Excel closes the XLL
public method | OnXllLoad | Called by the framework when Excel loads the XLL into memory
public method | OnXllOpen | Called by the framework when Excel opens the XLL
public method | OnXllOpenEx | Called by the framework when Excel opens the XLL. Programmer can return FALSE to halt further loading of the XLL.
public method | OnXllRegister | Called by the framework when the add-in is registered with the Excel Add-in Manager
public method | OnXllRegisterEx | Called by the framework when the add-in is registered with the Excel Add-in Manager
public method | OnXllUnload | Called by the framework when Excel unloads the XLL
public method | OnXllUnregister | Called by the framework when the add-in is removed from the list of add-ins with the Excel Add-in Manager
public method | ReportRegistrationFailures | Called by the framework to report any add-in functions that fail to register during initialization

COM support

public method | GetApplicationDispatch | Returns a dispatch pointer to the Excel Application object
public method | GetCom | Returns a dispatch pointer to the COM interface instance
public method | GetUseAutomation | Returns the value of the UseAutomation attribute
public method | SetUseAutomation | Returns the value of the UseAutomation attribute

COM event management

public method | GetComEventHandler | Returns the name of an add-in function to handle a specific COM event
public method | GetSinkEvents | Returns the state of the COM event handler
public method | SetComEventHandler | Sets the name of an add-in function to handle a specific COM event
public method | SetSinkEvents | Sets the SinkEvents flag to switch COM event handling on or off

COM event handlers

public method | OnAfterCalculate | Called by the framework just after calculation is completed
public method | OnNewWorkbook | Called by the framework when Excel creates a new workbook
public method | OnSheetActivate | Called by the framework when the user activates a worksheet
public method | OnSheetBeforeDoubleClick | Called by the framework when the user double-clicks in a worksheet
public method | OnSheetBeforeRightClick | Called by the framework when the user right-clicks in a worksheet
public method | OnSheetCalculate | Called by the framework when any worksheet is recalculated
public method | OnSheetChange | Called by the framework when the user changes the contents of a cell
public method | OnSheetDeactivate | Called by the framework when the user deactivates a worksheet
public method | OnSheetSelectionChange | Called by the framework when the user changes the selection
public method | OnWorkbookActivate | Called by the framework when a workbook is activated
public method | OnWorkbookAddinInstall | Called by the framework when an addin is installed
public method | OnWorkbookAddinUninstall | Called by the framework when an addin is uninstalled
public method | OnWorkbookAfterSave | Called by the framework just after a workbook is saved
public method | OnWorkbookBeforeClose | Called by the framework just before a workbook is closed
public method | OnWorkbookBeforePrint | Called by the framework just before a workbook is printed
public method | OnWorkbookBeforeSave | Called by the framework just before a workbook is saved
public method | OnWorkbookDeactivate | Called by the framework when a workbook is deactivated
public method | OnWorkbookNewSheet | Called by the framework when a new sheet is added to a workbook
public method | OnWorkbookOpen | Called by the framework when a workbook is opened

BinaryName support

ClearBinaryName | Clear a binary name from a worksheet
ClearBinaryNameA | Clear a binary name from a worksheet
ClearBinaryNameW | Clear a binary name from a worksheet
DefineBinaryName | Define a binary name in a worksheet and assign a block of data to it
DefineBinaryNameA | Define a binary name in a worksheet and assign a block of data to it
DefineBinaryNameW | Define a binary name in a worksheet and assign a block of data to it
GetBinaryName | Retrieve a binary name from a worksheet
GetBinaryNameA | Retrieve a binary name from a worksheet
GetBinaryNameW | Retrieve a binary name from a worksheet

Events

public method | AfterCalculateEvent | Gets a reference to the AfterCalculate event
public method | BeforeDoubleClickEvent | Gets a reference to the BeforeDoubleClick event
public method | BeforeRightClickEvent | Gets a reference to the BeforeRightClick event
public method | CalculateEvent | Gets a reference to the Calculate event
public method | NewWorkbookEvent | Gets a reference to the NewWorkbook event
public method | RegisterFunctionsEvent | Gets a reference to the RegisterFunctions event
public method | SelectionChangeEvent | Gets a reference to the SelectionChange event
public method | SheetActivateEvent | Gets a reference to the SheetActivate event
public method | SheetChangeEvent | Gets a reference to the SheetChange event
public method | SheetDeactivateEvent | Gets a reference to the SheetDeactivate event
public method | WorkbookActivateEvent | Gets a reference to the WorkbookActivate event
public method | WorkbookAfterSaveEvent | Gets a reference to the WorkbookAfterSave event
public method | WorkbookBeforeCloseEvent | Gets a reference to the WorkbookBeforeClose event
public method | WorkbookBeforeSaveEvent | Gets a reference to the WorkbookBeforeSave event
public method | WorkbookDeactivateEvent | Gets a reference to the WorkbookDeactivate event
public method | WorkbookNewSheetEvent | Gets a reference to the WorkbookNewSheet event
public method | WorkbookOpenEvent | Gets a reference to the WorkbookOpen event
public method | XllCloseEvent | Gets a reference to the XllClose event
public method | XllOpenEvent | Gets a reference to the XllOpen event

Common Language Runtime support

 | ClrExceptionToText | Converts a CLR Exception to an error message.
 | GetApplicationObject | Returns a .NET object containing a handle to the Excel.Application COM object.
public method | GetPrivateBinPath | Gets the private path used by the .NET Assembly loader.
public method | SetPrivateBinPath | Sets the private path used by the .NET Assembly loader.

Ribbon support

public method | GetHasRibbon | Returns whether the application has a ribbon
public method | InitializeRibbon | Requests the ribbon manager to intialize the ribbon controls for this add-in
public method | InvalidateRibbon | Requests the ribbon manager to invalidate the ribbon controls for all add-ins using the ribbon manager
public method | InvalidateRibbonControl | Requests the ribbon manager to invalidate a single ribbon control owned by this add-in
public method | InvalidateRibbonForAddin | Requests the ribbon manager to invalidate the ribbon controls for this add-in
public method | OnRibbonEvent | Called by the framework when a ribbon event occurs.
public method | SetHasRibbon | Sets whether the application has a ribbon
public method | SetRibbonImplementation | Sets the implementation used by the application to support a ribbon
public method | SupportsRibbon | Returns whether the container application can support a ribbon
public method | TerminateRibbon | Requests the ribbon manager to terminate the ribbon controls for this add-in

Requirements

Header: xllplus.h

See Also

CXllApp Class | xllplus.h | CXllFn object


CXllApp::AddFn

Add a function to the list of functions to be registered

BOOL AddFn(
   CXllFn* pfn
);

Parameters

pfn

Pointer an initialised function definition.

Return Value

Returns TRUE if the call succeeds, and FALSE if it fails for any reason.

Remarks

Adds the defined function to the list of functions that will be registered when RegisterFunctions() is called during the OnXllOpenEx() event.

This function should only be used before RegisterFunctions() is called, preferably during the OnXllOpenEx() event handler.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::RemoveFn() | CXllApp::FindFn()


CXllApp::AddStaticFns

Adds the XLL's functions to the global list of Excel add-in functions to be registered

int AddStaticFns( );

Return Value

Returns the number of functions collected.

Remarks

Collects all XLLFN structures that have been declared with the macros IMPLEMENT_XLLFN_EX, IMPLEMENT_XLLFN and IMPLEMENT_XLLFN2 and adds them to the CXllApp object's function map.

This function must be called by the InitInstance() virtual function. In the skeleton code written by the XLL Plus AppWizard, it is.

Note that this function does not actually register the add-in functions with Excel. This is delayed until the XllLoad event, which is called by Excel when the XLL is loaded.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::InitInstance() | CXllApp::PrefixFunctions()


CXllApp::AfterCalculateEvent

Gets a reference to the AfterCalculate event

CXlAfterCalculateEvent& AfterCalculateEvent( );

Return Value

The function returns a reference to the application's AfterCalculate event, which is of type CXlAfterCalculateEvent.

Remarks

The AfterCalculate event is raised after one or more worksheets have been calculated. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlAfterCalculateEventArgs is passed.

Availability

Note that this event is only available when running under Excel 2010 (Excel 14) or above.

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlAfterCalculateEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::AfterXllOpen

Called by the framework when Excel opens the XLL, after all other processing is complete.

virtual void AfterXllOpen( );

Remarks

This function is called whenever a user loads the add-in, whether using the Excel Tools - Add-ins dialog or directly, using the File - Open menu option.

This is a good time to do any initialization that needs to follow all other initialization steps, in particular if you need to override normal behavior set up during the OnXllOpenEx() event, or any CXllOpenEvent handlers.

The default implementation of this function does nothing.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnXllOpen() | CXllApp::OnXllClose()


CXllApp::BeforeDoubleClickEvent

Gets a reference to the BeforeDoubleClick event

CXlBeforeDoubleClickEvent& BeforeDoubleClickEvent( );

Return Value

The function returns a reference to the application's BeforeDoubleClick event, which is of type CXlBeforeDoubleClickEvent.

Remarks

The BeforeDoubleClick event is raised when the user double-clicks in a worksheet. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlCancellableRangeEventArgs is passed. Observers can cancel normal processing of the double-click by cancelling the event using CXlCancellableRangeEventArgs::SetCancel(false).

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlBeforeDoubleClickEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::BeforeRightClickEvent

Gets a reference to the BeforeRightClick event

CXlBeforeRightClickEvent& BeforeRightClickEvent( );

Return Value

The function returns a reference to the application's BeforeRightClick event, which is of type CXlBeforeRightClickEvent.

Remarks

The BeforeRightClick event is raised when the user right-clicks in a worksheet. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlCancellableRangeEventArgs is passed. Observers can cancel normal processing of the right-click by cancelling the event using CXlCancellableRangeEventArgs::SetCancel(false).

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlBeforeRightClickEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::CalculateEvent

Gets a reference to the Calculate event

CXlCalculateEvent& CalculateEvent( );

Return Value

The function returns a reference to the application's Calculate event, which is of type CXlCalculateEvent.

Remarks

The Calculate event is raised after a worksheet is calculated. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlWorksheetEventArgs is passed.

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlCalculateEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::CancelUserAbort

Cancels pending abort request

static BOOL CancelUserAbort( );

Return Value

This method should be called if, after GetUserAbort() returns TRUE, the user decides not to cancel the operation.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetUserAbort


CXllApp::ClearBinaryName

Clear a binary name from a worksheet

static BOOL ClearBinaryName(
   const TCHAR* pszName
);
static BOOL ClearBinaryName(
   const TCHAR* pszWorkbook,
   const TCHAR* pszWorksheet,
   const TCHAR* pszName
);

Parameters

pszName

The name of the invisible range to add to the worksheet. The name must conform to Excel range name rules.
pszWorkbook

Name of target workbook.
pszWorksheet

Name of target sheet.
pszName

Return Value

The function returns TRUE if the name is deleted (or if it does not exist), or FALSE if the operation fails.

Remarks

Binary names are invisible Excel named ranges, accessible only to the add-in programmer, not to the user. They differ from visible ranges in that you cannot us them for Excel data types, only for buffers of binary data.

Binary names are held in worksheets, and are unique at worksheet level. However, there may be multiple instances of a binary name in a workbook (as many as there are worksheets in the book).

The first form of the function acts on the active sheet of the active workbook.

The second form acts on the requested sheet. In order to do so, the active workbook and sheet are changed if required, and then changed back again after the action is complete.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::DefineBinaryName() | CXllApp::GetBinaryName()


CXllApp::ClearBinaryNameA

Clear a binary name from a worksheet

static BOOL ClearBinaryNameA(
   const char* pszName
);
static BOOL ClearBinaryNameA(
   const char* pszWorkbook,
   const char* pszWorksheet,
   const char* pszName
);

Parameters

pszName

The name of the invisible range to add to the worksheet. The name must conform to Excel range name rules.
pszWorkbook

Name of target workbook.
pszWorksheet

Name of target sheet.

Return Value

The function returns TRUE if the name is deleted (or if it does not exist), or FALSE if the operation fails.

Remarks

Binary names are invisible Excel named ranges, accessible only to the add-in programmer, not to the user. They differ from visible ranges in that you cannot us them for Excel data types, only for buffers of binary data.

Binary names are held in worksheets, and are unique at worksheet level. However, there may be multiple instances of a binary name in a workbook (as many as there are worksheets in the book).

The first form of the function acts on the active sheet of the active workbook.

The second form acts on the requested sheet. In order to do so, the active workbook and sheet are changed if required, and then changed back again after the action is complete.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::DefineBinaryName() | CXllApp::GetBinaryName()


CXllApp::ClearBinaryNameW

Clear a binary name from a worksheet

static BOOL ClearBinaryNameW(
   const wchar_t* pszName
);
static BOOL ClearBinaryNameW(
   const wchar_t* pszWorkbook,
   const wchar_t* pszWorksheet,
   const wchar_t* pszName
);

Parameters

pszName

The name of the invisible range to add to the worksheet. The name must conform to Excel range name rules.
pszWorkbook

Name of target workbook.
pszWorksheet

Name of target sheet.

Return Value

The function returns TRUE if the name is deleted (or if it does not exist), or FALSE if the operation fails.

Remarks

Binary names are invisible Excel named ranges, accessible only to the add-in programmer, not to the user. They differ from visible ranges in that you cannot us them for Excel data types, only for buffers of binary data.

Binary names are held in worksheets, and are unique at worksheet level. However, there may be multiple instances of a binary name in a workbook (as many as there are worksheets in the book).

The first form of the function acts on the active sheet of the active workbook.

The second form acts on the requested sheet. In order to do so, the active workbook and sheet are changed if required, and then changed back again after the action is complete.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::DefineBinaryName() | CXllApp::GetBinaryName()


CXllApp::ClrExceptionToText

Converts a CLR Exception to an error message.

static CString ClrExceptionToText(
   System::Exception^ ex
);

Parameters

ex

A handle to the CLR System::Exception object which was thrown during the execution of the add-in function.

Return Value

A string containing a summary of the error, formed by taking ex->Message and replacing carriage returns and line feeds with spaces.

Remarks

This function is called within the macro XLP_CATCH_CLR_EXCEPTIONS, in CLR builds only.

Availability

The function is available only under CLR builds.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::ConvertTypeToError

Translates exception types to standard Excel error values

static bool ConvertTypeToError(
   const XlExceptionTranslation* translations,
   CXlOper& xloResult,
   const CXlRuntimeException& ex
);

Parameters

translations

An array of translation elements, each of which will translate an error of a particular type to a chosen Excel error value. Each element of the array should be defined using the XLEXCEPTION_TRANSLATION macro. The array must end with an empty element, XLEXCEPTION_TRANSLATION_END.

xloResult

This value will be set to contain the result which will be displayed in Excel.

ex

A reference to the exception which was thrown and caught, and which is to be represented in xloResult.

Remarks

The macros XLEXCEPTION_TRANSLATION and XLEXCEPTION_TRANSLATION_END should be used to build the translations argument.

See Overriding exception-handling behavior in the User Guide for more information about this method.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::DisplayException | Overriding exception-handling behavior


CXllApp::CXllApp

Constructs a CXllApp object

CXllApp(
   LPCTSTR lpszAppName = NULL
);

Parameters

lpszAppName

A null-terminated string that contains the application name that Windows uses. If this argument is not supplied or is NULL, CWinApp uses the resource string AFX_IDS_APP_TITLE or the filename of the executable file.

Remarks

Constructs a CXllApp object and passes lpszAppName to be stored as the application name. You should construct one global object of your CXllApp-derived class. You can have only one CXllApp object in your application. The constructor stores a pointer to the CXllApp object so that WinMain can call the object's member functions to initialize and run the application.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::DefineBinaryName

Define a binary name in a worksheet and assign a block of data to it

static BOOL DefineBinaryName(
   const TCHAR* pszName,
   void* pData,
   size_t cbData
);
static BOOL DefineBinaryName(
   const TCHAR* pszWorkbook,
   const TCHAR* pszWorksheet,
   const TCHAR* pszName,
   void* pData,
   size_t cbData
);

Parameters

pszName

The name of the invisible range to add to the worksheet. The name must conform to Excel range name rules.
pData

A pointer to the data buffer containing the data which will be assigned to the BinaryName.
cbData

The number of bytes in the data buffer.
pszWorkbook

Name of target workbook.
pszWorksheet

Name of target sheet.
pszName
pData
cbData

Return Value

The function returns TRUE if the name is defined successfully, or FALSE if the operation fails.

Remarks

Binary names are invisible Excel named ranges, accessible only to the add-in programmer, not to the user. They differ from visible ranges in that you cannot us them for Excel data types, only for buffers of binary data.

Binary names are held in worksheets, and are unique at worksheet level. However, there may be multiple instances of a binary name in a workbook (as many as there are worksheets in the book).

The first form of the function acts on the active sheet of the active workbook.

The second form acts on the requested sheet. In order to do so, the active workbook and sheet are changed if required, and then changed back again after the action is complete.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::ClearBinaryName() | CXllApp::GetBinaryName()


CXllApp::DefineBinaryNameA

Define a binary name in a worksheet and assign a block of data to it

static BOOL DefineBinaryNameA(
   const char* pszName,
   void* pData,
   size_t cbData
);
static BOOL DefineBinaryNameA(
   const char* pszWorkbook,
   const char* pszWorksheet,
   const char* pszName,
   void* pData,
   size_t cbData
);

Parameters

pszName

The name of the invisible range to add to the worksheet. The name must conform to Excel range name rules.
pData

A pointer to the data buffer containing the data which will be assigned to the BinaryName.
cbData

The number of bytes in the data buffer.
pszWorkbook

Name of target workbook.
pszWorksheet

Name of target sheet.

Return Value

The function returns TRUE if the name is defined successfully, or FALSE if the operation fails.

Remarks

Binary names are invisible Excel named ranges, accessible only to the add-in programmer, not to the user. They differ from visible ranges in that you cannot us them for Excel data types, only for buffers of binary data.

Binary names are held in worksheets, and are unique at worksheet level. However, there may be multiple instances of a binary name in a workbook (as many as there are worksheets in the book).

The first form of the function acts on the active sheet of the active workbook.

The second form acts on the requested sheet. In order to do so, the active workbook and sheet are changed if required, and then changed back again after the action is complete.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::ClearBinaryName() | CXllApp::GetBinaryName()


CXllApp::DefineBinaryNameW

Define a binary name in a worksheet and assign a block of data to it

static BOOL DefineBinaryNameW(
   const wchar_t* pszName,
   void* pData,
   size_t cbData
);
static BOOL DefineBinaryNameW(
   const wchar_t* pszWorkbook,
   const wchar_t* pszWorksheet,
   const wchar_t* pszName,
   void* pData,
   size_t cbData
);

Parameters

pszName

The name of the invisible range to add to the worksheet. The name must conform to Excel range name rules.
pData

A pointer to the data buffer containing the data which will be assigned to the BinaryName.
cbData

The number of bytes in the data buffer.
pszWorkbook

Name of target workbook.
pszWorksheet

Name of target sheet.

Return Value

The function returns TRUE if the name is defined successfully, or FALSE if the operation fails.

Remarks

Binary names are invisible Excel named ranges, accessible only to the add-in programmer, not to the user. They differ from visible ranges in that you cannot us them for Excel data types, only for buffers of binary data.

Binary names are held in worksheets, and are unique at worksheet level. However, there may be multiple instances of a binary name in a workbook (as many as there are worksheets in the book).

The first form of the function acts on the active sheet of the active workbook.

The second form acts on the requested sheet. In order to do so, the active workbook and sheet are changed if required, and then changed back again after the action is complete.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::ClearBinaryName() | CXllApp::GetBinaryName()


CXllApp::DisplayException

Called by wrapper functions to translate caught exceptions to error messages

virtual void DisplayException(
   CXlOper& xloResult,
   const CXlRuntimeException& ex
);

Parameters

xloResult

This value should be set to contain the result which will be displayed in Excel.

ex

A reference to the exception which was thrown and caught, and which is to be represented in xloResult.

Remarks

This method is called by wrapper functions when an exception of type CXlRuntimeException is thrown by an add-in function.

You can override it to change the standard exception-handling behavior of your add-in.

The default implementation of this function sets xloResult to contain the error message prefixed by "#ERROR: ", e.g.:

CopyC++
#ERROR: Expected number for Series[4]

See Overriding exception-handling behavior in the User Guide for more information.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::ConvertTypeToError | Overriding exception-handling behavior


CXllApp::ErrorToString

Convert an error value to a string.

static const TCHAR* ErrorToString(
   unsigned short err
);

Parameters

err

An error value (e.g. xlerrValue).

Return Value

A pointer to a static string buffer containg the string value of the error, as it would be displayed in Excel, e.g.: #N/A!, #DIV/0! etc.

Remarks

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. It is not therefore necessary to fix the MFC CWinApp instance using the XLL_FIX_STATE macro: you can use code such as:

CString strResult = CXllApp::ErrorToString(xlerrValue);

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::ErrorToStringA

Convert an error value to a string.

static const char* ErrorToStringA(
   unsigned short err
);

Parameters

err

An error value (e.g. xlerrValue).

Return Value

A pointer to a static string buffer containg the string value of the error, as it would be displayed in Excel, e.g.: #N/A!, #DIV/0! etc.

Remarks

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. It is not therefore necessary to fix the MFC CWinApp instance using the XLL_FIX_STATE macro: you can use code such as:

CString strResult = CXllApp::ErrorToString(xlerrValue);

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::ErrorToStringW

Convert an error value to a string.

static const wchar_t* ErrorToStringW(
   unsigned short err
);

Parameters

err

An error value (e.g. xlerrValue).

Return Value

A pointer to a static string buffer containg the string value of the error, as it would be displayed in Excel, e.g.: #N/A!, #DIV/0! etc.

Remarks

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. It is not therefore necessary to fix the MFC CWinApp instance using the XLL_FIX_STATE macro: you can use code such as:

CString strResult = CXllApp::ErrorToString(xlerrValue);

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::Excel

Invoke the Excel SDK

static int cdecl Excel(
   int xlfn,
   int count,
   const CXlOper* arg0,
    ...
);
static int cdecl Excel(
   int xlfn
);
static int cdecl Excel(
   int xlfn,
   int count0
);

Parameters

xlfn

The Excel built-in function number. See Excel built-in function numbers for a list of values.

count

The number of XLOPER pointer arguments being passed to Excel.
arg0

The first argument to the function.
...

The remaining count-1 arguments (if any) to the function should also be const pointers to CXlOper.
count0

The number of XLOPER pointer arguments being passed to Excel. For this variant of Excel(), this value should always be 0.

Return Value

The result of the SDK call-back. xlretSuccess (0) indicates success. Other values indicate failure. A full list of return values can be found under Error Values.

Remarks

This function can be used to call an Excel built-in function via the Microsoft Excel SDK. Details of SDK calls and their arguments can be found in the Microsoft Excel 4 Function Reference.

This function should not be used if you have any interest in the value returned by the callback function. To receive a return value, use CXlOper::Excel(), which places the result in the calling CXlOper object.

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. You can use code such as:

    CXlOper xloBarNum;
    xloBarNum.ToInt(2);
    CXllApp::Excel(xlfDeleteToolbar, 1, xloBarNum);

CXlFuncs & CXlMacros

Most Excel worksheet and macro functions can be found, as ready-wrapped C++ methods, in the CXlFuncs and CXlMacros classes respectively.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXlOper::Excel | Error Values | CXlFuncs class | CXlMacros class | Excel built-in function numbers | Calling an Excel built-in function from your add-in


CXllApp::ExitInstance

Called by the framework when the XLL is unloaded from memory

virtual int ExitInstance( );

Return Value

0 if the function completes successfully; non-zero otherwise.

Remarks

This method is called whenever the XLL is finally unloaded from memory. Note that this can occur not only when Excel is closed, but also whenever the XLL is examined in Excel's Tools/AddIns dialog.

Final termination tasks can be done here. If the method is used, then it must call the base class method CXllApp::ExitInstance().

In general it is better to place all termination code in CXllApp::OnXllClose.

MFC considerations

In the MFC builds, CXllApp is descended from CWinApp. Calling the base class ExitInstance ensures that the MFC implementation is properly cleaned up.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::InitInstance() | CXllApp::OnXllClose()


CXllApp::FindFn

Find a function in the function list

CXllFn* FindFn(
   LPCTSTR pszFnName
);

Parameters

pszFnName

Pointer to a null-terminated string containing the exported name of the function (i.e. the name visible in Excel).

Return Value

Returns a pointer to the function if found, and NULL if it cannot be found.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::AddFn() | CXllApp::RemoveFn()


CXllApp::FindFnA

Find a function in the function list

CXllFn* FindFnA(
   LPCSTR pszFnName
);

Parameters

pszFnName

Pointer to a null-terminated string containing the exported name of the function (i.e. the name visible in Excel).

Return Value

Returns a pointer to the function if found, and NULL if it cannot be found.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::AddFn() | CXllApp::RemoveFn()


CXllApp::FindFnW

Find a function in the function list

CXllFn* FindFnW(
   LPCWSTR pszFnName
);

Parameters

pszFnName

Pointer to a null-terminated string containing the exported name of the function (i.e. the name visible in Excel).

Return Value

Returns a pointer to the function if found, and NULL if it cannot be found.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::AddFn() | CXllApp::RemoveFn()


CXllApp::GetAllFns

Get all functions in the function list

size_t GetAllFns(
   std::vector<CXllFn*>& fns
);

Parameters

fns

This vector will be populated with the set of all add-in functions that are registered by the application (or that are due to be registered later).

Return Value

Returns the number of functions in the list.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetApplicationDispatch

Returns a dispatch pointer to the Excel Application object

LPDISPATCH GetApplicationDispatch( );

Return Value

Returns an IDispatch interface pointer to the Excel Application object. If the COM interface cannot be initialized, then an exception of type CXlComException will be thrown.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetCom() | CXllApp::SetUseAutomation()


CXllApp::GetApplicationObject

Returns a .NET object containing a handle to the Excel.Application COM object.

static System::Object^ GetApplicationObject( );

Return Value

A .NET object which can be used by CLR code to access the Excel automation object, Excel.Application.

Remarks

A .NET method that receives this object can cast it to a handle to an _Application interface as in the following C# code.

using Microsoft.Office.Interop.Excel;
...
_Application app = appObj as _Application;

You must ensure that your add-in (or the assembly to which the value is passed) has a reference to the Excel Primary Interop Assembly.

Availability

The function is available only under CLR builds.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetBinaryName

Retrieve a binary name from a worksheet

static BOOL GetBinaryName(
   const TCHAR* pszName,
   CXlBinaryNameData& data
);
static BOOL GetBinaryName(
   const TCHAR* pszWorkbook,
   const TCHAR* pszWorksheet,
   const TCHAR* pszName,
   CXlBinaryNameData& data
);

Parameters

pszName

The name of the invisible range in the worksheet. The name must conform to Excel range name rules.
data

A reference to a data holder which will be set to point to the binary data associated with the name, if the function is successful.

pszWorkbook

Name of target workbook.
pszWorksheet

Name of target sheet.
pszName
data

Return Value

The function returns TRUE if the name is found and the data is successfully retrieved, or FALSE if the name does not exist or contains no data.

CXlBinaryNameData

The data is retrieved into a CXlBinaryNameData object in order to be sure that it is locked and unlocked properly. Excel stores BinaryName data in Windows global moveable memory blocks, and the CXlBinaryNameData object ensures that the GlobalFree() method is called when the data holder goes out of scope.

You should use the CXlBinaryNameData accessor methods to access the data block: CXlBinaryNameData::GetCount and CXlBinaryNameData::GetData.

Remarks

Binary names are invisible Excel named ranges, accessible only to the add-in programmer, not to the user. They differ from visible ranges in that you cannot us them for Excel data types, only for buffers of binary data.

Binary names are held in worksheets, and are unique at worksheet level. However, there may be multiple instances of a binary name in a workbook (as many as there are worksheets in the book).

The first form of the function acts on the active sheet of the active workbook.

The second form acts on the requested sheet. In order to do so, the active workbook and sheet are changed if required, and then changed back again after the action is complete.

Example

BinaryName data can be added to the active worksheet and retrieved using code like the following:

CopyC++
// Set data
double adValues[2] = { 1.0, 2.0 };
BOOL ok = CXllApp::DefineBinaryName("value_pair", (void*)adValues, sizeof(adValues));

// Retrieve data
CXlBinaryNameData data;
ok = CXllApp::GetBinaryName("value_pair", data);
if (ok && data.GetCount() == sizeof(adValues))
{
    memcpy(adValues, data.GetData(), sizeof(adValues));
}

Excel 2010

There is a known problem with Excel 2010 as of SP0. The function xlGetBinaryName always fails to find the requested name. As a result, CXllApp::GetBinaryName() always fails. This bug is fixed in Microsoft's hotfix 2459118. More information can be found at http://support.microsoft.com/kb/2459118.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::DefineBinaryName() | CXllApp::ClearBinaryName() | CXlBinaryNameData object


CXllApp::GetBinaryNameA

Retrieve a binary name from a worksheet

static BOOL GetBinaryNameA(
   const char* pszName,
   CXlBinaryNameData& data
);
static BOOL GetBinaryNameA(
   const char* pszWorkbook,
   const char* pszWorksheet,
   const char* pszName,
   CXlBinaryNameData& data
);

Parameters

pszName

The name of the invisible range in the worksheet. The name must conform to Excel range name rules.
data

A reference to a data holder which will be set to point to the binary data associated with the name, if the function is successful.

pszWorkbook

Name of target workbook.
pszWorksheet

Name of target sheet.

Return Value

The function returns TRUE if the name is found and the data is successfully retrieved, or FALSE if the name does not exist or contains no data.

CXlBinaryNameData

The data is retrieved into a CXlBinaryNameData object in order to be sure that it is locked and unlocked properly. Excel stores BinaryName data in Windows global moveable memory blocks, and the CXlBinaryNameData object ensures that the GlobalFree() method is called when the data holder goes out of scope.

You should use the CXlBinaryNameData accessor methods to access the data block: CXlBinaryNameData::GetCount and CXlBinaryNameData::GetData.

Remarks

Binary names are invisible Excel named ranges, accessible only to the add-in programmer, not to the user. They differ from visible ranges in that you cannot us them for Excel data types, only for buffers of binary data.

Binary names are held in worksheets, and are unique at worksheet level. However, there may be multiple instances of a binary name in a workbook (as many as there are worksheets in the book).

The first form of the function acts on the active sheet of the active workbook.

The second form acts on the requested sheet. In order to do so, the active workbook and sheet are changed if required, and then changed back again after the action is complete.

Example

BinaryName data can be added to the active worksheet and retrieved using code like the following:

CopyC++
// Set data
double adValues[2] = { 1.0, 2.0 };
BOOL ok = CXllApp::DefineBinaryName("value_pair", (void*)adValues, sizeof(adValues));

// Retrieve data
CXlBinaryNameData data;
ok = CXllApp::GetBinaryName("value_pair", data);
if (ok && data.GetCount() == sizeof(adValues))
{
    memcpy(adValues, data.GetData(), sizeof(adValues));
}

Excel 2010

There is a known problem with Excel 2010 as of SP0. The function xlGetBinaryName always fails to find the requested name. As a result, CXllApp::GetBinaryName() always fails. This bug is fixed in Microsoft's hotfix 2459118. More information can be found at http://support.microsoft.com/kb/2459118.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::DefineBinaryName() | CXllApp::ClearBinaryName() | CXlBinaryNameData object


CXllApp::GetBinaryNameW

Retrieve a binary name from a worksheet

static BOOL GetBinaryNameW(
   const wchar_t* pszName,
   CXlBinaryNameData& data
);
static BOOL GetBinaryNameW(
   const wchar_t* pszWorkbook,
   const wchar_t* pszWorksheet,
   const wchar_t* pszName,
   CXlBinaryNameData& data
);

Parameters

pszName

The name of the invisible range in the worksheet. The name must conform to Excel range name rules.
data

A reference to a data holder which will be set to point to the binary data associated with the name, if the function is successful.

pszWorkbook

Name of target workbook.
pszWorksheet

Name of target sheet.

Return Value

The function returns TRUE if the name is found and the data is successfully retrieved, or FALSE if the name does not exist or contains no data.

CXlBinaryNameData

The data is retrieved into a CXlBinaryNameData object in order to be sure that it is locked and unlocked properly. Excel stores BinaryName data in Windows global moveable memory blocks, and the CXlBinaryNameData object ensures that the GlobalFree() method is called when the data holder goes out of scope.

You should use the CXlBinaryNameData accessor methods to access the data block: CXlBinaryNameData::GetCount and CXlBinaryNameData::GetData.

Remarks

Binary names are invisible Excel named ranges, accessible only to the add-in programmer, not to the user. They differ from visible ranges in that you cannot us them for Excel data types, only for buffers of binary data.

Binary names are held in worksheets, and are unique at worksheet level. However, there may be multiple instances of a binary name in a workbook (as many as there are worksheets in the book).

The first form of the function acts on the active sheet of the active workbook.

The second form acts on the requested sheet. In order to do so, the active workbook and sheet are changed if required, and then changed back again after the action is complete.

Example

BinaryName data can be added to the active worksheet and retrieved using code like the following:

CopyC++
// Set data
double adValues[2] = { 1.0, 2.0 };
BOOL ok = CXllApp::DefineBinaryName("value_pair", (void*)adValues, sizeof(adValues));

// Retrieve data
CXlBinaryNameData data;
ok = CXllApp::GetBinaryName("value_pair", data);
if (ok && data.GetCount() == sizeof(adValues))
{
    memcpy(adValues, data.GetData(), sizeof(adValues));
}

Excel 2010

There is a known problem with Excel 2010 as of SP0. The function xlGetBinaryName always fails to find the requested name. As a result, CXllApp::GetBinaryName() always fails. This bug is fixed in Microsoft's hotfix 2459118. More information can be found at http://support.microsoft.com/kb/2459118.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::DefineBinaryName() | CXllApp::ClearBinaryName() | CXlBinaryNameData object


CXllApp::GetCalculationMode

Get Excel's calculation mode

static int GetCalculationMode( );

Return Value

The function returns a number from 1 to 3 indicating the type of calculation:- 1=Automatic; 2=Automatic except tables; 3=Manual.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::SetCalculationMode


CXllApp::GetCallerDims

Get the dimensions of the range from which this add-in function was called

static bool GetCallerDims(
   size_t& nRows,
   size_t& nColumns
);
static bool GetCallerDims(
   RW12& nRows,
   COL12& nColumns
);
static BOOL GetCallerDims(
   USHORT& usRows,
   USHORT& usColumns
); [Deprecated]

Parameters

nRows

If the function succeeds this will be set to the number of rows in the range from which this function was called.

nColumns

If the function succeeds this will be set to the number of columns in the range from which this function was called.

usRows

If the function succeeds this will be set to the number of rows in the range from which this function was called. The function will fail if there are more rows in the range can be held in a USHORT variable.
usColumns

If the function succeeds this will be set to the number of columns in the range from which this function was called.

Return Value

Returns TRUE if the function was called from a cell range, and sets the values of usRows and usColumns. Returns FALSE if the function was called from a macro.

Example

CXlOper::GetCallerDims() Example

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXlOper::GetCaller | CXlOper::GetDims


CXllApp::GetColumnPrefix

Return the character used for columns in R1C1 format

TCHAR GetColumnPrefix( ) const;

Return Value

Returns the character used to prefix column values in R1C1 format, in the language that was set when Excel was started.

In English, the function returns upper-case 'C'.

Remarks

If the user language is changed while Excel is running, the character returned by this call may no longer be valid. The character is set during the XllOpen event, and is cached in the CXllApp object for its lifetime.

Note that this function can be used during worksheet functions, but CXllApp::GetInternational, which returns an up-to-date value, cannot be called during worksheet functions.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetCom

Returns a dispatch pointer to the COM interface instance

CXllCom* GetCom( );

Return Value

Returns a pointer to the COM interface instance. If the COM interface cannot be initialized, then an exception of type CXlComException will be thrown.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllCom object | CXllApp::GetApplicationDispatch() | CXllApp::SetUseAutomation()


CXllApp::GetComEventHandler

Returns the name of an add-in function to handle a specific COM event

CString GetComEventHandler(
   int nEvent
) const;

Parameters

nEvent

An integer representing the event to be handled. See Remarks below for a list of values.

Return Value

Returns the name of an add-in function to handle a specific COM event. The return string will be empty if no handler has been set.

Remarks

This function returns the name of an add-in function that will be called whenever the specified COM event occurs.

If it is set to the name of an add-in function with the appproriate signature, the function will be called. If the function name is set to an empty string then no special event handling will occur.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::SetComEventHandler()


CXllApp::GetDllName

Called by the framework to get the name of the DLL containing the add-in functions when they are registered

virtual std::tstring GetDllName( );

Remarks

This method is called whenever the functions contained in a DLL are registered with Excel as add-in functions.

You can use it to override the name provided to Excel, when the XLL containing the functions has been loaded by a boot-strap XLL.

The default implementation of this function returns the name of the XLL loaded by Excel (whether using the Excel Tools - Add-ins dialog or directly, using the File - Open menu option).

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetFnCount

Get a count of the add-in functions in the library

int GetFnCount( );

Return Value

A count of the number of add-in functions contained in the library.

Example

CXllApp::GetNextFnAssoc() Example

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetStartFnPosition() | CXllApp::GetNextFnAssoc()


CXllApp::GetHasRibbon

Returns whether the application has a ribbon

bool GetHasRibbon( );

Return Value

Returns true if the add-in has been instructed to supply a ribbon.

Remarks

By default, an application class will not have a ribbon. Only if SetRibbonImplementation and SetHasRibbon have been called will the application support a ribbon.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetHideArgumentBoxForNoArgs

Get the value of the property that controls the behavior of the Excel Formula Wizard for functions with no arguments

bool GetHideArgumentBoxForNoArgs( );

Return Value

Returns the current value of the property.

If the value is true, then the extra argument box that appears in the Excel Formula Wizard for functions which in fact have no arguments will be suppressed. As a side-effect, the help text for the function will not appear.

If the value is false, then the extra argument box will continue to appear. However, the help text for the function will appear.

Remarks

There is a problem with the Excel Formula Wizard when displaying functions that have no arguments. Either the Wizard displays an argument box for a non-existent argument, or the help text for the function is not displayed.

The table below shows the behavior of the Wizard when displaying a zero-argument function, for different return values of GetHideArgumentBoxForNoArgs().

Value | Argument box | Function help text
true | Not displayed (good) | Not displayed (bad)
false | Displayed (bad) | Displayed (good)

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::SetHideArgumentBoxForNoArgs()


CXllApp::GetInternational

Returns information about the current country and international settings.

static BOOL GetInternational(
   int index,
   CXlOper& xloResult
);

Parameters

index

A member of enumeration XlInternationalEnum (see XllPlus.h). You can find a description of the types of information available in the Excel VBA help for Application.International. Note that C++ values are 1 less than the values shown in the VBA documentation.
xloResult

If the method succeeds, the result will be placed in here. The result will be of various different types, depending on the value of index.

Return Value

Returns TRUE if the method succeeds, FALSE if it fails.

Remarks

This function can only be called from macro functions, or from worksheet functions that have been marked as "Defer recalculation". It will always fail if called from worksheet functions that have not been marked as "Defer recalculation".

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | International sample


CXllApp::GetLibraryVersion

Return the XLL+ run-time library version.

static unsigned long GetLibraryVersion( );

Return Value

Returns the value of XLLPLUS_VERSION_NUMERIC (defined in xlpdefs.h) against which the run-time library was built.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetListSeparator

Return the character used for separating arguments

TCHAR GetListSeparator( ) const;

Return Value

Returns the character used to separate arguments in Excel formulae, in the language that was set when Excel was started.

Remarks

If the user language is changed while Excel is running, the character returned by this call may no longer be valid. The character is set during the XllOpen event, and is cached in the CXllApp object for its lifetime.

Note that this function can be used during worksheet functions, but CXllApp::GetInternational, which returns an up-to-date value, cannot be called during worksheet functions.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetNextFnAssoc

Iterate the function map

void GetNextFnAssoc(
   CXllApp::POSITION rNextPosition,
   CString rKey,
   CXllFn*& rpfn
);

Parameters

rNextPosition

Specifies a reference to a CXllApp::POSITION value returned by a previous GetNextFnAssoc or GetStartFnPosition call.
rKey

Specifies the returned key of the retrieved element.
rpfn

Specifies the returned value of the retrieved element.

Remarks

Retrieves the map element at rNextPosition, then updates rNextPosition to refer to the next element in the map. This function is most useful for iterating through all the elements in the map. Note that the position sequence is not necessarily the same as the key value sequence.

If the retrieved element is the last in the map, then the new value of rNextPosition is set to NULL.

Note Note:

This method is deprecated.

Example

CXllApp::GetNextFnAssoc() Example

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetStartFnPosition()


CXllApp::GetNextFnAssocA

Iterate the function map

void GetNextFnAssocA(
   CXllApp::POSITION rNextPosition,
   CStringA rKey,
   CXllFn*& rpfn
);

Parameters

rNextPosition

Specifies a reference to a CXllApp::POSITION value returned by a previous GetNextFnAssoc or GetStartFnPosition call.
rKey

Specifies the returned key of the retrieved element.
rpfn

Specifies the returned value of the retrieved element.

Remarks

Retrieves the map element at rNextPosition, then updates rNextPosition to refer to the next element in the map. This function is most useful for iterating through all the elements in the map. Note that the position sequence is not necessarily the same as the key value sequence.

If the retrieved element is the last in the map, then the new value of rNextPosition is set to NULL.

Note Note:

This method is deprecated.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetStartFnPosition()


CXllApp::GetNextFnAssocW

Iterate the function map

void GetNextFnAssocW(
   CXllApp::POSITION rNextPosition,
   CStringW rKey,
   CXllFn*& rpfn
);

Parameters

rNextPosition

Specifies a reference to a CXllApp::POSITION value returned by a previous GetNextFnAssoc or GetStartFnPosition call.
rKey

Specifies the returned key of the retrieved element.
rpfn

Specifies the returned value of the retrieved element.

Remarks

Retrieves the map element at rNextPosition, then updates rNextPosition to refer to the next element in the map. This function is most useful for iterating through all the elements in the map. Note that the position sequence is not necessarily the same as the key value sequence.

If the retrieved element is the last in the map, then the new value of rNextPosition is set to NULL.

Note Note:

This method is deprecated.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetStartFnPosition()


CXllApp::GetNumericToStringConversionMethod

Return the value of the NumericToStringConversionMethod flag.

static int GetNumericToStringConversionMethod( );

Return Value

An integer value indicating the method used for Numeric to String conversion. If the value is 1, then the XLL+ framework is set to use the method of XLL+ 5 (and earlier versions), offering increased accuracy (because Excel handles the conversion). If the value is 0, then the framework is using the method of XLL+ 6 and above, which is faster but less accurate.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::SetNumericToStringConversionMethod()


CXllApp::GetObserverFunctionName

Return the name of the add-in function that observes COM events.

CStringW GetObserverFunctionName( );

Return Value

A string containing the name - as exported to Excel - of the add-in function that observes COM events and routes them to the add-in's event handlers.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetPrivateBinPath

Gets the private path used by the .NET Assembly loader.

CString GetPrivateBinPath( );

Return Value

A string containing a list of directories, separated by semi-colons. If the function failed, the string will be empty.

Remarks

By default, this path contains a single directory - the directory that contains the XLL. If your .NET assembly files are located in the same directory as the XLL, then there is no need to change the value of the private bin path.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::SetPrivateBinPath()


CXllApp::GetRegDllName

Called by the framework to get the name of the DLL containing the add-in functions when they are registered

virtual void GetRegDllName(
   CXlOper& xloDllName
);

Parameters

xloDllName

This value should be populated with the name of the XLL which actually contains the add-in functions.

Remarks

This method is called whenever the functions contained in a DLL are registered with Excel as add-in functions.

You can use it to override the name provided to Excel, when the XLL containing the functions has been loaded by a boot-strap XLL.

The default implementation of this function returns the name of the XLL loaded by Excel (whether using the Excel Tools - Add-ins dialog or directly, using the File - Open menu option).

Note Note:

This method is deprecated. Use GetDllName instead.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetRibbonCallbackFunctionName

Return the name of the add-in function that observes Ribbon events.

CStringW GetRibbonCallbackFunctionName( );

Return Value

A string containing the name - as exported to Excel - of the add-in function that observes Ribbon events and routes them to the add-in's ribbon event handlers.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetRowPrefix

Return the character used for rows in R1C1 format

TCHAR GetRowPrefix( ) const;

Return Value

Returns the character used to prefix row values in R1C1 format, in the language that was set when Excel was started.

In English, the function returns upper-case 'R'.

Remarks

If the user language is changed while Excel is running, the character returned by this call may no longer be valid. The character is set during the XllOpen event, and is cached in the CXllApp object for its lifetime.

Note that this function can be used during worksheet functions, but CXllApp::GetInternational, which returns an up-to-date value, cannot be called during worksheet functions.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetRtdAsyncManager

Return a pointer to the RTD asynchronous function manager.

CRtdAsyncManager* GetRtdAsyncManager(
   bool bCreateIfNull = true
);

Parameters

bCreateIfNull

If the singleton instance of CRtdAsyncManager has not yet been created, then it will be created on demand if bCreateIfNull is true. If bCreateIfNull is false, and the instance has not yet been created, then it will not be created at this time, and NULL will be returned.

Return Value

A pointer to the singleton instance of CRtdAsyncManager, or NULL if the instance has not yet been created and bCreateIfNull is false.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CRtdAsyncManager Class


CXllApp::GetSheetId

Get the sheet ID of a named sheet

static DWORD GetSheetId(
   const char* pszSheetName
);
static DWORD GetSheetId(
   const wchar_t* pszSheetName
);
static DWORD GetSheetId(
   const char* pszBook,
   const char* pszSheet
);
static DWORD GetSheetId(
   const wchar_t* pszBook,
   const wchar_t* pszSheet
);

Parameters

pszSheetName

The name of a sheet in "[book]sheet" format.
pszBook

The name of the workbook.
pszSheet

The name of the worksheet.

Return Value

The sheet ID of the named sheet if successful; 0 if the sheet cannot be found.

Remarks

This function can be used to get the sheet ID of a named sheet. This ID can be used to construct references to cells.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetSheetName

Get the name of sheet from its sheet ID

static CString GetSheetName(
   DWORD dwSheetId
);

Parameters

dwSheetId

The sheet ID. This can be extracted from references, using CXlOper::GetSheetId().

Return Value

The name of the sheet if successful, in "[book]sheet" format; an empty string if the sheet cannot be found.

Remarks

This function can be used to get the name of a sheet from its ID. The combined sheet name can be split using CXllApp::SplitSheetName().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::MakeSheetName() | CXllApp::SplitSheetName()


CXllApp::GetSheetNameA

Get the name of sheet from its sheet ID

static CStringA GetSheetNameA(
   DWORD dwSheetId
);

Parameters

dwSheetId

The sheet ID. This can be extracted from references, using CXlOper::GetSheetId().

Return Value

The name of the sheet if successful, in "[book]sheet" format; an empty string if the sheet cannot be found.

Remarks

This function can be used to get the name of a sheet from its ID. The combined sheet name can be split using CXllApp::SplitSheetName().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::MakeSheetName() | CXllApp::SplitSheetName()


CXllApp::GetSheetNameW

Get the name of sheet from its sheet ID

static CStringW GetSheetNameW(
   DWORD dwSheetId
);

Parameters

dwSheetId

The sheet ID. This can be extracted from references, using CXlOper::GetSheetId().

Return Value

The name of the sheet if successful, in "[book]sheet" format; an empty string if the sheet cannot be found.

Remarks

This function can be used to get the name of a sheet from its ID. The combined sheet name can be split using CXllApp::SplitSheetName().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::MakeSheetName() | CXllApp::SplitSheetName()


CXllApp::GetSinkEvents

Returns the state of the COM event handler

BOOL GetSinkEvents( ) const;

Return Value

Returns TRUE if COM events are being handled.

Remarks

This function returns the state of the COM event handler.

If it is set to TRUE, then the event handlers for COM events will be invoked whenever significant events occur in Excel.

You can specify event handlers by overloading the appropriate virtual function in your derived application class.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::SetSinkEvents()


CXllApp::GetStartFnPosition

Get the starting position for iterating the function map

CXllApp::POSITION GetStartFnPosition( );

Return Value

A CXllApp::POSITION value that indicates a starting position for iterating the function map; or NULL if the map is empty.

Remarks

Starts a map iteration by returning a CXllApp::POSITION value that can be passed to a GetNextFnAssoc call. The iteration sequence is not predictable; therefore, the "first element in the map" has no special significance.

Note Note:

This method is deprecated.

Example

CXllApp::GetNextFnAssoc() Example

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetNextFnAssoc()


CXllApp::GetUseAutomation

Returns the value of the UseAutomation attribute

BOOL GetUseAutomation( ) const;

Return Value

Returns the value of the UseAutomation attibute. If this attribute is set to TRUE, then the addin will get a handle to Excel's COM interface during initialization. If it is FALSE, then the COM interface will not be available to the add-in.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllCom object | CXllApp::GetApplicationDispatch() | CXllApp::SetUseAutomation()


CXllApp::GetUserAbort

Returns whether user has aborted operation

static BOOL GetUserAbort( );

Return Value

The function returns TRUE if the user has pressed the Cancel key (since this function was last called).

Remarks

Very slow functions should call this method periodically, and should immediately abort operations and return an error if it returns TRUE.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::CancelUserAbort


CXllApp::GetVersionInfo

Return the version info of the XLL, including version number, copyright and build information.

static CString GetVersionInfo(
   const TCHAR* pszItem
);

Parameters

pszItem

The name of the item of version information requested. This may be one of:

CompanyName
FileDescription
FileVersion
InternalName
LegalCopyright
LegalTrademarks
OriginalFilename
ProductName
ProductVersion

Return Value

A string containing the version information requested. If none was found, the string will be empty.

Remarks

This function returns an item from the version information built into the XLL. This is the same information you can see in the Properties dialog of NT Explorer.

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. You can use code such as:

CXlOper xloResult;
xloResult = CXllApp::GetVersionInfo("FileVersion");

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetVersionInfoA

Return the version info of the XLL, including version number, copyright and build information.

static CStringA GetVersionInfoA(
   const char* pszItem
);

Parameters

pszItem

The name of the item of version information requested. This may be one of:

CompanyName
FileDescription
FileVersion
InternalName
LegalCopyright
LegalTrademarks
OriginalFilename
ProductName
ProductVersion

Return Value

A string containing the version information requested. If none was found, the string will be empty.

Remarks

This function returns an item from the version information built into the XLL. This is the same information you can see in the Properties dialog of NT Explorer.

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. You can use code such as:

CXlOper xloResult;
xloResult = CXllApp::GetVersionInfo("FileVersion");

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetVersionInfoW

Return the version info of the XLL, including version number, copyright and build information.

static CStringW GetVersionInfoW(
   const wchar_t* pszItem
);

Parameters

pszItem

The name of the item of version information requested. This may be one of:

CompanyName
FileDescription
FileVersion
InternalName
LegalCopyright
LegalTrademarks
OriginalFilename
ProductName
ProductVersion

Return Value

A string containing the version information requested. If none was found, the string will be empty.

Remarks

This function returns an item from the version information built into the XLL. This is the same information you can see in the Properties dialog of NT Explorer.

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. You can use code such as:

CXlOper xloResult;
xloResult = CXllApp::GetVersionInfo("FileVersion");

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetXlAsyncManager

Return a pointer to the queued function manager.

CXlAsyncManager* GetXlAsyncManager(
   bool bCreateIfNull = true
);

Parameters

bCreateIfNull

If the singleton instance of CXlAsyncManager has not yet been created, then it will be created on demand if bCreateIfNull is true. If bCreateIfNull is false, and the instance has not yet been created, then it will not be created at this time, and NULL will be returned.

Return Value

A pointer to the singleton instance of CXlAsyncManager, or NULL if the instance has not yet been created and bCreateIfNull is false.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXlAsyncManager Class


CXllApp::GetXllDir

Return the directory containing the XLL.

CString GetXllDir( );

Return Value

A string containing the long name of the directory containing the XLL file.

Remarks

This directory is extracted from the member variable m_stDllName, which is initialized during the XllOpen event. Therefore the returned value will not be valid if the function is called during InitInstance.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetXllFileName | CXllApp::GetXllFileNameOnly


CXllApp::GetXllFileName

Return the file name of the XLL.

CString GetXllFileName( );

Return Value

A string containing the file name (including extension, but not including path) of the XLL file.

Remarks

This directory is extracted from the member variable m_stDllName, which is initialized during the XllOpen event. Therefore the returned value will not be valid if the function is called during InitInstance.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetXllDir | CXllApp::GetXllFileNameOnly


CXllApp::GetXllFileNameOnly

Return the file name of the XLL, excluding extension.

CString GetXllFileNameOnly( );

Return Value

A string containing the file name (excluding extension and excluding path) of the XLL file.

Remarks

This directory is extracted from the member variable m_stDllName, which is initialized during the XllOpen event. Therefore the returned value will not be valid if the function is called during InitInstance.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetXllDir | CXllApp::GetXllFileName


CXllApp::GetXllName

Return the full path of the XLL.

static CString GetXllName( );

Return Value

A string containing the full path to the XLL file. If the function failed, the string will be empty.

Remarks

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. You can use code such as:

CString strLibName;
strLibName = CXllApp::GetXllName();

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetXllNameA

Return the full path of the XLL.

static CStringA GetXllNameA( );

Return Value

A string containing the full path to the XLL file. If the function failed, the string will be empty.

Remarks

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. You can use code such as:

CString strLibName;
strLibName = CXllApp::GetXllName();

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetXllNameW

Return the full path of the XLL.

static CStringW GetXllNameW( );

Return Value

A string containing the full path to the XLL file. If the function failed, the string will be empty.

Remarks

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. You can use code such as:

CString strLibName;
strLibName = CXllApp::GetXllName();

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::GetXlVersion

Return the Excel version number

static int GetXlVersion( );

Return Value

Excel's major version number as an integer.

Remarks

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. You can use code such as:

int version = CXllApp::GetXlVersion();

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::InitializeRibbon

Requests the ribbon manager to intialize the ribbon controls for this add-in

void InitializeRibbon( );

Remarks

This method is used by the framework, and should not normally be called by your code.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::InitInstance

Called by the framework when the XLL is loaded into memory

virtual BOOL InitInstance( );

Return Value

TRUE if the function completes successfully; FALSE otherwise.

Remarks

This method is called whenever the XLL is loaded into memory. Note that this can occur not only when the XLL is loaded, but also whenever the XLL is examined in Excel's Tools/AddIns dialog.

Cheap initialization tasks should be done here. In particular, the following must be done:

  1. You must call CXllApp::AddStaticFns() during InitInstance(). This method locates all the add-in functions in the XLL and adds them to the list of add-in functions that will be registered with Excel.
  2. Call the base class method, CXllApp::InitInstance() and return FALSE if the method returns FALSE.

The code generated by the XLL+ AppWizard includes code for all these tasks.

MFC considerations

In the MFC builds, CXllApp is descended from CWinApp. Calling the base class InitInstance ensures that the MFC implementation is properly initialized.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::ExitInstance | CXllApp::OnXllOpenEx()


CXllApp::Instance

Return the single instance of CXllApp

static CXllApp* Instance( );

Return Value

Returns the single instance of CXllApp.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::InvalidateRibbon

Requests the ribbon manager to invalidate the ribbon controls for all add-ins using the ribbon manager

void InvalidateRibbon( );

Remarks

After this method is called, you may receive a number of callbacks via CXllApp::OnRibbonEvent, depending on what attributes have been set in the ribbon.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::InvalidateRibbonControl

Requests the ribbon manager to invalidate a single ribbon control owned by this add-in

void InvalidateRibbonControl(
   LPCTSTR pszControlId
);

Parameters

pszControlId

The unique id of the control to be invalidated.

Remarks

After this method is called, you may receive a number of callbacks via CXllApp::OnRibbonEvent, depending on what attributes have been set in the control.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::InvalidateRibbonForAddin

Requests the ribbon manager to invalidate the ribbon controls for this add-in

void InvalidateRibbonForAddin( );

Remarks

After this method is called, you may receive a number of callbacks via CXllApp::OnRibbonEvent, depending on what attributes have been set in the ribbon.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::IsInFormulaWizard

Is Excel currently showing the Formula Wizard ?

static BOOL IsInFormulaWizard( );

Return Value

TRUE if the current add-in function is being called from the Excel Function Wizard; FALSE otherwise.

Remarks

If your function is expensive to perform, or may involve user interaction, it is not a good idea to call it from the Excel Function Wizard, as it will be called each time one of the arguments is changed. You can use this function to detect the condition and return a safe, cheap result.

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. You can use code such as:

    if ( CXllApp::IsInFormulaWizard())
    {
        xloRet = xlerrNA;
        return xloRet.Ret();
    }

Automating the code

You can use the XLL+ Function Wizard to generate this code for you automatically. See Do not call in Formula Wizard.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Function property: DoNotCallInFormulaWizard


CXllApp::MakeSheetName

Combine a workbook and sheet name to [book]sheet format

static CString MakeSheetName(
   const char* pszBook,
   const char* pszSheet
);
static CString MakeSheetName(
   const wchar_t* pszBook,
   const wchar_t* pszSheet
);

Parameters

pszBook

The name of the workbook.
pszSheet

The name of the worksheet.

Return Value

The name of the sheet in "[book]sheet" format.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::SplitSheetName() | CXllApp::GetSheetName()


CXllApp::NewWorkbookEvent

Gets a reference to the NewWorkbook event

CXlNewWorkbookEvent& NewWorkbookEvent( );

Return Value

The function returns a reference to the application's NewWorkbook event, which is of type CXlNewWorkbookEvent.

Remarks

The NewWorkbook event is raised when a new workbook is created. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlWorkbookEventArgs is passed.

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlNewWorkbookEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::OnAfterCalculate

Called by the framework just after calculation is completed

virtual void OnAfterCalculate( );

Remarks

This function is called just after one or more worksheets have been calculated.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnSheetCalculate()


CXllApp::OnNewWorkbook

Called by the framework when Excel creates a new workbook

virtual void OnNewWorkbook(
   LPDISPATCH dispWorkbook
);

Parameters

dispWorkbook

Pointer to dispatch interface of class Excel.Workbook.

Remarks

This function is called whenever Excel creates a new workbook.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method checks for a function which has been registered as a callback for this event using CXllApp::SetComEventHandler(), and calls it if it is present.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnWorkbookOpen() | CXllApp::GetSinkEvents() | CXllApp::SetSinkEvents()


CXllApp::OnRibbonEvent

Called by the framework when a ribbon event occurs.

virtual CXlOper OnRibbonEvent(
   const CRibbonEvtParams& e
);

Parameters

e

A set of event arguments contained in a CRibbonEvtParams object.

Return Value

The method should return a value of a type expected for the callback being handled. See RibbonCallbackTypes enumeration for a list of these types. See "Callback types" below for a list of the expected return values and types.

Remarks

If this virtual method is implemented by an application class, then the method should first call the base class method, for example as in the code below:

CopyC++
CXlOper CRibbonApp::OnRibbonEvent(const CRibbonEvtParams& e)
{
    CXlOper xloResult = CXllApp::OnRibbonEvent(e);
    switch (e.GetCallback())
    {
    case RIBBONCALLBACK_ONACTION:
        if (e.GetId() == _T("Ribbon1_PushButton"))
            XlMessageBox(_T("Hello from the ribbon!"), XlMessageBoxTypeInformation);
        break;
    }
    return xloResult;
}

Callback types

The table below lists the event parameters and return values for the various callback types.

Callback | Description | Parameters | Return type | Return value
RIBBONCALLBACK_ONACTION | The user has clicked a button or a menu or has selected an item from a gallery or dropdown. | Id, Tag, [Index], [SelectedId], [Pressed] | N/A | N/A
RIBBONCALLBACK_GETDESCRIPTION | The ribbon is asking for the description of a control. | Id, Tag | String | The description of the specified control.
RIBBONCALLBACK_GETENABLED | The ribbon is asking for the enabled state of a control. | Id, Tag | Boolean | True if the control is enabled; false if it is not.
RIBBONCALLBACK_GETIMAGE | The ribbon is asking for the image for a control. | Id, Tag | String | The resource id of an embedd PNG image, or the name of an PNG file in the same directory as the XLL.
RIBBONCALLBACK_GETIMAGEMSO | The ribbon is asking for the image for a control. | Id, Tag | String | The id of a standard Office image.
RIBBONCALLBACK_GETLABEL | The ribbon is asking for the label of a control. | Id, Tag | String | The label of the specified control.
RIBBONCALLBACK_GETKEYTIP | The ribbon is asking for the key tip of a control. | Id, Tag | String | The key tip of the specified control.
RIBBONCALLBACK_GETSIZE | The ribbon is asking for the size of a control. | Id, Tag | Integer | 0 for a regular sized control; 1 for a large control.
RIBBONCALLBACK_GETSCREENTIP | The ribbon is asking for the screentip of a control. | Id, Tag | String | The screentip of the specified control.
RIBBONCALLBACK_GETSUPERTIP | The ribbon is asking for the supertip of a control. | Id, Tag | String | The supertip of the specified control.
RIBBONCALLBACK_GETVISIBLE | The ribbon is asking whether a control is currently visible. | Id, Tag | Boolean | True if the control is visible; false if it is not.
RIBBONCALLBACK_GETSHOWIMAGE | The ribbon is asking whether the image of a control should be shown. | Id, Tag | Boolean | True if the image is visible; false if it is not.
RIBBONCALLBACK_GETSHOWLABEL | The ribbon is asking whether the label of a control should be shown. | Id, Tag | Boolean | True if the label is visible; false if it is not.
RIBBONCALLBACK_GETPRESSED | The ribbon is asking for the pressed state of a control. | Id, Tag | Boolean | True if the control is pressed; false if it is not.
RIBBONCALLBACK_GETITEMCOUNT | The ribbon is asking how many items are contained within a control. | Id, Tag | Integer | The number of items in the specfied control. The ribbon will make further callbacks for each item.
RIBBONCALLBACK_GETITEMHEIGHT | The ribbon is asking for the height of items within a control. | Id, Tag | Integer | The height of each item within a control, in pixels.
RIBBONCALLBACK_GETITEMID | The ribbon is asking for the id of an item within a control. | Id, Tag, Index | String | The id of the specifed item.
RIBBONCALLBACK_GETITEMIMAGE | The ribbon is asking for the image of an item within a control. | Id, Tag, Index | String | The resource id of an embedd PNG image, or the name of an PNG file in the same directory as the XLL.
RIBBONCALLBACK_GETITEMLABEL | The ribbon is asking for the label of an item within a control. | Id, Tag, Index | String | The label of the specified item.
RIBBONCALLBACK_GETITEMSCREENTIP | The ribbon is asking for the screentip of an item within a control. | Id, Tag, Index | String | The screentip of the specified item.
RIBBONCALLBACK_GETITEMSUPERTIP | The ribbon is asking for the supertip of an item within a control. | Id, Tag, Index | String | The supertip of the specified item.
RIBBONCALLBACK_GETITEMWIDTH | The ribbon is asking for the width of an item within a control. | Id, Tag, Index | Integer | The width of the specifed item within a control, in pixels.
RIBBONCALLBACK_GETTEXT | The ribbon is asking for the current text of the control. | Id, Tag | String | The current text in an editBox or comboBox control.
RIBBONCALLBACK_ONCHANGE | The ribbon is notifying the add-in that a text field has been changed by the user. | Id, Tag, Text | String | The current text in an editBox or comboBox control.
RIBBONCALLBACK_GETSELECTEDITEMID | The ribbon is asking for the id of the currently selected item of a control. | Id, Tag | String | The id of the selected item.
RIBBONCALLBACK_GETSELECTEDITEMINDEX | The ribbon is asking for the index of the currently selected item of a control. | Id, Tag | Integer | The index of the selected item.
RIBBONCALLBACK_GETCONTENT | The ribbon is asking for the content of a dynamic menu control. | Id, Tag | String | XML markup containing the menu items and buttons.
RIBBONCALLBACK_GETTITLE | The ribbon is asking for the title of a menu separator. | Id, Tag | String | The title (if any) to be shown on the menu separator.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | The Ribbon (User Guide) | Ribbon reference | RibbonCallbackTypes enumeration


CXllApp::OnSheetActivate

Called by the framework when the user activates a worksheet

virtual void OnSheetActivate(
   LPDISPATCH dispWorksheet
);

Parameters

dispWorksheet

Pointer to dispatch interface of type Excel.Worksheet.

Remarks

This function is called whenever the user activates a worksheet.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnSheetDeactivate() | CXllApp::OnWorkbookActivate() | CXllApp::OnSheetSelectionChange()


CXllApp::OnSheetBeforeDoubleClick

Called by the framework when the user double-clicks in a worksheet

virtual BOOL OnSheetBeforeDoubleClick(
   LPDISPATCH dispWorksheet,
   LPDISPATCH dispRange
);

Parameters

dispWorksheet

Pointer to dispatch interface of type Excel.Worksheet.
dispRange

Pointer to dispatch interface of type Excel.Range, representing the cell or cells that were clicked.

Return Value

The function should return TRUE to cancel any further processing of the double-click event. It should return FALSE (the default) to enable normal processing to continue.

Remarks

This function is called whenever the user double-clicks in a worksheet.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing and returns FALSE.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnSheetBeforeRightClick() | CXllApp::OnSheetSelectionChange()


CXllApp::OnSheetBeforeRightClick

Called by the framework when the user right-clicks in a worksheet

virtual BOOL OnSheetBeforeRightClick(
   LPDISPATCH dispWorksheet,
   LPDISPATCH dispRange
);

Parameters

dispWorksheet

Pointer to dispatch interface of type Excel.Worksheet.
dispRange

Pointer to dispatch interface of type Excel.Range, representing the cell or cells that were clicked.

Return Value

The function should return TRUE to cancel any further processing of the double-click event. It should return FALSE (the default) to enable normal processing to continue.

Note that if you return TRUE, popup menus will be disabled.

Remarks

This function is called whenever the user right-clicks in a worksheet.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing and returns FALSE.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnSheetSelectionChange() | CXllApp::OnSheetBeforeDoubleClick()


CXllApp::OnSheetCalculate

Called by the framework when any worksheet is recalculated

virtual void OnSheetCalculate(
   LPDISPATCH dispWorksheet
);

Parameters

dispWorksheet

Pointer to dispatch interface of type Excel.Worksheet.

Remarks

This function is called whenever a worksheet is recalculated, at the end of the recalculation process.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing.

Note that the function is called once for each worksheet that is recalculated, at the end of the sheet's recalculation.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnSheetDeactivate() | CXllApp::OnWorkbookActivate() | CXllApp::OnSheetSelectionChange()


CXllApp::OnSheetChange

Called by the framework when the user changes the contents of a cell

virtual void OnSheetChange(
   LPDISPATCH dispWorksheet,
   LPDISPATCH dispRange
);

Parameters

dispWorksheet

Pointer to dispatch interface of type Excel.Worksheet.
dispRange

Pointer to dispatch interface of type Excel.Range, representing the new selection.

Remarks

This function is called whenever the user changes the contents of a cell.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnSheetSelectionChange()


CXllApp::OnSheetDeactivate

Called by the framework when the user deactivates a worksheet

virtual void OnSheetDeactivate(
   LPDISPATCH dispWorksheet
);

Parameters

dispWorksheet

Pointer to dispatch interface of type Excel.Worksheet.

Remarks

This function is called whenever the user deactivates a worksheet, before the corresponding Activate event for the newly activated worksheet.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnSheetActivate() | CXllApp::OnWorkbookActivate() | CXllApp::OnSheetSelectionChange()


CXllApp::OnSheetSelectionChange

Called by the framework when the user changes the selection

virtual void OnSheetSelectionChange(
   LPDISPATCH dispWorksheet,
   LPDISPATCH dispRange
);

Parameters

dispWorksheet

Pointer to dispatch interface of type Excel.Worksheet.
dispRange

Pointer to dispatch interface of type Excel.Range, representing the new selection.

Remarks

This function is called whenever the user changes the selection in Excel.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnSheetActivate() | CXllApp::OnWorkbookActivate()


CXllApp::OnWorkbookActivate

Called by the framework when a workbook is activated

virtual void OnWorkbookActivate(
   LPDISPATCH dispWorkbook
);

Parameters

dispWorkbook

Pointer to dispatch interface of type Excel.Workbook.

Remarks

This function is called whenever a workbook is activated, just after the corresponding OnWorkbookDeactivate event for the previously active workbook.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnWorkbookDeactivate() | CXllApp::OnSheetActivate() | CXllApp::OnSheetDeactivate()


CXllApp::OnWorkbookAddinInstall

Called by the framework when an addin is installed

virtual void OnWorkbookAddinInstall(
   LPDISPATCH dispWorkbook
);

Parameters

dispWorkbook

Pointer to dispatch interface of type Excel.Workbook.

Remarks

This function is called when an addin is installed.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnWorkbookAddinUninstall()


CXllApp::OnWorkbookAddinUninstall

Called by the framework when an addin is uninstalled

virtual void OnWorkbookAddinUninstall(
   LPDISPATCH dispWorkbook
);

Parameters

dispWorkbook

Pointer to dispatch interface of type Excel.Workbook.

Remarks

This function is called when an addin is uninstalled.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnWorkbookAddinInstall()


CXllApp::OnWorkbookAfterSave

Called by the framework just after a workbook is saved

virtual void OnWorkbookAfterSave(
   LPDISPATCH dispWorkbook,
   BOOL bSuccess
);

Parameters

dispWorkbook

Pointer to dispatch interface of type Excel.Workbook.
bSuccess

True if the save operation completed successfully.

Remarks

This function is called just after a workbook is saved.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnNewWorkbook() | CXllApp::OnWorkbookOpen() | CXllApp::OnWorkbookBeforeSave()


CXllApp::OnWorkbookBeforeClose

Called by the framework just before a workbook is closed

virtual BOOL OnWorkbookBeforeClose(
   LPDISPATCH dispWorkbook
);

Parameters

dispWorkbook

Pointer to dispatch interface of type Excel.Workbook.

Return Value

The function should return TRUE to cancel any further processing of the double-click event. It should return FALSE (the default) to enable normal processing to continue.

Note that if you return TRUE, the file will not be closed, and if the application is in the process of shutting down, this process will be canceled.

Remarks

This function is called just before a workbook is closed.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing and returns FALSE.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnNewWorkbook() | CXllApp::OnWorkbookOpen() | CXllApp::OnWorkbookBeforeSave()


CXllApp::OnWorkbookBeforePrint

Called by the framework just before a workbook is printed

virtual BOOL OnWorkbookBeforePrint(
   LPDISPATCH dispWorkbook
);

Parameters

dispWorkbook

Pointer to dispatch interface of type Excel.Workbook.

Return Value

The function should return TRUE to cancel any further processing of the double-click event. It should return FALSE (the default) to enable normal processing to continue.

Note that if you return TRUE, the file will not be printed.

Remarks

This function is called just before a workbook is printed.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing and returns FALSE.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnNewWorkbook() | CXllApp::OnWorkbookOpen() | CXllApp::OnWorkbookBeforeSave()


CXllApp::OnWorkbookBeforeSave

Called by the framework just before a workbook is saved

virtual BOOL OnWorkbookBeforeSave(
   LPDISPATCH dispWorkbook,
   BOOL bSaveAsUI
);

Parameters

dispWorkbook

Pointer to dispatch interface of type Excel.Workbook.
bSaveAsUI

True if the Save As dialog box will be displayed.

Return Value

The function should return TRUE to cancel any further processing of the save event. It should return FALSE (the default) to enable normal processing to continue.

Note that if you return TRUE, the file will not be saved.

Remarks

This function is called just before a workbook is saved.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing and returns FALSE.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnNewWorkbook() | CXllApp::OnWorkbookOpen() | CXllApp::OnWorkbookBeforeSave()


CXllApp::OnWorkbookDeactivate

Called by the framework when a workbook is deactivated

virtual void OnWorkbookDeactivate(
   LPDISPATCH dispWorkbook
);

Parameters

dispWorkbook

Pointer to dispatch interface of type Excel.Workbook.

Remarks

This function is called whenever a workbook is deactivated, just before the corresponding OnWorkbookActivate event for the newly active workbook.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnWorkbookActivate() | CXllApp::OnSheetActivate() | CXllApp::OnSheetDeactivate()


CXllApp::OnWorkbookNewSheet

Called by the framework when a new sheet is added to a workbook

virtual void OnWorkbookNewSheet(
   LPDISPATCH dispWorkbook,
   LPDISPATCH dispWorksheet
);

Parameters

dispWorkbook

Pointer to dispatch interface of type Excel.Workbook.
dispWorksheet

Pointer to dispatch interface of type Excel.Worksheet, the newly added worksheet.

Remarks

This function is called when a new sheet is added to a workbook.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnSheetActivate() | CXllApp::OnSheetDeactivate()


CXllApp::OnWorkbookOpen

Called by the framework when a workbook is opened

virtual void OnWorkbookOpen(
   LPDISPATCH dispWorkbook
);

Parameters

dispWorkbook

Pointer to dispatch interface of type Excel.Workbook.

Remarks

This function is called whenever a workbook is opened in Excel.

Note that it will only be called if event-sinking is switched on (using CXllApp::SetSinkEvents()).

You can override the method in your application class to react to the event. The default method does nothing.

Implementation note

You should only implement this function if you need access to Excel's COM interfaces. To handle events, you should usually use the event model. If you particularly need to call an add-in function to handle the event, use the much simpler mechanism provided by CXllApp::SetComEventHandler().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnNewWorkbook() | CXllApp::OnWorkbookActivate() | CXllApp::OnWorkbookBeforeClose() | CXllApp::OnWorkbookBeforeSave()


CXllApp::OnXllClose

Called by the framework when Excel closes the XLL

virtual void OnXllClose( );

Remarks

This function is called whenever a user unloads the add-in, whether using the Excel Tools - Add-ins dialog or indirectly, when closing Excel.

This is a good time to do any termination and cleanup that needs to follow any use of your add-in functions, particularly closing databases and logging off data feeds.

The default implementation of this function does nothing.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnXllOpenEx() | CXllApp::OnXllOpen()


CXllApp::OnXllLoad

Called by the framework when Excel loads the XLL into memory

virtual BOOL OnXllLoad( );

Return Value

TRUE if the function completes successfully; FALSE otherwise.

Remarks

This function is called whenever the XLL is loaded into memory. This can occur repeatedly during the Excel Tools - Add-ins dialog.

The default implementation of this function does nothing.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnXllUnload()


CXllApp::OnXllOpen

Called by the framework when Excel opens the XLL

virtual void OnXllOpen( );

Remarks

This function is called whenever a user loads the add-in, whether using the Excel Tools - Add-ins dialog or directly, using the File - Open menu option.

This is a good time to do any initialization that needs to precede any use of your add-in functions, so long as the initialization cannot fail.

The default implementation of this function does nothing.

Note Note:

This method is deprecated. Use OnXllOpenEx instead.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnXllOpenEx() | CXllApp::OnXllClose()


CXllApp::OnXllOpenEx

Called by the framework when Excel opens the XLL. Programmer can return FALSE to halt further loading of the XLL.

virtual BOOL OnXllOpenEx( );

Return Value

TRUE if the function completes successfully; FALSE otherwise.

Remarks

This function is called whenever a user loads the add-in, whether using the Excel Tools - Add-ins dialog or directly, using the File - Open menu option.

This is a good time to do any initialization that needs to precede any use of your add-in functions, particularly password dialogs or data loading. Return FALSE to indicate that initialization failed, TRUE otherwise.

If you return FALSE, the add-in will not be loaded and will not be used by Excel thereafter.

The default implementation of this function does nothing, and returns TRUE.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnXllOpen() | CXllApp::OnXllClose()


CXllApp::OnXllRegister

Called by the framework when the add-in is registered with the Excel Add-in Manager

virtual void OnXllRegister( );

Remarks

This function is called whenever a user registers the add-in using the Excel Tools - Add-ins dialog. You can use this event to demand, for example, registration information from the user.

Note that since the XLL can be opened directly using the File - Open menu option, this event will not always take place.

The default implementation of this function does nothing.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnXllRegisterEx() | CXllApp::OnXllUnregister()


CXllApp::OnXllRegisterEx

Called by the framework when the add-in is registered with the Excel Add-in Manager

virtual BOOL OnXllRegisterEx( );

Remarks

This function is called whenever a user registers the add-in using the Excel Tools - Add-ins dialog. You can use this event to demand, for example, registration information from the user. You should return FALSE if some problem arises during this handling, and the registration of the XLL will be cancelled.

Note that since the XLL can be opened directly using the File - Open menu option, this event will not always take place.

The default implementation of this function does nothing and returns TRUE.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnXllRegister() | CXllApp::OnXllUnregister()


CXllApp::OnXllUnload

Called by the framework when Excel unloads the XLL

virtual BOOL OnXllUnload( );

Return Value

TRUE if the function completes successfully; FALSE otherwise.

Remarks

This function is called whenever the XLL is unloaded from memory. This can occur repeatedly during the Excel Tools - Add-ins dialog.

The default implementation of this function does nothing.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnXllLoad()


CXllApp::OnXllUnregister

Called by the framework when the add-in is removed from the list of add-ins with the Excel Add-in Manager

virtual void OnXllUnregister( );

Remarks

This function is called whenever a user unregisters the add-in using the Excel Tools - Add-ins dialog. You can use this event to show advertising information.

The default implementation of this function does nothing.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::OnXllRegister()


CXllApp::PrefixFunctions

Add a string prefix to all the library's add-in functions

void PrefixFunctions(
   const TCHAR* pszPrefix
);

Parameters

pszPrefix

Specifies a null-terminated string containing a prefix that will be added to the beginning of all exported Excel functions.

Remarks

This function should only be called during InitInstance(), after AddStaticFns().

All functions in Excel, including add-ins, share the same name-space. It is often useful to use this function to force all your functions to occupy a restricted portion of that name space.

For instance, you could prefix all your functions with the author's initials, thus ensuring that if two developers create different functions which happen to have the same name, they will not conflict in Excel.

Example

CXllApp::PrefixFunctions() Example

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::AddStaticFns()


CXllApp::PrefixFunctionsA

Add a string prefix to all the library's add-in functions

void PrefixFunctionsA(
   const char* pszPrefix
);

Parameters

pszPrefix

Specifies a null-terminated string containing a prefix that will be added to the beginning of all exported Excel functions.

Remarks

This function should only be called during InitInstance(), after AddStaticFns().

All functions in Excel, including add-ins, share the same name-space. It is often useful to use this function to force all your functions to occupy a restricted portion of that name space.

For instance, you could prefix all your functions with the author's initials, thus ensuring that if two developers create different functions which happen to have the same name, they will not conflict in Excel.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::AddStaticFns()


CXllApp::PrefixFunctionsW

Add a string prefix to all the library's add-in functions

void PrefixFunctionsW(
   const wchar_t* pszPrefix
);

Parameters

pszPrefix

Specifies a null-terminated string containing a prefix that will be added to the beginning of all exported Excel functions.

Remarks

This function should only be called during InitInstance(), after AddStaticFns().

All functions in Excel, including add-ins, share the same name-space. It is often useful to use this function to force all your functions to occupy a restricted portion of that name space.

For instance, you could prefix all your functions with the author's initials, thus ensuring that if two developers create different functions which happen to have the same name, they will not conflict in Excel.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::AddStaticFns()


CXllApp::RegisterFunctionsEvent

Gets a reference to the RegisterFunctions event

CXlRegisterFunctionsEvent& RegisterFunctionsEvent( );

Return Value

The function returns a reference to the application's RegisterFunctions event, which is of type CXlRegisterFunctionsEvent.

Remarks

The RegisterFunctions event is raised just before the XLL's add-in functions are registered is opened, giving observers a chance to modify function definitions before the are registered with Excel. All registered observers receive the event via the CXlEventObserver::Update method.

Registration

Observers should register for this event early in the life of the XLL. Registration can be done explicitly during CXllApp::InitInstance, or automatically by creating an instance of CXlRegisterFunctionsEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::RemoveFn

Remove a function from the list of functions to be registered

void RemoveFn(
   LPCTSTR pszFnName
);

Parameters

pszFnName

Pointer to a null-terminated string containing the exported name of the function (i.e. the name visible in Excel).

Remarks

Removes the named function from the list of functions that will be registered when RegisterFunctions() is called during the OnXllOpen() event.

This function should only be used before RegisterFunctions() is called, preferably during the OnXllOpen() or OnXllOpenEx() event handlers.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::AddFn() | CXllApp::FindFn()


CXllApp::RemoveFnA

Remove a function from the list of functions to be registered

void RemoveFnA(
   LPCSTR pszFnName
);

Parameters

pszFnName

Pointer to a null-terminated string containing the exported name of the function (i.e. the name visible in Excel).

Remarks

Removes the named function from the list of functions that will be registered when RegisterFunctions() is called during the OnXllOpen() event.

This function should only be used before RegisterFunctions() is called, preferably during the OnXllOpen() or OnXllOpenEx() event handlers.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::AddFn() | CXllApp::FindFn()


CXllApp::RemoveFnW

Remove a function from the list of functions to be registered

void RemoveFnW(
   LPCWSTR pszFnName
);

Parameters

pszFnName

Pointer to a null-terminated string containing the exported name of the function (i.e. the name visible in Excel).

Remarks

Removes the named function from the list of functions that will be registered when RegisterFunctions() is called during the OnXllOpen() event.

This function should only be used before RegisterFunctions() is called, preferably during the OnXllOpen() or OnXllOpenEx() event handlers.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::AddFn() | CXllApp::FindFn()


CXllApp::ReportRegistrationFailures

Called by the framework to report any add-in functions that fail to register during initialization

virtual bool ReportRegistrationFailures( );

Return Value

Returns true if the XLL can continue loading and false if it should not.

Remarks

This method is called after the functions contained in a DLL are registered with Excel as add-in functions, and one or more fails to register.

The default implementation of this function shows an error message and allows the user to choose whether to continue.

If the function is overridden then the implementation should return true if the XLL can continue loading and false if it should not.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::RetString

Return a string value to Excel.

static const char* RetString(
   const char* psz
);
static const char* RetString(
   const std::string& s
);
static const char* RetString(
   const CString& str
);

Parameters

psz

The string to be returned.
s

A reference to the string to be returned.
str

A reference to the string to be returned.

Return Value

A pointer to a string buffer that can be returned directly to Excel. The XLL+ run-time library will manage clean-up as required.

Remarks

For a string to be returned to Excel, it is necessary that its lifetime extend beyond that of the function from which it is called. One solution is to return a pointer to static storage, but this can be unwieldy and wasteful.

An easier technique is to return a string using RetString(), e.g.:

return CXllApp::RetString("Not a number");

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. You can use code such as:

CString strResult;
strResult.Format("%s%s", apszItemName[i], (j > 1) ? "s" : "");
return CXllApp::RetString(strResult);

Note Note:

This method is deprecated.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::SelectionChangeEvent

Gets a reference to the SelectionChange event

CXlSelectionChangeEvent& SelectionChangeEvent( );

Return Value

The function returns a reference to the application's SelectionChange event, which is of type CXlSelectionChangeEvent.

Remarks

The SelectionChange event is raised when Excel's active cell selection is changed. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlRangeEventArgs is passed.

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlSelectionChangeEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::SetCalculationMode

Set Excel's calculation mode

static int SetCalculationMode(
   int nCalculationMode
);

Parameters

nCalculationMode

nCalculationMode is a number from 1 to 3 indicating the type of calculation:- 1=Automatic; 2=Automatic except tables; 3=Manual.

Return Value

The previous calculation mode.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetCalculationMode


CXllApp::SetComEventHandler

Sets the name of an add-in function to handle a specific COM event

void SetComEventHandler(
   int nEvent,
   const TCHAR* pszMacroName
);

Parameters

nEvent

An integer representing the event to be handled. See Remarks below for a list of values.
pszMacroName

The name of the macro function that will be called when the event occurs. The parameter should be set to NULL or an empty string to switch off event handling for this event.

Observer Event model

This mechanism is now deprecated. It still works, but developers should note that an event handler of this type will override the observer event model. Thus, for example, if SetComEventHandler() is called for the Calculate event, any Calculate event observers that have been registered will not receive events.

Existing add-ins that use SetComEventHandler to handle events, and does not use the event model need not be changed. However, if you are using any features that rely on the event model, you should convert to the event model. Features that rely on the event model include handles and asynchronous functions.

See Events in the User Guide for an introduction to the observer event model.

Note Note:

This method is deprecated.

Remarks

This function sets the name of an add-in function that will be called whenever the specified COM event occurs.

If it is set to the name of an add-in function with the appproriate signature, the function will be called. If the function name is set to an empty string then no special error handling will occur.

Note: COM event handlers installed through this mechanism will not be called unless the SinkEvents flag has been set to TRUE, using CXllApp::SetSinkEvents(TRUE).

Add-in functions for event handling

The table below describes the events and the signatures of the functions that handle them. You can find a set of example functions with the correct signatures in the ComEvents sample.

Event | Return value | Argument 1 | Argument 2
NewWorkbook | (ignored) | const TCHAR* WorkbookName |
SheetSelectionChange | (ignored) | const TCHAR* WorksheetName | const TCHAR* Range
SheetBeforeDoubleClick | BOOL Cancel | const TCHAR* WorksheetName | const TCHAR* Range
SheetBeforeRightClick | BOOL Cancel | const TCHAR* WorksheetName | const TCHAR* Range
SheetActivate | (ignored) | const TCHAR* WorksheetName |
SheetDeactivate | (ignored) | const TCHAR* WorksheetName |
SheetCalculate | (ignored) | const TCHAR* WorksheetName |
SheetChange | (ignored) | const TCHAR* WorksheetName | const TCHAR* Range
WorkbookOpen | (ignored) | const TCHAR* WorkbookName |
WorkbookActivate | (ignored) | const TCHAR* WorkbookName |
WorkbookDeactivate | (ignored) | const TCHAR* WorkbookName |
WorkbookBeforeClose | BOOL Cancel | const TCHAR* WorkbookName |
WorkbookBeforeSave | BOOL Cancel | const TCHAR* WorkbookName | BOOL bSaveAsUI
WorkbookBeforePrint | BOOL Cancel | const TCHAR* WorkbookName |
WorkbookNewSheet | {ignored) | const TCHAR* WorkbookName | const TCHAR* WorksheetName
WorkbookAddinInstall | {ignored) | const TCHAR* WorkbookName |
WorkbookAddinUninstall | {ignored) | const TCHAR* WorkbookName |

The following restrictions and notes also apply to event handler callback functions:

Macro functions
Event handler call-back functions must be marked as Macro functions in the XLL+ Function Wizard.
WorksheetName
The WorksheetName argument will always be in the form [Book1]Sheet1. You can split into it's constituent parts with the CXllApp::SplitSheetName() method.
BOOL Cancel
Some of these handlers are expected to return a BOOL result, which tells Excel whether to carry on processing the event. You should normally return FALSE, and only return TRUE if you wish to disable further standard event handling.
SetSinkEvents
The event handler will not be called unless COM event handling has been switched on using CXllApp::SetSinkEvents(TRUE).

For more details about these events, see Excel Help for the events of the Application object.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetComEventHandler() | CXllApp::SetSinkEvents() | ComEvents sample


CXllApp::SetErrorHandling

Switch on or off XLM4 macro error handling

static SetErrorHandling(
   BOOL bValue
);

Parameters

bValue

TRUE to switch on error handling. FALSE to switch it off.

Remarks

This function can be used to control how Excel reacts to failed functions. It is equivalent to calling the XL4 macro "=ERROR(bValue)". If error handling is switched off, then no Excel alert boxes will be shown.

This function can only be called from macro functions. It will always fail if called from worksheet functions.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::SetHasRibbon

Sets whether the application has a ribbon

void SetHasRibbon(
   bool bNewValue
);

Parameters

bNewValue

True if the add-in supplies a ribbon; false if it deos not.

Remarks

The function should not be called after the OnXllOpenEx event has been raised. In normal use, it should be called during InitInstance(), immediately after SetRibbonImplementation.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::SetHideArgumentBoxForNoArgs

Set the behavior of the Excel Formula Wizard for functions with no arguments

void SetHideArgumentBoxForNoArgs(
   bool hide
);

Parameters

hide

If hide is true, then the extra argument box that appears in the Excel Formula Wizard for functions which in fact have no arguments will be suppressed. As a side-effect, the help text for the function will not appear.

If hide is false, then the extra argument box will continue to appear. However, the help text for the function will appear.

Remarks

There is a problem with the Excel Formula Wizard when displaying functions that have no arguments. Either the Wizard displays an argument box for a non-existent argument, or the help text for the function is not displayed.

The table below shows the behavior of the Wizard when displaying a zero-argument function, for different values of hide.

hide | Argument box | Function help text
true | Not displayed (good) | Not displayed (bad)
false | Displayed (bad) | Displayed (good)

The default value for this setting is false. If you want to change it, call SetHideArgumentBoxForNoArgs(true) during CXllApp::InitInstance() or CXllApp::OnXllOpenEx().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetHideArgumentBoxForNoArgs()


CXllApp::SetNumericToStringConversionMethod

Set the value of the NumericToStringConversionMethod flag.

static void SetNumericToStringConversionMethod(
   int conversionMethod
);

Parameters

conversionMethod

An integer value indicating the method used for Numeric to String conversion. If the value is 1, then the XLL+ framework will be set to use the method of XLL+ 5 (and earlier versions), offering increased accuracy (because Excel handles the conversion). If the value is 0, then the framework will use the method of XLL+ 6 and above, which is faster but less accurate.

This flag controls the behavior of the conversion used by functions called in generated code, when the target variable is a string (or an array of strings) and the input value is numeric.

When the library is initialized, the default value is 0. To change the default behavior, call this method during InitInstance().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetNumericToStringConversionMethod()


CXllApp::SetPrivateBinPath

Sets the private path used by the .NET Assembly loader.

void SetPrivateBinPath(
   const CString& path
);

Parameters

path

A string containing a list of directories, separated by semi-colons.

Remarks

By default, this path contains a single directory - the directory that contains the XLL. If your .NET assembly files are located in the same directory as the XLL, then there is no need to change the value of the private bin path.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetPrivateBinPath()


CXllApp::SetRibbonImplementation

Sets the implementation used by the application to support a ribbon

void SetRibbonImplementation(
   RibbonImplementations nImpl
);

Parameters

nImpl

This value should be RibbonImplementationShared to use the shared ribbon manager.

Remarks

The function should not be called after the OnXllOpenEx event has been raised. In normal use, it should be called during InitInstance(), immediately before SetHasRibbon(true).

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::SetSinkEvents

Sets the SinkEvents flag to switch COM event handling on or off

BOOL SetSinkEvents(
   BOOL bSinkEvents
);

Parameters

bSinkEvents

The new value of the SinkEvents flag

Return Value

Returns the new value of the SinkEvents flag.

Remarks

This function sets the state of the COM event handler.

If it is set to TRUE, then the event handlers for COM events will be invoked whenever significant events occur in Excel.

You can specify event handlers by overloading the appropriate virtual function in your derived application class.

Note Note:

This method is deprecated.

COM event handlers

The functions registered using CXllApp::SetComEventHandler() will not be called unless SetSinkEvents(TRUE) has been called.

In addition, the following handlers are switched on and off by SetSinkEvents():

CXllApp::OnNewWorkbook()
CXllApp::OnSheetSelectionChange()
CXllApp::OnSheetBeforeDoubleClick()
CXllApp::OnSheetBeforeRightClick()
CXllApp::OnSheetActivate()
CXllApp::OnSheetDeactivate()
CXllApp::OnSheetCalculate()
CXllApp::OnSheetChange()
CXllApp::OnWorkbookOpen()
CXllApp::OnWorkbookActivate()
CXllApp::OnWorkbookDeactivate()
CXllApp::OnWorkbookBeforeClose()
CXllApp::OnWorkbookBeforeSave()
CXllApp::OnWorkbookBeforePrint()
CXllApp::OnWorkbookAddinInstall()
CXllApp::OnWorkbookAddinUninstall()
CXllApp::OnAfterCalculate()
CXllApp::OnWorkbookAfterSave()

Note that the other overridable functions (OnXllOpen() etc) are not affected by the SinkEvents flag.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::GetSinkEvents()


CXllApp::SetUseAutomation

Returns the value of the UseAutomation attribute

void SetUseAutomation(
   BOOL bUseAutomation
);

Parameters

bUseAutomation

This value will set the value of the UseAutomation attribute.

Return Value

Sets the value of the UseAutomation attibute. If this attribute is set to TRUE, then the addin will get a handle to Excel's COM interface during initialization. If it is FALSE, then the COM interface will not be available to the add-in.

Deprecation

Note Note:

This method is deprecated.

Remarks

The method must be called during CXllApp::InitInstance in order to have any effect.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllCom object | CXllApp::GetApplicationDispatch() | CXllApp::GetUseAutomation()


CXllApp::SheetActivateEvent

Gets a reference to the SheetActivate event

CXlSheetActivateEvent& SheetActivateEvent( );

Return Value

The function returns a reference to the application's SheetActivate event, which is of type CXlSheetActivateEvent.

Remarks

The SheetActivate event is raised when a worksheet is activated. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlWorksheetEventArgs is passed.

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlSheetActivateEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::SheetChangeEvent

Gets a reference to the SheetChange event

CXlSheetChangeEvent& SheetChangeEvent( );

Return Value

The function returns a reference to the application's SheetChange event, which is of type CXlSheetChangeEvent.

Remarks

The SheetChange event is raised when a cell is changed in a worksheet. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlRangeEventArgs is passed.

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlSheetChangeEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::SheetDeactivateEvent

Gets a reference to the SheetDeactivate event

CXlSheetDeactivateEvent& SheetDeactivateEvent( );

Return Value

The function returns a reference to the application's SheetDeactivate event, which is of type CXlSheetDeactivateEvent.

Remarks

The SheetDeactivate event is raised when a worksheet is deactivated. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlWorksheetEventArgs is passed.

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlSheetDeactivateEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::SplitSheetName

Get a workbook and sheet name from [book]sheet format

static SplitSheetName(
   const char* pszFullName,
   CStringA& strBook,
   CStringA& strSheet
);
static SplitSheetName(
   const wchar_t* pszFullName,
   CStringW& strBook,
   CStringW& strSheet
);

Parameters

pszFullName

The full name of the sheet in [book]sheet format.
strBook

The name of the workbook wil be placed here, if any is contained in pszFullName.
strSheet

The name of the worksheet will be placed here.

Example

CXllApp::SplitSheetName() Example

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::MakeSheetName() | CXllApp::GetSheetName()


CXllApp::SupportsRibbon

Returns whether the container application can support a ribbon

bool SupportsRibbon( );

Return Value

Returns true if the running version of Excel supports ribbons (i.e. is Excel 2007 or later). Returns false if the ribbon is not supported by the running version of Excel.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::TerminateRibbon

Requests the ribbon manager to terminate the ribbon controls for this add-in

void TerminateRibbon( );

Remarks

This method is used by the framework, and should not normally be called by your code.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::WinMessageBox

Display the standard Windows message box

static int WinMessageBox(
   LPCTSTR lpText,
   LPCTSTR lpCaption,
   UINT uType
);

Parameters

lpText

A null-terminated string that will be displayed in the message box.
lpCaption

A null-terminated string that will be displayed in title of the message box.
uType

Various MB_* flags, specifying the buttons, icons and behavior of the message box.

Return Value

See the documention for the Win32 API function ::MessageBox().

Remarks

This function calls the the Win32 API function MessageBox(). This offers more flexibility than the Excel message box (see CXllApp::XlMessageBox), and is generally preferred to it.

See the documention for the Win32 API function ::MessageBox().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::XlMessageBox


CXllApp::WinMessageBoxA

Display the standard Windows message box

static int WinMessageBoxA(
   LPCSTR lpText,
   LPCSTR lpCaption,
   UINT uType
);

Parameters

lpText

A null-terminated string that will be displayed in the message box.
lpCaption

A null-terminated string that will be displayed in title of the message box.
uType

Various MB_* flags, specifying the buttons, icons and behavior of the message box.

Return Value

See the documention for the Win32 API function ::MessageBox().

Remarks

This function calls the the Win32 API function MessageBox(). This offers more flexibility than the Excel message box (see CXllApp::XlMessageBox), and is generally preferred to it.

See the documention for the Win32 API function ::MessageBox().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::XlMessageBox


CXllApp::WinMessageBoxW

Display the standard Windows message box

static int WinMessageBoxW(
   LPCWSTR lpText,
   LPCWSTR lpCaption,
   UINT uType
);

Parameters

lpText

A null-terminated string that will be displayed in the message box.
lpCaption

A null-terminated string that will be displayed in title of the message box.
uType

Various MB_* flags, specifying the buttons, icons and behavior of the message box.

Return Value

See the documention for the Win32 API function ::MessageBox().

Remarks

This function calls the the Win32 API function MessageBox(). This offers more flexibility than the Excel message box (see CXllApp::XlMessageBox), and is generally preferred to it.

See the documention for the Win32 API function ::MessageBox().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::XlMessageBox


CXllApp::WorkbookActivateEvent

Gets a reference to the WorkbookActivate event

CXlWorkbookActivateEvent& WorkbookActivateEvent( );

Return Value

The function returns a reference to the application's WorkbookActivate event, which is of type CXlWorkbookActivateEvent.

Remarks

The WorkbookActivate event is raised when a workbook is activated. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlWorkbookEventArgs is passed.

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookActivateEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::WorkbookAfterSaveEvent

Gets a reference to the WorkbookAfterSave event

CXlWorkbookAfterSaveEvent& WorkbookAfterSaveEvent( );

Return Value

The function returns a reference to the application's WorkbookAfterSave event, which is of type CXlWorkbookAfterSaveEvent.

Remarks

The WorkbookAfterSave event is raised when a workbook save operation is complete, and provides a flag indicating whether the operation was successful, and the saved name of the workbook. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlAfterSaveEventArgs is passed.

Availability

Note that this event is only available when running under Excel 2010 (Excel 14) or above.

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookAfterSaveEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::WorkbookBeforeCloseEvent

Gets a reference to the WorkbookBeforeClose event

CXlWorkbookBeforeCloseEvent& WorkbookBeforeCloseEvent( );

Return Value

The function returns a reference to the application's WorkbookBeforeClose event, which is of type CXlWorkbookBeforeCloseEvent.

Remarks

The WorkbookBeforeClose event is raised when a workbook is about to be closed, and allows the event to be cancelled. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlBeforeCloseEventArgs is passed. Observers can cancel normal processing of the double-click by cancelling the event using CXlBeforeCloseEventArgs::SetCancel(false).

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookBeforeCloseEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::WorkbookBeforeSaveEvent

Gets a reference to the WorkbookBeforeSave event

CXlWorkbookBeforeSaveEvent& WorkbookBeforeSaveEvent( );

Return Value

The function returns a reference to the application's WorkbookBeforeSave event, which is of type CXlWorkbookBeforeSaveEvent.

Remarks

The WorkbookBeforeSave event is raised when a workbook is about to be saved, and allows the event to be cancelled. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlBeforeSaveEventArgs is passed. Observers can cancel normal processing of the double-click by cancelling the event using CXlBeforeSaveEventArgs::SetCancel(false).

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookBeforeSaveEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::WorkbookDeactivateEvent

Gets a reference to the WorkbookDeactivate event

CXlWorkbookDeactivateEvent& WorkbookDeactivateEvent( );

Return Value

The function returns a reference to the application's WorkbookDeactivate event, which is of type CXlWorkbookDeactivateEvent.

Remarks

The WorkbookDeactivate event is raised when a workbook is deactivated. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlWorkbookEventArgs is passed.

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookDeactivateEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::WorkbookNewSheetEvent

Gets a reference to the WorkbookNewSheet event

CXlWorkbookNewSheetEvent& WorkbookNewSheetEvent( );

Return Value

The function returns a reference to the application's WorkbookNewSheet event, which is of type CXlWorkbookNewSheetEvent.

Remarks

The WorkbookNewSheet event is raised when a new sheet is added to a workbook. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlWorkbookNewSheetEventArgs is passed.

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookNewSheetEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::WorkbookOpenEvent

Gets a reference to the WorkbookOpen event

CXlWorkbookOpenEvent& WorkbookOpenEvent( );

Return Value

The function returns a reference to the application's WorkbookOpen event, which is of type CXlWorkbookOpenEvent.

Remarks

The WorkbookOpen event is raised when a workbook is opened. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXlWorkbookEventArgs is passed.

Registration

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookOpenEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events


CXllApp::XlGetStackSpace

Gets the number of bytes of remaining stack space

static USHORT XlGetStackSpace( );

Return Value

Returns the number of bytes of stack space available.

Remarks

Excel has a limited amount of stack space available for use by add-in functions. The XLL+ classes have been designed to make optimal use of the stack, and any very large data requirements are allocated on the heap and automatically cleaned up.

However, if your code needs very large amounts of stack space (for instance in a recursive algorithm), then you should check that sufficient stack space is available for your code to run, by periodically calling XlGetStackSpace().

Note Note:

This method is deprecated. Use XlGetStackSpace2 instead.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::XlGetStackSpace2

Gets the number of bytes of remaining stack space

static unsigned int XlGetStackSpace2( );

Return Value

Returns the number of bytes of stack space available.

Remarks

Excel has a limited amount of stack space available for use by add-in functions. The XLL+ classes have been designed to make optimal use of the stack, and any very large data requirements are allocated on the heap and automatically cleaned up.

However, if your code needs very large amounts of stack space (for instance in a recursive algorithm), then you should check that sufficient stack space is available for your code to run, by periodically calling XlGetStackSpace().

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllApp::XlHwnd

Return Excel's application window handle

static HWND XlHwnd( );

Return Value

The handle to Excel's application window. If a modal dialog is being shown by Excel, then this function will return the handle of the dialog window instead. In either case the return value is a useful handle to use an ancestor for your own windows or as an argument to Windows API calls.

Remarks

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. You can use code such as:

hwnd = CXllApp::XlHwnd();

It is not usually necessary to call this function to retrieve arguments for MFC functions. The CExcelWnd class will automatically attach itself to the Excel application window when it is constructed; this is the preferred interface between Excel and MFC windows.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CExcelWnd


CXllApp::XllCloseEvent

Gets a reference to the XllClose event

CXllCloseEvent& XllCloseEvent( );

Return Value

The function returns a reference to the application's XllClose event, which is of type CXllCloseEvent.

Remarks

The XllClose event is raised when the XLL is closed, just before OnXllClose() is called. All registered observers receive the event via the CXlEventObserver::Update method.

Registration

Observers can be registered explicitly at any time during the life of the XLL, or automatically by creating an instance of CXllCloseEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events | CXllApp::XllOpenEvent() | CXllApp::OnXllClose()


CXllApp::XllOpenEvent

Gets a reference to the XllOpen event

CXllOpenEvent& XllOpenEvent( );

Return Value

The function returns a reference to the application's XllOpen event, which is of type CXllOpenEvent.

Remarks

The XllOpen event is raised when the XLL is opened, just after OnXllOpenEx() is called. All registered observers receive the event via the CXlEventObserver::Update method.

When observers are notified, an argument of type CXllOpenEventArgs is passed.

Registration

Observers should register for this event early in the life of the XLL. Registration can be done explicitly during CXllApp::InitInstance, or automatically by creating an instance of CXllOpenEventStaticObserver.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | Events | CXllApp::XllCloseEvent() | CXllApp::OnXllOpenEx()


CXllApp::XlMessageBox

Display the Excel message box

static BOOL XlMessageBox(
   const TCHAR* pszText,
   XlMessageBoxTypes usType
);

Parameters

pszText

A null-terminated string that will be displayed in the message box.
usType

If usType is XlMessageBoxTypeQuestion (1), XlMessageBox will display a dialog with OK and Cancel buttons; the icon will be a question mark. If usType is XlMessageBoxTypeInformation (2), then an information icon will be displayed, and only the OK button will be available. If usType is XlMessageBoxTypeExclamation (3), then a warning icon will be displayed, and only the OK button will be available.

Return Value

TRUE if the user presses OK; FALSE if the user presses Cancel

Remarks

This function displays an Excel message box containing the text parameter, an icon, the OK button and optionally the Cancel button. It is equivalent to calling the Excel ALERT macro.

Since the function is static, it is not necessary to use an instance of CXllApp to invoke it. It is not therefore necessary to fix the MFC CWinApp instance using the XLL_FIX_STATE macro: you can use code such as:

if ( CXllApp::XlMessageBox("Refresh data now?", 1) )
    RefreshData();

If you need more flexibility from a message box, use the Windows MessageBox via CXllApp::WinMessageBox, or create your own dialog class and show it using an instance of CExcelWnd as the parent CWnd.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::WinMessageBox | CXllApp::XlHwnd | CExcelWnd


CXllApp::XlMessageBoxA

Display the Excel message box

static BOOL XlMessageBoxA(
   const char* pszText,
   XlMessageBoxTypes usType
);

Parameters

pszText

A null-terminated string that will be displayed in the message box.
usType

If usType is XlMessageBoxTypeQuestion (1), XlMessageBox will display a dialog with OK and Cancel buttons; the icon will be a question mark. If usType is XlMessageBoxTypeInformation (2), then an information icon will be displayed, and only the OK button will be available. If usType is XlMessageBoxTypeExclamation (3), then a warning icon will be displayed, and only the OK button will be available.

Return Value

TRUE if the user presses OK; FALSE if the user presses Cancel

Remarks

This function displays an Excel message box containing the text parameter, an icon, the OK button and optionally the Cancel button. It is equivalent to calling the Excel ALERT macro.

Since the function is static, it is not necessary to use an instance of CXllApp to invoke it. It is not therefore necessary to fix the MFC CWinApp instance using the XLL_FIX_STATE macro: you can use code such as:

if ( CXllApp::XlMessageBox("Refresh data now?", 1) )
    RefreshData();

If you need more flexibility from a message box, use the Windows MessageBox via CXllApp::WinMessageBox, or create your own dialog class and show it using an instance of CExcelWnd as the parent CWnd.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::WinMessageBox | CXllApp::XlHwnd | CExcelWnd


CXllApp::XlMessageBoxW

Display the Excel message box

static BOOL XlMessageBoxW(
   const wchar_t* pszText,
   XlMessageBoxTypes usType
);

Parameters

pszText

A null-terminated string that will be displayed in the message box.
usType

If usType is XlMessageBoxTypeQuestion (1), XlMessageBox will display a dialog with OK and Cancel buttons; the icon will be a question mark. If usType is XlMessageBoxTypeInformation (2), then an information icon will be displayed, and only the OK button will be available. If usType is XlMessageBoxTypeExclamation (3), then a warning icon will be displayed, and only the OK button will be available.

Return Value

TRUE if the user presses OK; FALSE if the user presses Cancel

Remarks

This function displays an Excel message box containing the text parameter, an icon, the OK button and optionally the Cancel button. It is equivalent to calling the Excel ALERT macro.

Since the function is static, it is not necessary to use an instance of CXllApp to invoke it. It is not therefore necessary to fix the MFC CWinApp instance using the XLL_FIX_STATE macro: you can use code such as:

if ( CXllApp::XlMessageBox("Refresh data now?", 1) )
    RefreshData();

If you need more flexibility from a message box, use the Windows MessageBox via CXllApp::WinMessageBox, or create your own dialog class and show it using an instance of CExcelWnd as the parent CWnd.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods | CXllApp::WinMessageBox | CXllApp::XlHwnd | CExcelWnd


CXllApp::XlVersion

Return the Excel version number

static double XlVersion( );

Return Value

Excel's major and minor version numbers as the integer and fractional parts of a double precision floating point number e.g. 5.0 or 4.1.

Remarks

Since this function is static, it is not necessary to use an instance of CXllApp to invoke it. It is not therefore necessary to fix the MFC CWinApp instance using the XLL_FIX_STATE macro: you can use code such as:

dVersion = CXllApp::XlVersion();

Note Note:

This method is deprecated. Use GetXlVersion instead.

Requirements

Header: xllplus.h

See Also

CXllApp Class | CXllApp Methods


CXllFn Class

Represents a single add-in function.

class CXllFn

Overview

The CXllFn object represents a function that can be (and may already have been) registered. The class is used extensively by the framework, but is only of use to you as an add-in author if you wish to inspect or modify function definitions at run-time.

CXllFn Data Members

The public data members if CXllFn are listed below. Many of the values used by Excel 2007 are wide strings. See Wide strings for help on how to use these.

CStringW | m_stName | Name of function in Excel. (Note that this field is now a wide string, whereas it was a standard string under XLL+ 5 and below. See Breaking changes for more details.)
CStringA | m_stEntryPoint4 | Name of C wrapper function used under earlier versions of Excel.
CStringA | m_stEntryPoint12 | Name of C wrapper function used under Excel 2007 and above.
CStringA | m_stArgTemplate4 | Argument template for earlier versions of Excel, containing the return type, the data types of the arguments and behaviour flags.
CStringW | m_stArgTemplate12 | Argument template for Excel 2007, containing the return type, the data types of the arguments and behaviour flags.
CStringA | m_stArgNames4 | Argument names for earlier versions of Excel, separated by commas.
CStringW | m_stArgNames12 | Argument names for Excel 2007 and above, separated by commas.
USHORT | m_usType | Availability flag. 1 indicates that the function can be called from worksheets; 2 that it can be called from macro sheets; 0 that it can be called from either, but is not shown in the Excel Formula Wizard. No other value is acceptable.
CStringA | m_stCategory4 | The category under which the function will appear in the Excel Function Wizard, under earlier versions of Excel.
CStringW | m_stCategory12 | The category under which the function will appear in the Excel Function Wizard, under Excel 2007 and above.
USHORT | m_usHelpTopic | The help topic ID for the function. 0 indicates that no help is available.
CStringW | m_stHelpTopic | The help topic identifier string for the function. If this is empty, then the help topic ID will be used.
CStringA | m_stHelpText4 | Description of function (as displayed by Excel Function Wizard), under earlier versions of Excel.
CStringW | m_stHelpText12 | Description of function (as displayed by Excel Function Wizard), under Excel 2007 and above.
CStringA[] | m_astArgHelpText4 | String array containing descriptions of each argument (as displayed by Excel Function Wizard), under earlier versions of Excel.
CStringW[] | m_astArgHelpText12 | String array containing descriptions of each argument (as displayed by Excel Function Wizard), under Excel 2007 and above.
CString | m_stKey | Fast key to invoke macro function.

Requirements

Header: xllplus.h

See Also

CXllFn Methods | xllplus.h | CXllApp object


CXllFn Methods

The methods of the CXllFn class are listed here.

State

public method | IsRegistered | Returns whether the function has been successfully registered
public method | RegID | Returns the registration ID for the function.

Properties

public method | GetArgumentCount | Returns the number of arguments.
public method | GetArgumentHelpText | Returns the help text for the one of the function's arguments as it will appear in the Excel Formula Wizard.
public method | GetArgumentHelpTextA | Returns the help text for the one of the function's arguments as it will appear in the Excel Formula Wizard.
public method | GetArgumentHelpTexts | Returns the help text for all of the function's arguments as it will appear in the Excel Formula Wizard.
public method | GetArgumentHelpTextW | Returns the help text for the one of the function's arguments as it will appear in the Excel Formula Wizard.
public method | GetArgumentName | Returns the name of one of the function's arguments as it will appear in the Excel Formula Wizard.
public method | GetArgumentNameA | Returns the name of one of the function's arguments as it will appear in the Excel Formula Wizard.
public method | GetArgumentNames | Returns the names of all of the function's arguments as they will appear in the Excel Formula Wizard.
public method | GetArgumentNameW | Returns the name of one of the function's arguments as it will appear in the Excel Formula Wizard.
public method | GetArgumentTemplate | Returns the function's argument template.
public method | GetArgumentTemplateA | Returns the function's argument template.
public method | GetArgumentTemplateW | Returns the function's argument template.
public method | GetCategory | Returns the category under which the function will appear in the Excel Formula Wizard.
public method | GetCategoryA | Returns the category under which the function will appear in the Excel Formula Wizard.
public method | GetCategoryW | Returns the category under which the function will appear in the Excel Formula Wizard.
public method | GetEntryPoint | Returns the name of the registered 'C' entry-point for the function.
public method | GetEntryPointA | Returns the name of the registered 'C' entry-point for the function.
public method | GetEntryPointW | Returns the name of the registered 'C' entry-point for the function.
public method | GetHelpText | Returns the help text for the function which will appear in the Excel Formula Wizard.
public method | GetHelpTextA | Returns the help text for the function which will appear in the Excel Formula Wizard.
public method | GetHelpTextW | Returns the help text for the function which will appear in the Excel Formula Wizard.
public method | GetName | Returns the name of the function as it will appear in Excel.

Version

public method | SupportsXL12 | Returns whether the function is available under Excel 2007 and above.
public method | SupportsXL4 | Returns whether the function is available under Excel 2003 and below.

Construction

public method CXllFn Constructs a CXllFn object

Requirements

Header: xllplus.h

See Also

CXllFn Class | xllplus.h | CXllApp object


CXllFn::CXllFn

Constructs a CXllFn object

CXllFn( );

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetArgumentCount

Returns the number of arguments.

size_t GetArgumentCount( ) const;

Return Value

Returns the number of arguments to the function.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetArgumentHelpText

Returns the help text for the one of the function's arguments as it will appear in the Excel Formula Wizard.

CString GetArgumentHelpText(
   size_t index
) const;

Parameters

index

Index of the argument. If the index is out of range, then an exception of type CXlOutOfRangeException will be thrown.

Return Value

Returns the help text for the one of the function's arguments as it will appear in the Excel Formula Wizard. If the help text contains resource IDs, it will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetArgumentHelpTextA

Returns the help text for the one of the function's arguments as it will appear in the Excel Formula Wizard.

CStringA GetArgumentHelpTextA(
   size_t index
) const;

Parameters

index

Index of the argument. If the index is out of range, then an exception of type CXlOutOfRangeException will be thrown.

Return Value

Returns the help text for the one of the function's arguments as it will appear in the Excel Formula Wizard. If the help text contains resource IDs, it will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetArgumentHelpTexts

Returns the help text for all of the function's arguments as it will appear in the Excel Formula Wizard.

void GetArgumentHelpTexts(
   std::vector<CStringA>& names
) const;
void GetArgumentHelpTexts(
   std::vector<CStringW>& wnames
) const;

Parameters

names

This vector will be filled with the help text of each of the function's arguments as it will appear in the Excel Formula Wizard and in Excel 2007 pop-up help. If a help text contains resource IDs, they will be localized.

wnames

This vector will be filled with the help text of each of the function's arguments as it will appear in the Excel Formula Wizard and in Excel 2007 pop-up help. If a help text contains resource IDs, they will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetArgumentHelpTextW

Returns the help text for the one of the function's arguments as it will appear in the Excel Formula Wizard.

CStringW GetArgumentHelpTextW(
   size_t index
) const;

Parameters

index

Index of the argument. If the index is out of range, then an exception of type CXlOutOfRangeException will be thrown.

Return Value

Returns the help text for the one of the function's arguments as it will appear in the Excel Formula Wizard. If the help text contains resource IDs, it will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetArgumentName

Returns the name of one of the function's arguments as it will appear in the Excel Formula Wizard.

CString GetArgumentName(
   size_t index
) const;

Parameters

index

Index of the argument. If the index is out of range, then an exception of type CXlOutOfRangeException will be thrown.

Return Value

Returns the name of one of the function's arguments as it will appear in the Excel Formula Wizard and in Excel 2007 pop-up help. If the argument name has a resource ID, it will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetArgumentNameA

Returns the name of one of the function's arguments as it will appear in the Excel Formula Wizard.

CStringA GetArgumentNameA(
   size_t index
) const;

Parameters

index

Index of the argument. If the index is out of range, then an exception of type CXlOutOfRangeException will be thrown.

Return Value

Returns the name of one of the function's arguments as it will appear in the Excel Formula Wizard and in Excel 2007 pop-up help. If the argument name has a resource ID, it will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetArgumentNames

Returns the names of all of the function's arguments as they will appear in the Excel Formula Wizard.

void GetArgumentNames(
   std::vector<CStringA>& names
) const;
void GetArgumentNames(
   std::vector<CStringW>& wnames
) const;

Parameters

names

This vector will be filled with the names of the function's arguments as they will appear in the Excel Formula Wizard and in Excel 2007 pop-up help. If an argument name has a resource ID, it will be localized.

wnames

This vector will be filled with the names of the function's arguments as they will appear in the Excel Formula Wizard and in Excel 2007 pop-up help. If an argument name has a resource ID, it will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetArgumentNameW

Returns the name of one of the function's arguments as it will appear in the Excel Formula Wizard.

CStringW GetArgumentNameW(
   size_t index
) const;

Parameters

index

Index of the argument. If the index is out of range, then an exception of type CXlOutOfRangeException will be thrown.

Return Value

Returns the name of one of the function's arguments as it will appear in the Excel Formula Wizard and in Excel 2007 pop-up help. If the argument name has a resource ID, it will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetArgumentTemplate

Returns the function's argument template.

CString GetArgumentTemplate( ) const;

Return Value

Returns the function's argument template. This will vary according to which version of Excel is running.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetArgumentTemplateA

Returns the function's argument template.

CStringA GetArgumentTemplateA( ) const;

Return Value

Returns the function's argument template. This will vary according to which version of Excel is running.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetArgumentTemplateW

Returns the function's argument template.

CStringW GetArgumentTemplateW( ) const;

Return Value

Returns the function's argument template. This will vary according to which version of Excel is running.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetCategory

Returns the category under which the function will appear in the Excel Formula Wizard.

CString GetCategory( ) const;

Return Value

Returns the category under which the function will appear in the Excel Formula Wizard. If the category contains resource IDs, it will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetCategoryA

Returns the category under which the function will appear in the Excel Formula Wizard.

CStringA GetCategoryA( ) const;

Return Value

Returns the category under which the function will appear in the Excel Formula Wizard. If the category contains resource IDs, it will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetCategoryW

Returns the category under which the function will appear in the Excel Formula Wizard.

CStringW GetCategoryW( ) const;

Return Value

Returns the category under which the function will appear in the Excel Formula Wizard. If the category contains resource IDs, it will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetEntryPoint

Returns the name of the registered 'C' entry-point for the function.

CString GetEntryPoint( ) const;

Return Value

Returns the name of the registered 'C' entry-point for the function. This will vary according to which version of Excel is running.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetEntryPointA

Returns the name of the registered 'C' entry-point for the function.

CStringA GetEntryPointA( ) const;

Return Value

Returns the name of the registered 'C' entry-point for the function. This will vary according to which version of Excel is running.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetEntryPointW

Returns the name of the registered 'C' entry-point for the function.

CStringW GetEntryPointW( ) const;

Return Value

Returns the name of the registered 'C' entry-point for the function. This will vary according to which version of Excel is running.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetHelpText

Returns the help text for the function which will appear in the Excel Formula Wizard.

CString GetHelpText( ) const;

Return Value

Returns the function's help text. If the help text contains resource IDs, it will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetHelpTextA

Returns the help text for the function which will appear in the Excel Formula Wizard.

CStringA GetHelpTextA( ) const;

Return Value

Returns the function's help text. If the help text contains resource IDs, it will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetHelpTextW

Returns the help text for the function which will appear in the Excel Formula Wizard.

CStringW GetHelpTextW( ) const;

Return Value

Returns the function's help text. If the help text contains resource IDs, it will be localized.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::GetName

Returns the name of the function as it will appear in Excel.

CString GetName( ) const;

Return Value

Returns the name of the function as it will appear in Excel.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::IsRegistered

Returns whether the function has been successfully registered

BOOL IsRegistered( ) const;

Return Value

Returns TRUE if the function has been successfully registered as an Excel add-in function. Returns FALSE if the function has not been registered, or if registration failed.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::RegID

Returns the registration ID for the function.

double RegID( ) const;

Return Value

Returns a non-zero value if the function has been successfully registered as an Excel add-in function. Returns 0.0 if the function has not been registered, or if registration failed.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::SupportsXL12

Returns whether the function is available under Excel 2007 and above.

bool SupportsXL12( ) const;

Return Value

Returns true if the function can be registered under Excel 2007 and above. Returns false if the function cannot be registered under Excel 2007 and above.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXllFn::SupportsXL4

Returns whether the function is available under Excel 2003 and below.

bool SupportsXL4( ) const;

Return Value

Returns true if the function can be registered under Excel 2003 and below. Returns false if the function cannot be registered under Excel 2003 and below.

Requirements

Header: xllplus.h

See Also

CXllFn Class | CXllFn Methods


CXlOper Class

Used to pass data from add-in functions to Excel.

class CXlOper

Overview

A CXlOper object encapsulates the XLOPER structure. This structure is used by the Excel SDK to pass data between Excel and add-in functions. Specifically, the XLOPER data type is used to pass data to and from Excel under the following circumstances:

  • Passing values which can contain various data types
  • Passing arrays
  • Passing optional arguments

    • Because Excel 2007 and earlier versions of Excel use different XLOPER structures, code that directly reads or writes the structure must be aware of which version of Excel it is using. The CXlOper class wraps these differences, so that you can ignore which version of Excel is being run.

    Data types

    The table below lists the data types supported by the CXlOper class.

    Type | 'C' type | Description
xltypeNum | double | IEEE floating-point number (8 bytes)
xltypeStr | LPSTR | Under Excel 2003 and below: an ASCII string (limited to 255 characters)
xltypeStr | LPWSTR | Under Excel 2007 and above: a Unicode string (limited to 32,767 characters)
xltypeBool | BOOL | Boolean
xltypeErr | WORD | Error value. For a full list of error values, see the Error codes.
xltypeInt | short int | Under Excel 2003 and below: a 16-bit integer
xltypeInt | int | Under Excel 2007 and above: a 32-bit integer
xltypeMulti | array | Array of XLOPERs
xltypeSRef | sref | Reference to a single range of cells
xltypeRef | mref | Reference to one or more ranges of cells

    COper class

    Under earlier versions of XLL+ (5 and below) the COper class was used as a simple way to pass array or optional arguments from Excel to add-in functions. The COper class has now been merged into CXlOper. The following line in the XLL+ header files redefines COper:

    CopyC++
    typedef CXlOper COper;

    This allows existing code that uses the COper type to build without problems.

    Some methods of COper have not been implemented. Please see Breaking changes - COper methods for a list.

    CXlArray type

    See also Comparison of CXlOper and CXlArray types.

    Requirements

    Header: xllplus.h

    See Also

    CXlOper Methods | xllplus.h


CXlOper Methods

The methods of the CXlOper class are listed here.

Construction

public method CXlOper Constructs a CXlOper object

Operations

public method Clear Reclaim resources from CXlOper

Comparisons

public method | Compare | Compare the contents of this CXlOper with another
public method | operator != | Compare the contents of this CXlOper with another
public method | operator < | Compare the contents of this CXlOper with another
public method | operator <= | Compare the contents of this CXlOper with another
public method | operator == | Compare the contents of this CXlOper with another
public method | operator > | Compare the contents of this CXlOper with another
public method | operator >= | Compare the contents of this CXlOper with another

Type inspection

public method | IsArray | Does the CXlOper contain an array?
public method | IsBool | Does the CXlOper contain a boolean?
public method | IsDouble | Does the CXlOper contain a double-precision floating point number?
public method | IsEmpty | Is the CXlOper empty?
public method | IsError | Does the CXlOper contain an error?
public method | IsInt | Does the CXlOper contain an integer?
public method | IsMissing | Is the CXlOper missing (i.e. omitted from the caller's argument list)?
public method | IsMRef | Does the CXlOper contain a multiple reference?
public method | IsOfType | Is the CXlOper of the specified type?
public method | IsPresent | Is the CXlOper not missing (i.e. not omitted from the caller's argument list)?
public method | IsRef | Does the CXlOper contain a reference?
public method | IsScalar | Does the CXlOper contain a single value?
public method | IsSRef | Does the CXlOper contain a single reference?
public method | IsString | Does the CXlOper contain a string?
public method | IsValue | Does the CXlOper contain one or more values?

Assignment operators

public method operator = Assigns a new value to the CXlOper, using a variety of input types

Output casting operators

public method | operator [] | Returns an item from an array
public method | operator BOOL | Returns a boolean value
public method | operator bool | Returns a boolean value
public method | operator CString | Returns a string value
public method | operator double | Returns a numeric value

Input functions

public method | FromBool | Assigns a boolean value and data type to the CXlOper
public method | FromDouble | Assigns an floating-point numeric value and data type to the CXlOper
public method | FromDoubleArray | Assigns the CXlOper to be an array of double's, and copies values into the array
public method | FromError | Assigns an error value and data type to the CXlOper
public method | FromInt | Assigns a single integer to the CXlOper
public method | FromLongArray | Assigns the CXlOper to be an array of double's wih integer values, and copies values into the array
public method | FromMatrix | Assigns a 2-dimensional array of numbers, booleans or strings to the CXlOper
public method | FromMatrix2 | Assigns a 2-dimensional array of numbers, booleans or strings to the CXlOper
public method | FromMissing | Sets the CXlOper to be a missing argument
public method | FromMRef | Assigns multiple range references to the CXlOper
public method | FromNil | Sets the CXlOper to be an empty argument
public method | FromNumericMatrix | Assigns a 2-dimensional array of numbers to the CXlOper
public method | FromNumericVector | Assigns a 1-dimensional array of numbers to the CXlOper
public method | FromNumericVector2 | Assigns a 1-dimensional array of numbers to the CXlOper
public method | FromSRef | Assigns a single range reference to the CXlOper
public method | FromString | Assigns a string value and data type to the CXlOper
public method | FromVector | Assigns a 1-dimensional array of numbers, booleans or strings to the CXlOper
public method | FromVector2 | Assigns a 1-dimensional array of numbers, booleans or strings to the CXlOper

Output functions

public method | ToBool | Returns a boolean value
public method | ToDouble | Retrieves a numeric value from the CXlOper
public method | ToInt | Returns an integer value
public method | ToString | Returns a string value

Array functions

public method | AllocArray | Assigns the CXlOper to be an array, sets it to a size and allocates the memory to contain its items
public method | Cell | Returns a reference to an item in an array
public method | FreeArray | Releases the resources of an array's items
public method | GetCount | Returns the number of cells in an array
public method | GetCount2 | Returns the number of cells in an array
public method | GetDims | Gets the number of rows and columns in an array
public method | GetHeight | Returns the number of rows in an array
public method | GetHeight2 | Returns the number of rows in an array
public method | GetVectorCount | Returns the number of cells in an array
public method | GetVectorCount2 | Returns the number of cells in an array
public method | GetWidth | Returns the number of columns in an array
public method | GetWidth2 | Returns the number of columns in an array
public method | IsVector | Returns TRUE if the CXlOper contains 1 row and/or 1 column
public method | VectorCell | Returns a reference to an item in a one-dimensional array

Matrix & vector functions

public method | ReadMatrix | Reads data from a 2-dimensional array into a matrix of numbers or strings
public method | ReadVector | Reads a row or a column from an array into a vector of numbers or strings

Reference functions

public method | GetActiveCell | Creates a reference to the active cell
public method | GetRef | Returns a copy of the first (or only) single reference in a single or multiple range reference
public method | GetRefCount | Returns the number of references in a multiple reference
public method | GetRefItem | Returns a copy of one of the single references in a multiple reference
public method | GetSheetId | Returns the SheetId of a CXlOper containing a reference
public method | GetSheetName | Returns the SheetName of a CXlOper containing a reference
public method | GetSheetNameA | Returns the SheetName of a CXlOper containing a reference
public method | GetSheetNameW | Returns the SheetName of a CXlOper containing a reference
public method | MakeRef | Creates a reference from an address
public method | MakeRefA | Creates a reference from an address
public method | MakeRefIntl | Creates a reference from an address in English
public method | MakeRefIntlA | Creates a reference from an address in English
public method | MakeRefIntlW | Creates a reference from an address in English
public method | MakeRefW | Creates a reference from an address
public method | MoveRefBy | Moves a reference by the specified number of rows and columns
public method | Offset | Returns a reference moved by the specified number of rows and columns
public method | Resize | Returns a reference resized to the specified number of rows and columns
public method | SetActiveCell | Sets the active cell to be the cell referred to by this CXlOper
public method | SetRef | Sets the first (or only) single reference in a single or multiple range reference
public method | SetRefItem | Sets one of the single references in a multiple reference

SDK interface

public method | ChangeType | Convert a CXlOper from one data type to another
public method | Coerce | Convert an Excel range into an array of values, forcing a recalculation if necessary
public method | ConvertFormula | Convert a formula between A1 and RC formats, using local language settings
public method | ConvertFormulaA | Convert a formula between A1 and RC formats, using local language settings
public method | ConvertFormulaIntl | Convert a formula between A1 and RC formats, using English language settings
public method | ConvertFormulaIntlA | Convert a formula between A1 and RC formats, using English language settings
public method | ConvertFormulaIntlW | Convert a formula between A1 and RC formats, using English language settings
public method | ConvertFormulaW | Convert a formula between A1 and RC formats, using local language settings
public method | Evaluate | Evaluate a formula expressed in local language
public method | EvaluateIntl | Evaluate a formula expressed in US English format
public method | Excel | Invoke the Excel SDK
public method | GetCaller | Retrieve a reference to the cell or cells that called the add-in function
public method | GetFormula | Get the formula in the referenced cell, in local format
public method | GetFormulaA | Get the formula in the referenced cell, in local format
public method | GetFormulaIntl | Get the formula in the referenced cell, in English
public method | GetFormulaIntlA | Get the formula in the referenced cell, in English
public method | GetFormulaIntlW | Get the formula in the referenced cell, in English
public method | GetFormulaW | Get the formula in the referenced cell, in local format
public method | GetLongString | Read a long string (of up to 1024 characters) from a single cell
public method | GetLongStringA | Read a long string (of up to 1024 characters) from a single cell
public method | GetLongStringW | Read a long string (of up to 1024 characters) from a single cell
public method | SetFormula | Set the formula of the referenced cell, in local format
public method | SetFormulaA | Set the formula of the referenced cell, in local format
public method | SetFormulaIntl | Set the formula of the referenced cell, in English
public method | SetFormulaIntlA | Set the formula of the referenced cell, in English
public method | SetFormulaIntlW | Set the formula of the referenced cell, in English
public method | SetFormulaW | Set the formula of the referenced cell, in local format
public method | SetLongFormula | Set the formula of the referenced cell, in local format, for formulae of more than 255 characters
public method | SetLongFormulaA | Set the formula of the referenced cell, in local format, for formulae of more than 255 characters
public method | SetLongFormulaIntl | Set the formula of the referenced cell, in English, for formulae of more than 255 characters
public method | SetLongFormulaIntlA | Set the formula of the referenced cell, in English, for formulae of more than 255 characters
public method | SetLongFormulaIntlW | Set the formula of the referenced cell, in English, for formulae of more than 255 characters
public method | SetLongFormulaW | Set the formula of the referenced cell, in local format, for formulae of more than 255 characters
public method | SetValue | Set the value of the referenced cells

Utilities

public method | Format | Fill the CXlOper with a formatted string (like sprintf() and CString::Format())
 | MissingArg | Returns a placeholder to send to SDK calls as a missing argument
 | MissingArgP | Returns a placeholder to send to SDK calls as a missing argument

Return handlers

public method | CallAddin | Call an add-in function directly, and store the result
public method | HandleResult | Ensures that an add-in function result is contained in the calling object
public method | Ret | Prepares a CXlOper to be returned as a value to Excel
 | RetError | Returns an error value to Excel
 | RetString | Returns a string value to Excel
 | RetVal | Returns a pointer to Excel's return value

Deprecated functions

public method ToDoubleArray Copies the contents of an OPER into a 'C' array of doubles or pointers to doubles

Requirements

Header: xllplus.h

See Also

CXlOper Class | xllplus.h


CXlOper::AllocArray

Assigns the CXlOper to be an array, sets it to a size and allocates the memory to contain its items

void AllocArray(
   size_t szRows,
   size_t szCols
);
void AllocArray(
   size_t szRows,
   size_t szCols,
   const CXlOper& xloFill
);

Parameters

szRows

The number of rows to be allocated in the array.
szCols

The number of columns to be allocated in the array.
xloFill

A value which will be used to initialise all the cells in the array.

Remarks

This function sets a CXlOper to be an array and sets its size. It then populates it either with #N/A (first variant), or with xloFill (second variant).

Use this function if you are returning an array of mixed cells, such as strings and numbers in a single array. If you are returning arrays of a single type, then you will find the FromMatrix() and FromVector() functions simpler and quicker to use.

Examples

CXlOper::GetCallerDims() Example | CXlOper::AllocArray() Example | CXlOper::GetCaller() Example | MyMonthsInYear Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::CallAddin

Call an add-in function directly, and store the result

void CallAddin(
   CXlOper* pxloResult
);

Parameters

pxloResult

The return value of an add-in function.

Remarks

This function can be used to call an add-in function directly from another add-in function within the same library. The result of the call will be placed in the calling CXlOper instance.

For example:

CXlOper* BsTheta_Impl(CXlOper& xloResult, double Spot, BOOL Put, const CXlOper*
    Div, double Borrow, double ImpVol, double Strike, long ValueDate, long
    Maturity, double RiskFree, short int DayCount)
{
    // End of generated code
//}}XLP_SRC

    // Call the array version of the function
    CXlOper xloCalc;
    xloCalc.CallAddin(BsCalc_Impl(xloCalc, Spot, Put, Div, Borrow, ImpVol,
        Strike, ValueDate, Maturity, RiskFree, DayCount));

    // Extract a cell from the array
    if (xloCalc.IsArray())
        xloResult = xloCalc.Cell(6, 1);
    else
        xloResult = xloCalc;

    return xloResult.Ret();
}

See the SimpOpt sample for an example of the method in use.

Caution

This is the recommended way to call local add-in functions directly. Any other method (such as simply copying the return value) may result in memory leaks.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::Ret() | CXlOper::Excel()


CXlOper::Cell

Returns a reference to an item in an array

CXlCell Cell(
   size_t szRow,
   size_t szCol
);
const CXlConstCell Cell(
   size_t szRow,
   size_t szCol
) const;

Parameters

szRow

The row containing the item of interest (the top row is 0).
szCol

The column containing the item of interest (the leftmost column is 0).

Remarks

The reference returned by this function can be used to read the item and (if the CXlOper itself is writeable) to update it.

If the indices are out of range then an exception of type CXlOutOfRangeException will be thrown.

Breaking change

Under previous versions of XLL+ (5 and below), this method returned a reference to a CXlOper type, which was contained within the outer CXlOper. In order to support both Excel 2007 and older versions of Excel, this functionality has had to be changed.

The method now returns a new class of object, CXlCell or CXlConstCell, which can be used to refer to the cell, but is not itself of type CXlOper.

If your code retained a copy of the return value, as in for instance:

const CXlOper& item = xloArray.Cell(i, j);
total += item.ToDouble();

then it must be changed. The code above becomes:

CXlConstCell item = xloArray.Cell(i, j);
total += item.ToDouble();

If your code simply used the returned value without retaining a copy of it, then it will continue to compile. For example, the following code does not need to change:

xloArray.Cell(i, j) = 0.0;

Examples

CXlOper::GetCallerDims() Example | CXlOper::Cell() Example | CXlOper::AllocArray() Example | CXlOper::GetCaller() Example | MyMonthsInYear Example | MySum Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::ChangeType

Convert a CXlOper from one data type to another

int ChangeType(
   WORD xltype,
   const CXlOper* lpxlopSource = 0
);

Parameters

xltype

The type desired. This should be one of the xltype values listed in CXlOper data types.

lpxlopSource

The source of the conversion. If lpxlopSource is 0, then the destination CXlOper (*this) will be converted in place.

Return Value

The result of the SDK call-back. xlretSuccess (0) indicates success. Other values indicate failure. A full list of return values can be found in Error Codes.

Remarks

This function converts a CXlOper from its current data type to another.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::Coerce()


CXlOper::Clear

Reclaim resources from CXlOper

void Clear( );

Remarks

Clear the value in the CXlOper. If the value has already been set, then it will be discarded with appropriate memory reallocation.

This function is called automatically by the destructor when necessary.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::Init()


CXlOper::Coerce

Convert an Excel range into an array of values, forcing a recalculation if necessary

int Coerce( );
int Coerce(
   const CXlRef& xlr
);
int Coerce(
   const CXlOper& xlo
);

Parameters

xlr

A valid reference to an Excel cell range.
xlo

A CXlOper containing at least one range reference.

Return Value

The result of the SDK call-back. xlretSuccess (0) indicates success. Other values indicate failure. A full list of return values can be found in Error Codes.

Remarks

This function fills the CXlOper object with the values contained in the cells referred to by the parameter. If there are no arguments, and the CXlOper currently contains a cell reference, then that reference will be used.

It is important to note that this function will fail under Excel 2003 and below if more than 64 kb of data is contained in the cell range. This is equivalent to about 5400 cells.

Example

CXlOper::Coerce() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetValue()


CXlOper::Compare

Compare the contents of this CXlOper with another

int Compare(
   const CXlOper& xlo
) const;

Parameters

xlo

A reference to another CXlOper.

Return Value

Returns 1 if the value in this object is greater than that in xlo, -1 if xlo is less and 0 if the two are equal.

Remarks

This function acts like strcmp() and similar 'C' library functions.

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::ConvertFormula

Convert a formula between A1 and RC formats, using local language settings

BOOL ConvertFormula(
   const TCHAR* pszFormulaIn,
   CString& strFormulaOut,
   BOOL bToA1
) const;

Parameters

pszFormulaIn

String buffer containing the formula. The formula is assumed to be in the current language (i.e. in "local" form), using punctuation derived from the user's regional settings, and function names derived from the Excel version.

If the formula is not in the correct format for the current settings, then the call will fail. To convert a formula which works under all language settings, see CXlOper::ConvertFormulaIntl.
strFormulaOut

Buffer to receive converted formula, in local language.
bToA1

If FALSE, then pszFormulaIn should contain references in A1 format; if TRUE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed.

Remarks

This method requires that the calling object be a valid reference (i.e. this->IsRef() is true). Relative addresses in the formula will be treated as being relative to the calling object's reference.

Breaking change

In XLL+ versions earlier than 4.3.1, this method was implemented as a static function. This was a design error, and has been corrected. As a result, existing calls to CXlOper::ConvertFormula that are explicitly expressed as static will fail to compile, e.g.:

BOOL ok = CXlOper::ConvertFormula(strIn, strOut, TRUE);
In addition, calls to ConvertFormula which are non-static will fail at run-time if the calling object does not contain a reference.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetFormula() | CXlOper::SetFormula()


CXlOper::ConvertFormulaA

Convert a formula between A1 and RC formats, using local language settings

BOOL ConvertFormulaA(
   const char* pszFormulaIn,
   CStringA& strFormulaOut,
   BOOL bToA1
) const;

Parameters

pszFormulaIn

String buffer containing the formula. The formula is assumed to be in the current language (i.e. in "local" form), using punctuation derived from the user's regional settings, and function names derived from the Excel version.

If the formula is not in the correct format for the current settings, then the call will fail. To convert a formula which works under all language settings, see CXlOper::ConvertFormulaIntl.
strFormulaOut

Buffer to receive converted formula, in local language.
bToA1

If FALSE, then pszFormulaIn should contain references in A1 format; if TRUE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed.

Remarks

This method requires that the calling object be a valid reference (i.e. this->IsRef() is true). Relative addresses in the formula will be treated as being relative to the calling object's reference.

Breaking change

In XLL+ versions earlier than 4.3.1, this method was implemented as a static function. This was a design error, and has been corrected. As a result, existing calls to CXlOper::ConvertFormula that are explicitly expressed as static will fail to compile, e.g.:

BOOL ok = CXlOper::ConvertFormula(strIn, strOut, TRUE);
In addition, calls to ConvertFormula which are non-static will fail at run-time if the calling object does not contain a reference.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetFormula() | CXlOper::SetFormula()


CXlOper::ConvertFormulaIntl

Convert a formula between A1 and RC formats, using English language settings

BOOL ConvertFormulaIntl(
   const TCHAR* pszFormulaIn,
   CString& strFormulaOut,
   BOOL bToA1
) const;

Parameters

pszFormulaIn

String buffer containing the formula. The formula is assumed to be in English, using US English regional settings - i.e. arguments and lists are separated by commas; rows in arrays are separated by semi-colons; the full stop is used as a decimal point.

If the formula is not in the correct English format, then the call will fail. To convert a formula which works using local language settings, see CXlOper::ConvertFormula.
strFormulaOut

Buffer to receive converted formula.
bToA1

If FALSE, then pszFormulaIn should contain references in A1 format; they will be converted to RC. If TRUE, the references should be in RC format; they will be converted to A1.

Return Value

Returns TRUE if the function was successful, FALSE if it failed.

Remarks

This method requires that the calling object be a valid reference (i.e. this->IsRef() is true). Relative addresses in the formula will be treated as being relative to the calling object's reference.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetFormulaIntl() | CXlOper::SetFormulaIntl()


CXlOper::ConvertFormulaIntlA

Convert a formula between A1 and RC formats, using English language settings

BOOL ConvertFormulaIntlA(
   const char* pszFormulaIn,
   CStringA& strFormulaOut,
   BOOL bToA1
) const;

Parameters

pszFormulaIn

String buffer containing the formula. The formula is assumed to be in English, using US English regional settings - i.e. arguments and lists are separated by commas; rows in arrays are separated by semi-colons; the full stop is used as a decimal point.

If the formula is not in the correct English format, then the call will fail. To convert a formula which works using local language settings, see CXlOper::ConvertFormula.
strFormulaOut

Buffer to receive converted formula.
bToA1

If FALSE, then pszFormulaIn should contain references in A1 format; they will be converted to RC. If TRUE, the references should be in RC format; they will be converted to A1.

Return Value

Returns TRUE if the function was successful, FALSE if it failed.

Remarks

This method requires that the calling object be a valid reference (i.e. this->IsRef() is true). Relative addresses in the formula will be treated as being relative to the calling object's reference.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetFormulaIntl() | CXlOper::SetFormulaIntl()


CXlOper::ConvertFormulaIntlW

Convert a formula between A1 and RC formats, using English language settings

BOOL ConvertFormulaIntlW(
   const wchar_t* pszFormulaIn,
   CStringW& strFormulaOut,
   BOOL bToA1
) const;

Parameters

pszFormulaIn

String buffer containing the formula. The formula is assumed to be in English, using US English regional settings - i.e. arguments and lists are separated by commas; rows in arrays are separated by semi-colons; the full stop is used as a decimal point.

If the formula is not in the correct English format, then the call will fail. To convert a formula which works using local language settings, see CXlOper::ConvertFormula.
strFormulaOut

Buffer to receive converted formula.
bToA1

If FALSE, then pszFormulaIn should contain references in A1 format; they will be converted to RC. If TRUE, the references should be in RC format; they will be converted to A1.

Return Value

Returns TRUE if the function was successful, FALSE if it failed.

Remarks

This method requires that the calling object be a valid reference (i.e. this->IsRef() is true). Relative addresses in the formula will be treated as being relative to the calling object's reference.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetFormulaIntl() | CXlOper::SetFormulaIntl()


CXlOper::ConvertFormulaW

Convert a formula between A1 and RC formats, using local language settings

BOOL ConvertFormulaW(
   const wchar_t* pszFormulaIn,
   CStringW& strFormulaOut,
   BOOL bToA1
) const;

Parameters

pszFormulaIn

String buffer containing the formula. The formula is assumed to be in the current language (i.e. in "local" form), using punctuation derived from the user's regional settings, and function names derived from the Excel version.

If the formula is not in the correct format for the current settings, then the call will fail. To convert a formula which works under all language settings, see CXlOper::ConvertFormulaIntl.
strFormulaOut

Buffer to receive converted formula, in local language.
bToA1

If FALSE, then pszFormulaIn should contain references in A1 format; if TRUE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed.

Remarks

This method requires that the calling object be a valid reference (i.e. this->IsRef() is true). Relative addresses in the formula will be treated as being relative to the calling object's reference.

Breaking change

In XLL+ versions earlier than 4.3.1, this method was implemented as a static function. This was a design error, and has been corrected. As a result, existing calls to CXlOper::ConvertFormula that are explicitly expressed as static will fail to compile, e.g.:

BOOL ok = CXlOper::ConvertFormula(strIn, strOut, TRUE);
In addition, calls to ConvertFormula which are non-static will fail at run-time if the calling object does not contain a reference.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetFormula() | CXlOper::SetFormula()


CXlOper::CXlOper

Constructs a CXlOper object

CXlOper( );
CXlOper(
   const CXlOper& xlo
);
CXlOper(
   XLOPER4* xlop4
);
CXlOper(
   XLOPER12* xlop12
);
CXlOper(
   double d
);
CXlOper(
   XlErrorType xlerr
);
CXlOper(
   BOOL wboolean
);
CXlOper(
   bool boolean
);
CXlOper(
   const CString& str
);
CXlOper(
   const char* psz
);
CXlOper(
   const CStringA& astr
);
CXlOper(
   const std::string& str_stl
);
CXlOper(
   const wchar_t* wpsz
);
CXlOper(
   const CStringW& wstr
);
CXlOper(
   const std::wstring& wstr_stl
);
CXlOper(
   const CXlStringArg& str_arg
);
CXlOper(
   int i,
   int nDummy
);
CXlOper(
   const double* pd,
   size_t cRows
);
CXlOper(
   const double* pd,
   size_t cRows,
   size_t cCols,
   BOOL bByRows = FALSE
);
CXlOper(
   const double* const* apd,
   size_t cRows,
   size_t cCols,
   BOOL bByRows = FALSE
);
CXlOper(
   const long* pl,
   size_t cRows
);
CXlOper(
   const long* pl,
   size_t cRows,
   size_t cCols,
   BOOL bByRows = FALSE
);
CXlOper(
   const long* const* apl,
   size_t cRows,
   size_t cCols,
   BOOL bByRows = FALSE
);
CXlOper(
   const xlp::matrix<double>& dmat
); [Deprecated]
CXlOper(
   const xlp::matrix<CString>& smat
); [Deprecated]
CXlOper(
   const std::vector<double>& dvec,
   BOOL bRow = FALSE,
   long lBound = 0
);
CXlOper(
   const std::vector<bool>& bvec,
   BOOL bRow = FALSE,
   long lBound = 0
);
CXlOper(
   const std::vector<std::string>& strvec,
   BOOL bRow = FALSE,
   long lBound = 0
);
CXlOper(
   const std::vector<std::wstring>& wstrvec,
   BOOL bRow = FALSE,
   long lBound = 0
);
CXlOper(
   const std::vector<CString>& svec,
   BOOL bRow = FALSE,
   long lBound = 0
);
CXlOper(
   const std::vector<std::CStringA>& asvec,
   BOOL bRow = FALSE,
   long lBound = 0
);
CXlOper(
   const std::vector<std::CStringW>& wsvec,
   BOOL bRow = FALSE,
   long lBound = 0
);
CXlOper(
   const std::vector<long>& lvec,
   BOOL bRow = FALSE,
   long lBound = 0,
   BOOL toBoolean = FALSE
);

Parameters

xlo

A reference to a CXlOper instance, which will be deep-copied to this object.
xlop4

A pointer to an initialised OPER4, as passed by Excel 2003 and below.
xlop12

A pointer to an initialised OPER12, as passed by Excel 2007 and above.
d

A double-precision floating-point number.
xlerr

An error number (see also Error Values).

wboolean

A boolean value: TRUE (1) or FALSE (0).
boolean

A boolean value: true or false.
str

A reference to a CString, which will be copied into the value of the new object.
psz

A pointer to a null-terminated ASCII string.

Note that under Excel 2007 and above, the string will be converted to Unicode.
astr

A reference to a CStringA, which will be copied into the value of the new object.

Note that under Excel 2007 and above, the string will be converted to Unicode.
str_stl

A reference to a STL std::string, which will be copied into the value of the new object.

Note that under Excel 2007 and above, the string will be converted to Unicode.
wpsz

A pointer to a null-terminated wide-character string.

Note that under Excel 2003 and below, the string will be converted to a multi-byte character ASCII string, and will be truncated to 255 bytes.

wstr

A reference to a CStringW, which will be copied into the value of the new object.

Note that under Excel 2003 and below, the string will be converted to a multi-byte character ASCII string, and will be truncated to 255 bytes.

wstr_stl

A reference to a STL std::wstring, which will be copied into the value of the new object.

Note that under Excel 2003 and below, the string will be converted to a multi-byte character ASCII string, and will be truncated to 255 bytes.

str_arg

A reference to a CXlStringArg passed to an add-in function by Excel, which will be copied into the value of the new object.

Note that under Excel 2003 and below, the string will be a multi-byte character ASCII string, and will be limited to 255 bytes. Under Excel 2007 and above, the string is Unicode and is limited to 32,767 characters.

i

An integer value. This constructor creates an XLOPER variant which is of use only in calls to the Excel SDK.
nDummy

Ignored. This dummy parameter is required in order to distinguish the integer constructor from other more frequently used numeric constructors.
pd

An array of double's, containing either cRows items, or (cRows x cCols) items, depending on the function variant used. For the latter type, the values should be arranged in the order specified by the bByRows parameter.
cRows

The number of rows contained in the supplied array of items.
cCols

The number of columns contained in the supplied array of items.
bByRows

Storage order of arrays of double's. If TRUE, then values in the same row are stored contiguously, otherwise values in the same column are assumed to be stored contiguously.
apd

An array of pointers to double, containing either cRows arrays each of size cCols, or cCols arrays each of size cRows, depending on the order specified by the bByRows parameter.
pl

An array of long's, containing either cRows items, or (cRows x cCols) items, depending on the function variant used. For the latter type, the values should be arranged in the order specified by the bByRows parameter.

apl

An array of pointers to long, containing either cRows arrays each of size cCols, or cCols arrays each of size cRows, depending on the order specified by the bByRows parameter.

dmat

A reference to a matrix of doubles. The array in the CXlOper will contain a copy of the matrix.
smat

A reference to a matrix of CStrings. The array in the CXlOper will contain a copy of the matrix.
dvec

A reference to a vector of doubles. The array in the CXlOper will contain a copy of the vector.
bRow

If TRUE, then the vector created will be a row; otherwise the vector will be a column.
lBound

The number of items at the start of the input vector which will be ignored. This is useful for vectors created with a lower bound (usually 1).

bvec

A reference to a vector of booleans. The array in the CXlOper will contain a copy of the vector.

strvec

A reference to a vector of std::string's. The array in the CXlOper will contain a copy of the vector.
wstrvec

A reference to a vector of std::wstring wide character strings. The array in the CXlOper will contain a copy of the vector.

svec

A reference to a vector of CStrings. The array in the CXlOper will contain a copy of the vector.

asvec

A reference to a vector of CStringA ASCII strings. The array in the CXlOper will contain a copy of the vector.

wsvec

A reference to a vector of CStringW wide-character strings. The array in the CXlOper will contain a copy of the vector.

lvec

A reference to a vector of long integers. The array in the CXlOper will contain a copy of the vector. Depending on the value of toBoolean, each cell will be converted to either a boolean value or a double.

toBoolean

If TRUE, then the resulting Excel array will contain boolean values instead of numbers. Any non-zero value will be converted to TRUE, and zero values will be converted to FALSE.

Remarks

The vector and matrix versions of the constructor will throw an exception of type CXlEmptyArrayException if the supplied array is empty, or of type CXlArrayTooLargeException if the array is too large.

Example

MyUpper Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::Evaluate

Evaluate a formula expressed in local language

int Evaluate(
   const char* pszFormula
);
int Evaluate(
   const wchar_t* pszFormula
);

Parameters

pszFormula

A string containing the formula to be evaluated.

Return Value

The result of the SDK call-back. xlretSuccess (0) indicates success. Other values indicate failure. A full list of return values can be found in Error Codes.

Remarks

This function fills the CXlOper object with the result of the formula passed to it.

International considerations

Be careful when using formulae that the formula is formatted correctly for the current language settings. For example, arguments in English are separated by commas; in German, semi-colons are used.

You can use CXllApp::GetInternational to get the current list separators and other punctuation characters.

Alternatively, you can use CXlOper::EvaluateIntl to apply formulae that work under all language settings.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::EvaluateIntl

Evaluate a formula expressed in US English format

int EvaluateIntl(
   const char* pszFormula
);
int EvaluateIntl(
   const wchar_t* pszFormula
);

Parameters

pszFormula

A string containing the formula to be evaluated. The formula should use US English settings for built-in funcion names, addresses and separators.

Return Value

The result of the SDK call-back. xlretSuccess (0) indicates success. Other values indicate failure. A full list of return values can be found in Error Codes.

Remarks

This function fills the CXlOper object with the result of the formula passed to it.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::Excel

Invoke the Excel SDK

int cdecl Excel(
   int xlfn,
   int count,
   const CXlOper* pxlo,
    ...
);
int cdecl Excel(
   int xlfn,
   int count,
   const XLOPER4* pxlo4,
    ...
);
int cdecl Excel(
   int xlfn,
   int count,
   const XLOPER12* pxlo12,
    ...
);
int cdecl Excel(
   int xlfn,
   int count,
   const CXlOper*[] array_xlo
);
int cdecl Excel(
   int xlfn,
   int count,
   const XLOPER4*[] array_xlo4
);
int cdecl Excel(
   int xlfn,
   int count,
   const XLOPER12*[] array_xlo12
);

Parameters

xlfn

The Excel built-in function number. See Excel built-in function numbers for a list of values.

count

The number of arguments being passed to Excel.
pxlo

A pointer to an initialized CXlOper object.

...

The remaining count-1 arguments to the function should be of a the same type as the first argument.

pxlo4

A pointer to an initialized XLOPER4 structure.

pxlo12

A pointer to an initialized XLOPER12 structure.

array_xlo

A pointer to an array of count initialized CXlOper pointers.

array_xlo4

A pointer to an array of count initialized XLOPER4 pointers.

array_xlo12

A pointer to an array of count initialized XLOPER12 pointers.

Return Value

The result of the SDK call-back. xlretSuccess (0) indicates success. Other values indicate failure. A full list of return values can be found under Error Codes.

Remarks

This function can be used to call an Excel built-in function via the Microsoft Excel SDK. Details of SDK calls and their arguments can be found in the Microsoft Excel 4 Function Reference.

The result of the call will be put in the object which made it. The CXlOper will be marked for special memory clean-up, since the data returned is owned by Excel. If you have no interest in the value returned by Excel, use CXllApp::Excel() instead.

CXlFuncs & CXlMacros

Most Excel worksheet and macro functions can be found, as ready-wrapped C++ methods, in the CXlFuncs and CXlMacros classes respectively.

Example

CXlOper::Excel() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXllApp::Excel() | Error Values | CXlFuncs class | CXlMacros class | Excel built-in function numbers | Calling an Excel built-in function from your add-in


CXlOper::Format

Fill the CXlOper with a formatted string (like sprintf() and CString::Format())

BOOL Format(
   const char* lpszFormat,
    ...
);
BOOL Format(
   const wchar_t* lpwszFormat,
    ...
);
BOOL Format(
   UINT idFormat,
    ...
);

Parameters

lpszFormat

A formatting string, exactly like those used by sprintf.
...

The values to be substituted into the output string in place of the tokens in the template string.
lpwszFormat

A formatting string, exactly like those used by sprintf.
idFormat

The resource ID of a formatting string, exactly like those used by sprintf.

Return Value

The function always returns FALSE;

Remarks

The Format function places a string into the CXlOper which calls it. The string is formatted using the template string in exactly the same way as sprintf(). For example:

CXlOper xloResult;
xloResult.Format("Result code %d", rc);

Examples

CXlOper::GetDims() Example | CXlOper::AllocArray() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::FreeArray

Releases the resources of an array's items

void FreeArray( );

Remarks

Release the memory assigned for the items of an array.

Note: The framework will call this function as required. All memory used by CXlOper objects is automatically released (by one means or another). You never actually need to call this function; you may choose to do so in order to free up memory while an object is still in scope, in order to save heap space.

Note Note:

This method is deprecated. Use Clear instead.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::FromBool

Assigns a boolean value and data type to the CXlOper

void FromBool(
   bool boolVal
);

Parameters

boolVal

Value to be applied to the CXlOper.

Remarks

This function assigns the value of boolVal to the CXlOper, and sets the type of the CXlOper to be xltypeBool.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::FromDouble

Assigns an floating-point numeric value and data type to the CXlOper

void FromDouble(
   double d
);

Parameters

d

Value to be applied to the CXlOper.

Remarks

This function assigns the value of d to the CXlOper, and sets the type of the CXlOper to be xltypeNum.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::FromDoubleArray

Assigns the CXlOper to be an array of double's, and copies values into the array

const CXlOper& FromDoubleArray(
   const double* pd,
   size_t cRows
);
const CXlOper& FromDoubleArray(
   const double* pd,
   size_t cRows,
   size_t cCols,
   BOOL bByRows = FALSE
);
const CXlOper& FromDoubleArray(
   const double* const* apd,
   size_t cRows,
   size_t cCols,
   BOOL bByRows = FALSE
);

Parameters

pd

An array of double's, containing either cRows items, or (cRows x cCols) items, depending on the function variant used. For the latter type, the values should be arranged in the order specified by the bByRows parameter.
cRows

The number of rows contained in the supplied array of doubles.
cCols

The number of columns contained in the supplied array of doubles.
bByRows

Storage order of arrays of double's. If TRUE, then values in the same row are stored contiguously, otherwise values in the same column are assumed to be stored contiguously.
apd

An array of pointers to double, containing either cRows arrays each of size cCols, or cCols arrays each of size cRows, depending on the order specified by the bByRows parameter.

Remarks

This function sets the type of the CXlOper to be an array, allocates space for the array of doubles provided and sets the values into the CXlOper.

The method will throw an exception of type CXlEmptyArrayException if the supplied array is empty, or of type CXlArrayTooLargeException if the array is too large.

Example

MyDaysInMonth Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::FromError

Assigns an error value and data type to the CXlOper

void FromError(
   XlErrorType xlerr
);

Parameters

xlerr

Value to be applied to the CXlOper. See also Error Values for a description of error values.

Remarks

This function assigns the value of xlerr to the CXlOper, and sets the type of the CXlOper to be xltypeErr.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::FromInt

Assigns a single integer to the CXlOper

void FromInt(
   int i
);

Parameters

i

Integer value to be applied to the CXlOper.

Remarks

This function assigns the value i to the CXlOper, and sets the type of the CXlOper to be xltypeInt. This data type is only normally used as an argument to SDK calls.

Examples

CXlOper::GetWidth() Example | CXlOper::GetHeight() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::FromLongArray

Assigns the CXlOper to be an array of double's wih integer values, and copies values into the array

const CXlOper& FromLongArray(
   const long* pl,
   size_t cRows
);
const CXlOper& FromLongArray(
   const long* pl,
   size_t cRows,
   size_t cCols,
   BOOL bByRows = FALSE
);
const CXlOper& FromLongArray(
   const long* const* apl,
   size_t cRows,
   size_t cCols,
   BOOL bByRows = FALSE
);

Parameters

pl

An array of long's, containing either cRows items, or (cRows x cCols) items, depending on the function variant used. For the latter type, the values should be arranged in the order specified by the bByRows parameter.

cRows

The number of rows contained in the supplied array of longs.
cCols

The number of columns contained in the supplied array of longs.
bByRows

Storage order of arrays of long's. If TRUE, then values in the same row are stored contiguously, otherwise values in the same column are assumed to be stored contiguously.

apl

An array of pointers to long, containing either cRows arrays each of size cCols, or cCols arrays each of size cRows, depending on the order specified by the bByRows parameter.

Remarks

This function sets the type of the CXlOper to be an array, allocates space for the array of longs provided and sets the values into the CXlOper. Each integer value is converted to a double.

The method will throw an exception of type CXlEmptyArrayException if the supplied array is empty, or of type CXlArrayTooLargeException if the array is too large.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::FromMatrix

Assigns a 2-dimensional array of numbers, booleans or strings to the CXlOper

template< class T >
BOOL FromMatrix(
   const ple::imtx<T>& mat1,
   long lLBound1 = 0,
   long lLBound2 = 0,
   BOOL toBoolean = FALSE
);
template< class T >
BOOL FromMatrix(
   const xlp::matrix<T>& mat2,
   long lLBound1 = 0,
   long lLBound2 = 0,
   BOOL toBoolean = FALSE
);

Parameters

mat1

2-dimensional array of data, contained in an object which supports the imtx interface.

The following types for T are directly supported:

  • bool
  • long
  • unsigned long
  • int
  • unsigned int
  • short
  • unsigned short
  • double
  • float
  • CString
  • CStringA
  • CStringW
  • std::string
  • std::wstring
Any other type is treated as an enumerated type, and converted first to long and then to a number.

lLBound1

Lower bound of the rows of data in the matrix. The first lLBound1 rows of input will be ignored.
lLBound2

Lower bound of the columns of data in the matrix. The first lLBound2 columns of input will be ignored.
toBoolean

If TRUE, then the resulting Excel array will contain boolean values instead of numbers.
mat2

2-dimensional array of data.

The data types supported are as for mat1.

Return Value

Returns TRUE if the function succeeded, FALSE if it failed.

Remarks

This function sets the type of the CXlOper to be an array, allocates space for the matrix of numbers or strings provided and sets the values into the CXlOper.

The method will return FALSE if the size of the array is 0 or if it is too large.

Note Note:

This method is deprecated. Use FromMatrix2 instead.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::operator =


CXlOper::FromMatrix2

Assigns a 2-dimensional array of numbers, booleans or strings to the CXlOper

template< class T >
const CXlOper& FromMatrix2(
   const ple::imtx<T>& mat1,
   size_t lLBound1 = 0,
   size_t lLBound2 = 0,
   bool toBoolean = FALSE
);

Parameters

mat1

2-dimensional array of data, contained in an object which supports the imtx interface.

The following types for T are directly supported:

  • bool
  • long
  • unsigned long
  • int
  • unsigned int
  • short
  • unsigned short
  • double
  • float
  • CString
  • CStringA
  • CStringW
  • std::string
  • std::wstring
Any other type is treated as an enumerated type, and converted first to long and then to a number.

lLBound1

Lower bound of the rows of data in the matrix. The first lLBound1 rows of input will be ignored.

lLBound2

Lower bound of the columns of data in the matrix. The first lLBound2 columns of input will be ignored.

toBoolean

If TRUE, then the resulting Excel array will contain boolean values instead of numbers.

Remarks

This function sets the type of the CXlOper to be an array, allocates space for the matrix of numbers or strings provided and sets the values into the CXlOper.

The method will throw an exception of type CXlEmptyArrayException if the supplied array is empty, or of type CXlArrayTooLargeException if the array is too large.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::operator =


CXlOper::FromMissing

Sets the CXlOper to be a missing argument

void FromMissing( );

Remarks

This function sets the type of the CXlOper to be xltypeMissing. This data type is only normally used as an argument to SDK calls.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::FromMRef

Assigns multiple range references to the CXlOper

const CXlOper& FromMRef(
   const CXlRef* axlr,
   int cxlr,
   DWORD idSheet
);
const CXlOper& FromMRef(
   const CXlRef* axlr,
   int cxlr,
   const char* pszSheetName
);
const CXlOper& FromMRef(
   const CXlRef* axlr,
   int cxlr,
   const wchar_t* wpszSheetName
);

Parameters

axlr

An array of CXlRef single range references to be applied to the CXlOper.
cxlr

The size of the axlr array.
idSheet

The id of the sheet containing the references in axlr.
pszSheetName

The name of the sheet containing the references in axlr.
wpszSheetName

The name of the sheet containing the references in axlr.

Remarks

This function assigns the cell references contained in axlr on the indicated sheet to the CXlOper, and sets the type of the CXlOper to be xltypeRef.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::FromNil

Sets the CXlOper to be an empty argument

void FromNil( );

Remarks

This function sets the type of the CXlOper to be xltypeNil. This data type is only normally used as an argument to SDK calls.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::FromNumericMatrix

Assigns a 2-dimensional array of numbers to the CXlOper

template< class T >
const CXlOper& FromNumericMatrix(
   const ple::imtx<T>& mat,
   size_t lLBound1 = 0,
   size_t lLBound2 = 0
);

Parameters

mat

2-dimensional array of data, contained in an object which supports the imtx interface.

The following types for T are directly supported:

  • long
  • unsigned long
  • int
  • unsigned int
  • short
  • unsigned short
  • double
  • float
This template function will fail to compile for a matrix whose members cannot be cast to double.

lLBound1

Lower bound of the rows of data in the matrix. The first lLBound1 rows of input will be ignored.

lLBound2

Lower bound of the columns of data in the matrix. The first lLBound2 columns of input will be ignored.

Remarks

This function sets the type of the CXlOper to be a two-dimensional array with the same number of columns and rows as the input matrix, allocates space for the numbers provided and sets the values into the CXlOper.

Note that this method ensures that all integer numeric types are returned to Excel as floating point numbers. To return integer types as boolean values, use CXlOper::FromMatrix2().

The method will throw an exception of type CXlEmptyArrayException if the supplied array is empty, or of type CXlArrayTooLargeException if the array is too large.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::operator = | CXlOper::CXlOper | CXlOper::FromNumericVector2


CXlOper::FromNumericVector

Assigns a 1-dimensional array of numbers to the CXlOper

template< class T >
BOOL FromNumericVector(
   const std::vector<T>& vec,
   BOOL bRow = FALSE,
   long lLBound = 0
);

Parameters

vec

1-dimensional array of numeric data.

The following types for T are directly supported:

  • long
  • unsigned long
  • int
  • unsigned int
  • short
  • unsigned short
  • double
  • float
This template function will fail to compile for a vector whose members cannot be cast to double.

bRow

If TRUE, then the vector created will be a row; otherwise the vector will be a column.
lLBound

The lower bound of "interesting" inputs. The first lLBound items in the input vector will be ignored.

Return Value

Returns TRUE if the function succeeded, FALSE if it failed.

Remarks

This function sets the type of the CXlOper to be an array with a single column or row, allocates space for the vector of numbers provided and sets the values into the CXlOper.

Note that this method ensures that all integer numeric types are returned to Excel as floating point numbers. To return integer types as boolean values, use CXlOper::FromVector2().

The method will fail and return FALSE if the size of the vector is 0 or if it is too large.

Note Note:

This method is deprecated. Use FromNumericVector2 instead.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::operator = | CXlOper::CXlOper | CXlOper::FromVector2


CXlOper::FromNumericVector2

Assigns a 1-dimensional array of numbers to the CXlOper

template< class T >
const CXlOper& FromNumericVector2(
   const std::vector<T>& vec,
   bool bRow = FALSE,
   size_t lLBound = 0
);

Parameters

vec

1-dimensional array of numeric data.

The following types for T are directly supported:

  • long
  • unsigned long
  • int
  • unsigned int
  • short
  • unsigned short
  • double
  • float
This template function will fail to compile for a vector whose members cannot be cast to double.

bRow

If TRUE, then the vector created will be a row; otherwise the vector will be a column.

lLBound

The lower bound of "interesting" inputs. The first lLBound items in the input vector will be ignored.

Remarks

This function sets the type of the CXlOper to be an array with a single column or row, allocates space for the vector of numbers provided and sets the values into the CXlOper.

Note that this method ensures that all integer numeric types are returned to Excel as floating point numbers. To return integer types as boolean values, use CXlOper::FromVector().

The method will throw an exception of type CXlEmptyArrayException if the supplied array is empty, or of type CXlArrayTooLargeException if the array is too large.

Example

CXlOper::FromNumericVector2() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::operator = | CXlOper::CXlOper | CXlOper::FromVector2


CXlOper::FromSRef

Assigns a single range reference to the CXlOper

const CXlOper& FromSRef(
   const CXlRef& xlr,
   bool clear
);

Parameters

xlr

Range reference to be applied to the CXlOper.
clear

If clear is false, then the current contents of the CXlOper will not be destroyed. Since this may cause memory leaks, it should be used with care

Remarks

This function assigns the range reference contained in xlr to the CXlOper, and sets the type of the CXlOper to be xltypeSRef.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::FromString

Assigns a string value and data type to the CXlOper

void FromString(
   const char* psz
);
void FromString(
   const std::string& str
);
void FromString(
   const wchar_t* wpsz
);
void FromString(
   const std::wstring& wstr
);
void FromString(
   const CXlStringArg& strarg
);

Parameters

psz

Value to be applied to the CXlOper. Note that under Excel 2007 and above, the string will be converted to Unicode.

str

STL ASCII string to be applied to the CXlOper. Note that under Excel 2007 and above, the string will be converted to Unicode.

wpsz

A null-terminated Unicode string which will be copied to the CXlOper. Note that under Excel 2003 and below, the string will be converted to a multibyte character ASCII string, and limited to 255 bytes.

wstr

A reference to an STL Unicode string which will be copied to the CXlOper. Note that under Excel 2003 and below, the string will be converted to a multibyte character ASCII string, and limited to 255 bytes.

strarg

A reference to a string argument type passed from Excel, which may contain an 8-bit string or a 16-bit string.

Remarks

This function assigns the supplied string value to the CXlOper, and sets the type of the CXlOper to be xltypeStr.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::FromVector

Assigns a 1-dimensional array of numbers, booleans or strings to the CXlOper

template< class T >
BOOL FromVector(
   const std::vector<T>& dvec,
   BOOL bRow = FALSE,
   size_t lLBound = 0,
   BOOL toBoolean = FALSE
);

Parameters

dvec

1-dimensional array of data.

The following types for T are directly supported:

  • bool
  • long
  • unsigned long
  • int
  • unsigned int
  • short
  • unsigned short
  • double
  • float
  • CString
  • CStringA
  • CStringW
  • std::string
  • std::wstring
Any other type is treated as an enumerated type, and converted first to long and then to a number.

bRow

If TRUE, then the vector created will be a row; otherwise the vector will be a column.
lLBound

The lower bound of "interesting" inputs. The first lLBound items in the input vector will be ignored.
toBoolean

If TRUE, then the resulting Excel array will contain boolean values instead of numbers.

Return Value

Returns TRUE if the function succeeded, FALSE if it failed.

Remarks

This function sets the type of the CXlOper to be an array with a single column or row, allocates space for the vector of doubles, booleans or strings provided and sets the values into the CXlOper.

Note that integer numeric types are returned to Excel as boolean values. To return integer types as numbers, use CXlOper::FromNumericVector2().

The method will fail and return FALSE if the size of the vector is 0 or if it is too large.

Note Note:

This method is deprecated. Use FromVector2 instead.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::operator = | CXlOper::CXlOper | CXlOper::FromNumericVector


CXlOper::FromVector2

Assigns a 1-dimensional array of numbers, booleans or strings to the CXlOper

template< class T >
const CXlOper& FromVector2(
   const std::vector<T>& dvec,
   bool bRow = FALSE,
   size_t lLBound = 0,
   bool toBoolean = FALSE
);

Parameters

dvec

1-dimensional array of data.

The following types for T are directly supported:

  • bool
  • long
  • unsigned long
  • int
  • unsigned int
  • short
  • unsigned short
  • double
  • float
  • CString
  • CStringA
  • CStringW
  • std::string
  • std::wstring
Any other type is treated as an enumerated type, and converted first to long and then to a number.

bRow

If true, then the vector created will be a row; otherwise the vector will be a column.

lLBound

The lower bound of "interesting" inputs. The first lLBound items in the input vector will be ignored.

toBoolean

If true, then the resulting Excel array will contain boolean values instead of numbers. (If T is a string, then all values will be false.)

Remarks

This function sets the type of the CXlOper to be an array with a single column or row, allocates space for the vector of doubles, booleans or strings provided and sets the values into the CXlOper.

This function is called by the CXlOper(std::vector<...> vec) constructors.

Note that integer numeric types are returned to Excel as boolean values. To return integer types as numbers, use CXlOper::FromNumericVector2().

The method will throw an exception of type CXlEmptyArrayException if the supplied array is empty, or of type CXlArrayTooLargeException if the array is too large.

Example

CXlOper::FromVector2() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::operator = | CXlOper::CXlOper | CXlOper::FromNumericVector2


CXlOper::GetActiveCell

Creates a reference to the active cell

BOOL GetActiveCell( );

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if there is no current cell, or if the function cannot be run in Excel at this time.

Remarks

This function will create a reference to the currently active cell. The reference can then be used to access the contents of the cell, for example with the methods SetValue() and Coerce(). The function will fail if the address is not found.

This function can only be called from macro functions. It will always fail if called from worksheet functions.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetActiveCell() | CXlOper::MakeRef()


CXlOper::GetCaller

Retrieve a reference to the cell or cells that called the add-in function

int GetCaller(
   BOOL bFullRef
);

Parameters

bFullRef

If bFullRef is FALSE (the default value), then only a local reference will be placed in the CXlOper. This will be of type xltypeSRef, and will not contain a sheet ID. If bFullRef is TRUE, then an absolute reference will be retrieved. This will be of type xltypeRef, and will contain a sheet ID.

Return Value

The result of the SDK call-back. xlretSuccess (0) indicates success. Other values indicate failure. A full list of return values can be found in Error Codes.

Remarks

GetCaller() tells you which cell (or cells) the add-in function was called from. It fills the CXlOper object with a reference to the cell or cells that called the add-in function.

If the current function was not called from a cell (or cells) then the object will not contain a reference. For example, the function may have been called from a button or a menu, or it may have been called by an event handler such as OnCalculate(). The table below shows the results of using GetCaller() in different situations.

Called from | bFullRef | Result type | Result contents
Worksheet cell(s) | FALSE | xltypeSRef | Local range reference, excluding sheet ID
Menu FALSE xltypeMulti Array of 4 numbers, as follows:
1 | Index of item within menu
2 | Index of menu in menu bar
3 | Menu bar number (Excel application menu = 10)
4 | 0
Button | FALSE | xltypeStr | String containing button name
Event handler | FALSE | xltypeErr | xlerrRef
Worksheet cell(s) | TRUE | xltypeRef | Absolute range reference, including sheet ID
Menu | TRUE | Function fails | N/A
Button | TRUE | Function fails | N/A
Event handler | TRUE | Function fails | N/A

It is therefore advisable to check that the result is a reference, by calling CXlOper::IsRef, as in the following code:

CopyC++
CXlOper xloCaller;
if ((xloCaller.GetCaller() != 0) || !xloCaller.IsRef())
{
    // Fail
}

Example

CXlOper::GetCaller() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXllApp::GetCallerDims() | CXlRef


CXlOper::GetCount

Returns the number of cells in an array

long GetCount( ) const;

Return Value

This function returns the total number of cells contained in an CXlOper.

Example

CXlOper::operator [] Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::GetCount2

Returns the number of cells in an array

long long GetCount2( ) const;

Return Value

This function returns the total number of cells contained in an CXlOper.

Example

CXlOper::GetCount2() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::GetDims

Gets the number of rows and columns in an array

void GetDims(
   USHORT& usRows,
   USHORT& usColumns,
   BOOL bArrayOnly = FALSE
) const;
void GetDims(
   size_t& szRows,
   size_t& szColumns,
   BOOL bArrayOnly = FALSE
) const;

Parameters

usRows

Reference to a variable which will contain the number of rows in the array.
usColumns

Reference to a variable that will contain the number of columns in the array.
bArrayOnly

If the bArrayOnly parameter is true, then the function asserts if the CXlOper does not contain an array; if bArrayOnly is false, then the function returns 1 for the number of rows and columns of a non-array CXlOper.
szRows

Reference to a variable which will contain the number of rows in the array.
szColumns

Reference to a variable that will contain the number of columns in the array.

Remarks

This function gets the height and width of an array.

Examples

CXlOper::GetDims() Example | MySum Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::GetFormula

Get the formula in the referenced cell, in local format

BOOL GetFormula(
   CString& strFormula,
   BOOL& bIsArray,
   BOOL bA1 = TRUE
) const;

Parameters

strFormula

String buffer which will be filled with the formula. The formula will be in local form, as it appears in the Excel formula bar.
bIsArray

Will be set to TRUE if the cell is part of an array; to FALSE if it is not.
bA1

If TRUE, then the formula will contain references in A1 format; if FALSE, the references will be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, or if it cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions, or from worksheet functions that have been marked as "Defer recalculation". It will always fail if called from worksheet functions that have not been marked as "Defer recalculation".

International considerations

Be aware when inspecting a formula retrieved using this method that the formula is formatted for the current language settings. For example, arguments in English are separated by commas; in German, semi-colons are used.

You can use CXllApp::GetInternational to get the current list separators and other punctuation characters.

Alternatively, you can use CXlOper::GetFormulaIntl to apply formulae that work in all languages.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetFormula() | CXlOper::ConvertFormula() | CXllApp::GetInternational() | CXlOper::GetFormulaIntl()


CXlOper::GetFormulaA

Get the formula in the referenced cell, in local format

BOOL GetFormulaA(
   CStringA& strFormula,
   BOOL& bIsArray,
   BOOL bA1 = TRUE
) const;

Parameters

strFormula

String buffer which will be filled with the formula. The formula will be in local form, as it appears in the Excel formula bar.
bIsArray

Will be set to TRUE if the cell is part of an array; to FALSE if it is not.
bA1

If TRUE, then the formula will contain references in A1 format; if FALSE, the references will be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, or if it cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions, or from worksheet functions that have been marked as "Defer recalculation". It will always fail if called from worksheet functions that have not been marked as "Defer recalculation".

International considerations

Be aware when inspecting a formula retrieved using this method that the formula is formatted for the current language settings. For example, arguments in English are separated by commas; in German, semi-colons are used.

You can use CXllApp::GetInternational to get the current list separators and other punctuation characters.

Alternatively, you can use CXlOper::GetFormulaIntl to apply formulae that work in all languages.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetFormula() | CXlOper::ConvertFormula() | CXllApp::GetInternational() | CXlOper::GetFormulaIntl()


CXlOper::GetFormulaIntl

Get the formula in the referenced cell, in English

BOOL GetFormulaIntl(
   CString& strFormula,
   BOOL& bIsArray,
   BOOL bA1 = TRUE
) const;

Parameters

strFormula

String buffer which will be filled with the formula. The formula will be in English and will use US English settings for punctuation.
bIsArray

Will be set to TRUE if the cell is part of an array; to FALSE if it is not.
bA1

If TRUE, then the formula will contain references in A1 format; if FALSE, the references will be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, or if it cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions, or from worksheet functions that have been marked as "Defer recalculation". It will always fail if called from worksheet functions that have not been marked as "Defer recalculation".

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetFormulaIntl() | CXlOper::ConvertFormulaIntl() | CXlOper::GetFormula()


CXlOper::GetFormulaIntlA

Get the formula in the referenced cell, in English

BOOL GetFormulaIntlA(
   CStringA& strFormula,
   BOOL& bIsArray,
   BOOL bA1 = TRUE
) const;

Parameters

strFormula

String buffer which will be filled with the formula. The formula will be in English and will use US English settings for punctuation.
bIsArray

Will be set to TRUE if the cell is part of an array; to FALSE if it is not.
bA1

If TRUE, then the formula will contain references in A1 format; if FALSE, the references will be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, or if it cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions, or from worksheet functions that have been marked as "Defer recalculation". It will always fail if called from worksheet functions that have not been marked as "Defer recalculation".

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetFormulaIntl() | CXlOper::ConvertFormulaIntl() | CXlOper::GetFormula()


CXlOper::GetFormulaIntlW

Get the formula in the referenced cell, in English

BOOL GetFormulaIntlW(
   CStringW& strFormula,
   BOOL& bIsArray,
   BOOL bA1 = TRUE
) const;

Parameters

strFormula

String buffer which will be filled with the formula. The formula will be in English and will use US English settings for punctuation.
bIsArray

Will be set to TRUE if the cell is part of an array; to FALSE if it is not.
bA1

If TRUE, then the formula will contain references in A1 format; if FALSE, the references will be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, or if it cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions, or from worksheet functions that have been marked as "Defer recalculation". It will always fail if called from worksheet functions that have not been marked as "Defer recalculation".

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetFormulaIntl() | CXlOper::ConvertFormulaIntl() | CXlOper::GetFormula()


CXlOper::GetFormulaW

Get the formula in the referenced cell, in local format

BOOL GetFormulaW(
   CStringW& strFormula,
   BOOL& bIsArray,
   BOOL bA1 = TRUE
) const;

Parameters

strFormula

String buffer which will be filled with the formula. The formula will be in local form, as it appears in the Excel formula bar.
bIsArray

Will be set to TRUE if the cell is part of an array; to FALSE if it is not.
bA1

If TRUE, then the formula will contain references in A1 format; if FALSE, the references will be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, or if it cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions, or from worksheet functions that have been marked as "Defer recalculation". It will always fail if called from worksheet functions that have not been marked as "Defer recalculation".

International considerations

Be aware when inspecting a formula retrieved using this method that the formula is formatted for the current language settings. For example, arguments in English are separated by commas; in German, semi-colons are used.

You can use CXllApp::GetInternational to get the current list separators and other punctuation characters.

Alternatively, you can use CXlOper::GetFormulaIntl to apply formulae that work in all languages.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetFormula() | CXlOper::ConvertFormula() | CXllApp::GetInternational() | CXlOper::GetFormulaIntl()


CXlOper::GetHeight

Returns the number of rows in an array

USHORT GetHeight(
   BOOL bArrayOnly = FALSE
) const;

Parameters

bArrayOnly

If the bArrayOnly parameter is TRUE, then the function asserts if the CXlOper does not contain an array; if bArrayOnly is FALSE, then the function returns 1 for the number of rows of a non-array CXlOper.

Return Value

This function returns the height of an array.

Example

CXlOper::GetHeight() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::GetHeight2

Returns the number of rows in an array

int GetHeight2(
   BOOL bArrayOnly = FALSE
) const;

Parameters

bArrayOnly

If the bArrayOnly parameter is TRUE, then the function asserts if the CXlOper does not contain an array; if bArrayOnly is FALSE, then the function returns 1 for the number of rows of a non-array CXlOper.

Return Value

This function returns the height of an array.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::GetLongString

Read a long string (of up to 1024 characters) from a single cell

BOOL GetLongString(
   CString& strText
) const;

Parameters

strText

If the function succeeds, this will contain the entire string contained in the target cell.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference to a single cell, or if it cannot be run in Excel at this time.

Remarks

This function retrieves the entire string contained in a cell, even if the string contains more than 255 characters. The calling object must contain a reference to a single cell.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::Coerce()


CXlOper::GetLongStringA

Read a long string (of up to 1024 characters) from a single cell

BOOL GetLongStringA(
   CStringA& strText
) const;

Parameters

strText

If the function succeeds, this will contain the entire string contained in the target cell.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference to a single cell, or if it cannot be run in Excel at this time.

Remarks

This function retrieves the entire string contained in a cell, even if the string contains more than 255 characters. The calling object must contain a reference to a single cell.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::Coerce()


CXlOper::GetLongStringW

Read a long string (of up to 1024 characters) from a single cell

BOOL GetLongStringW(
   CStringW& strText
) const;

Parameters

strText

If the function succeeds, this will contain the entire string contained in the target cell.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference to a single cell, or if it cannot be run in Excel at this time.

Remarks

This function retrieves the entire string contained in a cell, even if the string contains more than 255 characters. The calling object must contain a reference to a single cell.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::Coerce()


CXlOper::GetRef

Returns a copy of the first (or only) single reference in a single or multiple range reference

CXlRef GetRef( ) const;

Return Value

Returns a single range reference, by value or by reference. If the CXlOper contains a multiple reference, then the function will return the first single reference it contains.

Remarks

The function will throw an exception of type CXlBadOperTypeException if the object does not contain a single or multiple reference. GetRef() should be used only if IsRef() returns TRUE, as in:

if ( xlo.IsRef() )
{
    cRows = xlo.GetRef().Height();
}

Breaking change

Under XLL+ version 5 and below, this method returned a reference to the actual CXlRef contained within the CXlOper, which could then be written to directly. In order to support Excel 2007 as well as earlier versions of Excel, this functionality has had to be changed.

The method now returns a copy of the CXlRef contained in the CXlOper; in order to change its value, you must call SetRef to apply any changes. Thus, if your existing code is:

xloRef.GetRef().MoveBy(0, 1);

You will need to change it to:

CXlRef xlr = xloRef.GetRef();
xlr.MoveBy(0, 1);
xloRef.SetRef(xlr);

Alternatively, you can use the new short-hand function:

xloRef.MoveRefBy(0, 1);

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetRef() | CXlOper::GetRefCount() | CXlOper::GetRefItem()


CXlOper::GetRefCount

Returns the number of references in a multiple reference

WORD GetRefCount( ) const;

Return Value

Returns the number of references in a single or multiple reference. If the CXlOper contains a single reference the function will return 1.

Remarks

For a CXlOper that contains a reference (either single or multiple) this function returns number of references.

The function throws an exception of type CXlBadOperTypeException if the object does not contain a single or multiple reference.

Example

MyAddress Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetRefItem()


CXlOper::GetRefItem

Returns a copy of one of the single references in a multiple reference

CXlRef GetRefItem(
   WORD wItem
) const;

Parameters

wItem

The index of the range to retrieve. The first item is at position 0.

Return Value

Returns a copy of one of the single ranges in a multiple reference. If the CXlOper contains a single reference, and wItem is 0, then the function will return the single reference itself.

Remarks

The function will throw an exception of type CXlBadOperTypeException if the object does not contain a single or multiple reference, or of type CXlOutOfRangeException if wItem is out of range.

Breaking change

Under XLL+ version 5 and below, this method returned a reference to the actual CXlRef contained within the CXlOper, which could then be written to directly. In order to support Excel 2007 as well as earlier versions of Excel, this functionality has had to be changed.

The method now returns a copy of the CXlRef contained in the CXlOper; in order to change its value, you must call SetRefItem to apply any changes. Thus, if your existing code is:

xloRef.GetRefItem(0).MoveBy(0, 1);

You will need to change it to:

CXlRef xlr = xloRef.GetRefItem(0);
xlr.MoveBy(0, 1);
xloRef.SetRefItem(0, xlr);

Alternatively, you can use the new short-hand function:

xloRef.MoveRefBy(0, 1);

Examples

CXlOper::GetCaller() Example | MyAddress Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetRefCount() | CXlOper::SetRefItem()


CXlOper::GetSheetId

Returns the SheetId of a CXlOper containing a reference

DWORD GetSheetId( ) const;

Return Value

32-bit integer value representing the unique identifier assigned to the worksheet by Excel. This value remains the same throughout the life of the worksheet object. It is reassigned each time the spreadsheet is opened.

Throws an exception of type CXlBadOperTypeException if the CXlOper is not a reference.

Remarks

For a CXlOper that contains a reference (either single or multiple) this function returns the SheetId.

The function throws an exception of type CXlBadOperTypeException if the object does not contain a single or multiple reference.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXllApp::GetSheetId()


CXlOper::GetSheetName

Returns the SheetName of a CXlOper containing a reference

CString GetSheetName( ) const;

Return Value

Worksheet name of the worksheet containing the cell or cells referenced.

Remarks

For a CXlOper that contains a reference (either single or multiple) this function returns the sheet name.

The function throws an exception of type CXlBadOperTypeException if the object does not contain a single or multiple reference.

Example

MyAddress Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXllApp::GetSheetName()


CXlOper::GetSheetNameA

Returns the SheetName of a CXlOper containing a reference

CStringA GetSheetNameA( ) const;

Return Value

Worksheet name of the worksheet containing the cell or cells referenced.

Remarks

For a CXlOper that contains a reference (either single or multiple) this function returns the sheet name.

The function throws an exception of type CXlBadOperTypeException if the object does not contain a single or multiple reference.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXllApp::GetSheetName()


CXlOper::GetSheetNameW

Returns the SheetName of a CXlOper containing a reference

CStringW GetSheetNameW( ) const;

Return Value

Worksheet name of the worksheet containing the cell or cells referenced.

Remarks

For a CXlOper that contains a reference (either single or multiple) this function returns the sheet name.

The function throws an exception of type CXlBadOperTypeException if the object does not contain a single or multiple reference.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXllApp::GetSheetName()


CXlOper::GetVectorCount

Returns the number of cells in an array

USHORT GetVectorCount( ) const;

Return Value

This function returns the total number of cells contained in an CXlOper.

Remarks

Use this function with VectorCell() to iterate the cells in a vector.

If the CXlOper is not a vector (i.e. contains more than row and more than column) then the return value may be subject to overflow (because it is greater than 2^16) and will therefore be unreliable.

Note Note:

This method is deprecated. Use GetVectorCount2 instead.

Example

CXlOper::VectorCell() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::VectorCell() | CXlOper::IsVector()


CXlOper::GetVectorCount2

Returns the number of cells in an array

long GetVectorCount2( ) const;

Return Value

This function returns the total number of cells contained in an CXlOper.

Remarks

Use this function with VectorCell() to iterate the cells in a vector.

If the CXlOper is not a vector (i.e. contains more than row and more than column) then the return value may be subject to overflow (because it is greater than 2^32) and will therefore be unreliable.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::VectorCell() | CXlOper::IsVector()


CXlOper::GetWidth

Returns the number of columns in an array

USHORT GetWidth(
   BOOL bArrayOnly = FALSE
) const;

Parameters

bArrayOnly

If the bArrayOnly parameter is TRUE, then the function asserts if the CXlOper does not contain an array; if bArrayOnly is FALSE, then the function returns 1 for the number of columns of a non-array CXlOper.

Return Value

This function returns the width of an array.

Example

CXlOper::GetWidth() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::GetWidth2

Returns the number of columns in an array

int GetWidth2(
   BOOL bArrayOnly = FALSE
) const;

Parameters

bArrayOnly

If the bArrayOnly parameter is TRUE, then the function asserts if the CXlOper does not contain an array; if bArrayOnly is FALSE, then the function returns 1 for the number of columns of a non-array CXlOper.

Return Value

This function returns the width of an array.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::HandleResult

Ensures that an add-in function result is contained in the calling object

void HandleResult(
   CXlOper* pxloResult
);

Parameters

pxloResult

The return value of an add-in function, or null.

Remarks

This function is called by generated code, and should not normally be used by hand-written code.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::IsArray

Does the CXlOper contain an array?

BOOL IsArray( ) const;

Return Value

Returns TRUE if the CXlOper contains an array, FALSE otherwise.

Examples

CXlOper::IsArray() Example | CXlOper::Cell() Example | CXlOper::ToDoubleArray() Examples

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsOfType() | CXlOper::IsDouble() | CXlOper::IsError() | CXlOper::IsBool() | CXlOper::IsString() | CXlOper::IsEmpty() | CXlOper::IsMissing() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsBool

Does the CXlOper contain a boolean?

BOOL IsBool( ) const;

Return Value

Returns TRUE if the CXlOper contains a boolean value, FALSE otherwise.

Example

CXlOper::IsBool() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsOfType() | CXlOper::IsArray() | CXlOper::IsDouble() | CXlOper::IsError() | CXlOper::IsString() | CXlOper::IsEmpty() | CXlOper::IsMissing() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsDouble

Does the CXlOper contain a double-precision floating point number?

BOOL IsDouble( ) const;

Return Value

Returns TRUE if the CXlOper contains a single floating point value, FALSE otherwise.

Examples

CXlOper::IsDouble() Example | MyDaysInFeb Example | MySum Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsOfType() | CXlOper::IsArray() | CXlOper::IsError() | CXlOper::IsBool() | CXlOper::IsString() | CXlOper::IsEmpty() | CXlOper::IsMissing() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsEmpty

Is the CXlOper empty?

BOOL IsEmpty( ) const;

Return Value

Returns TRUE if the CXlOper is uninitialised, FALSE otherwise.

Example

CXlOper::IsEmpty() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsOfType() | CXlOper::IsArray() | CXlOper::IsDouble() | CXlOper::IsError() | CXlOper::IsBool() | CXlOper::IsString() | CXlOper::IsMissing() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsError

Does the CXlOper contain an error?

BOOL IsError( ) const;

Return Value

Returns TRUE if the CXlOper contains an error value, FALSE otherwise.

Example

CXlOper::IsError() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsOfType() | CXlOper::IsArray() | CXlOper::IsDouble() | CXlOper::IsBool() | CXlOper::IsString() | CXlOper::IsEmpty() | CXlOper::IsMissing() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsInt

Does the CXlOper contain an integer?

BOOL IsInt( ) const;

Return Value

Returns TRUE if the CXlOper contains an integer type, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsOfType() | CXlOper::IsArray() | CXlOper::IsDouble() | CXlOper::IsError() | CXlOper::IsBool() | CXlOper::IsEmpty() | CXlOper::IsMissing() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsMissing

Is the CXlOper missing (i.e. omitted from the caller's argument list)?

BOOL IsMissing( ) const;

Return Value

Returns TRUE if the CXlOper has been omitted from the list of arguments by the caller, FALSE otherwise.

Examples

CXlOper::IsMissing() Example | MyDaysInFeb Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsOfType() | CXlOper::IsArray() | CXlOper::IsDouble() | CXlOper::IsError() | CXlOper::IsBool() | CXlOper::IsString() | CXlOper::IsEmpty() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsMRef

Does the CXlOper contain a multiple reference?

BOOL IsMRef( ) const;

Return Value

Returns TRUE if the CXlOper contains a multiple reference, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsOfType() | CXlOper::IsArray() | CXlOper::IsDouble() | CXlOper::IsError() | CXlOper::IsBool() | CXlOper::IsString() | CXlOper::IsEmpty() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsOfType

Is the CXlOper of the specified type?

BOOL IsOfType(
   WORD xltype
) const;

Parameters

xltype

A xltype value. This should be one of the xltype values listed in CXlOper data types.

Return Value

Returns TRUE if the CXlOper is of the specified type, FALSE if it is of any other type.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsArray() | CXlOper::IsDouble() | CXlOper::IsError() | CXlOper::IsBool() | CXlOper::IsString() | CXlOper::IsEmpty() | CXlOper::IsMissing() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsPresent

Is the CXlOper not missing (i.e. not omitted from the caller's argument list)?

BOOL IsPresent( ) const;

Return Value

Returns TRUE if the CXlOper has not been omitted from the list of arguments by the caller, FALSE otherwise.

Example

CXlOper::IsPresent() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsMissing()


CXlOper::IsRef

Does the CXlOper contain a reference?

BOOL IsRef( ) const;

Return Value

Returns TRUE if the CXlOper contains a single or multiple reference, FALSE otherwise.

Examples

CXlOper::GetCaller() Example | MyAddress Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsOfType() | CXlOper::IsArray() | CXlOper::IsDouble() | CXlOper::IsError() | CXlOper::IsBool() | CXlOper::IsString() | CXlOper::IsEmpty() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsScalar

Does the CXlOper contain a single value?

BOOL IsScalar( ) const;

Return Value

Returns TRUE if the CXlOper contains a single value, FALSE otherwise.

Remarks

This method is equivalent to IsDouble() || IsBool() || IsInt() || IsString().

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsOfType() | CXlOper::IsArray() | CXlOper::IsDouble() | CXlOper::IsError() | CXlOper::IsBool() | CXlOper::IsString() | CXlOper::IsEmpty() | CXlOper::IsMissing() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsSRef

Does the CXlOper contain a single reference?

BOOL IsSRef( ) const;

Return Value

Returns TRUE if the CXlOper contains a single reference, FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsOfType() | CXlOper::IsArray() | CXlOper::IsDouble() | CXlOper::IsError() | CXlOper::IsBool() | CXlOper::IsString() | CXlOper::IsEmpty() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsString

Does the CXlOper contain a string?

BOOL IsString( ) const;

Return Value

Returns TRUE if the CXlOper contains a string value, FALSE otherwise.

Example

CXlOper::IsString() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsOfType() | CXlOper::IsArray() | CXlOper::IsDouble() | CXlOper::IsError() | CXlOper::IsBool() | CXlOper::IsEmpty() | CXlOper::IsMissing() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsValue

Does the CXlOper contain one or more values?

BOOL IsValue( ) const;

Return Value

Returns TRUE if the CXlOper contains one or more values, FALSE otherwise.

Remarks

This method is equivalent to IsScalar() || IsArray().

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::IsOfType() | CXlOper::IsArray() | CXlOper::IsScalar() | CXlOper::IsDouble() | CXlOper::IsError() | CXlOper::IsBool() | CXlOper::IsString() | CXlOper::IsEmpty() | CXlOper::IsMissing() | CXlOper::IsInt() | CXlOper::IsSRef() | CXlOper::IsMRef() | CXlOper::IsRef()


CXlOper::IsVector

Returns TRUE if the CXlOper contains 1 row and/or 1 column

bool IsVector( ) const;

Return Value

This function returns true if the CXlOper contains either a single cell or an array with one column and/or one row. It returns false if the CXlOper contains more than row and more than column, or if it contains a reference.

Remarks

Use this function to determine whether VectorCell() and GetVectorCount() can be used on the CXlOper.

Examples

CXlOper::operator [] Example | CXlOper::VectorCell() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::VectorCell()


CXlOper::MakeRef

Creates a reference from an address

BOOL MakeRef(
   const TCHAR* pszAddress,
   BOOL bA1 = TRUE,
   BOOL bLocal = FALSE
);

Parameters

pszAddress

The address of a cell or range of cells.

This can include a worksheet name, in "[book]sheet" format. If the worksheet name is omitted, the address will be assumed to be in the worksheet of the cell from which the current add-in function was called.

The following addresses are all valid:

[Book1.xls]Sheet2!A2
[Book1.xls]Sheet2!A1:C3
A2

The following address is valid in English only:

[Book1.xls]Sheet2!R1C5

The address can also contain a named range.
bA1

TRUE if the address is in A1 format; FALSE if the address is in R1C1 format.
bLocal

If bLocal is TRUE then the reference will always be external, i.e. it will include a sheet ID and IsMRef() will return TRUE. If bLocal is FALSE then the reference will only be external if it refers to a sheet other than the current sheet. If it refers to the current sheet, then it will not include a sheet ID and IsSRef() will return TRUE.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the address string is not valid for any reason.

Remarks

This function will create a reference from a string address. The reference can then be used to access the contents of the cell, for example with the methods SetValue() and Coerce(). The function will fail if the address is not found.

International considerations

Be aware when creating a reference using this method that the address should be formatted for the current language settings. This has no impact on "A1" style adresses, but "RC" style addresses use different letters in different Excel language versions. For example, "R1C1" in English is "Z1S1" in German.

You can use CXllApp::GetInternational(XlInternationalUpperCaseRowLetter) and CXllApp::GetInternational(XlInternationalUpperCaseColumnLetter) to get the current letters.

Alternatively, you can use CXlOper::MakeRefIntl to create addresses that work in all Excel language versions.

See Using references and Setting formulae in the User Guide for more information.

Example

CXlOper::Coerce() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::MakeRefIntl() | CXlOper::FromMRef() | CXlOper::FromSRef() | CXllApp::MakeSheetName()


CXlOper::MakeRefA

Creates a reference from an address

BOOL MakeRefA(
   const char* pszAddress,
   BOOL bA1 = TRUE,
   BOOL bLocal = FALSE
);

Parameters

pszAddress

The address of a cell or range of cells.

This can include a worksheet name, in "[book]sheet" format. If the worksheet name is omitted, the address will be assumed to be in the worksheet of the cell from which the current add-in function was called.

The following addresses are all valid:

[Book1.xls]Sheet2!A2
[Book1.xls]Sheet2!A1:C3
A2

The following address is valid in English only:

[Book1.xls]Sheet2!R1C5

The address can also contain a named range.
bA1

TRUE if the address is in A1 format; FALSE if the address is in R1C1 format.
bLocal

If bLocal is TRUE then the reference will always be external, i.e. it will include a sheet ID and IsMRef() will return TRUE. If bLocal is FALSE then the reference will only be external if it refers to a sheet other than the current sheet. If it refers to the current sheet, then it will not include a sheet ID and IsSRef() will return TRUE.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the address string is not valid for any reason.

Remarks

This function will create a reference from a string address. The reference can then be used to access the contents of the cell, for example with the methods SetValue() and Coerce(). The function will fail if the address is not found.

International considerations

Be aware when creating a reference using this method that the address should be formatted for the current language settings. This has no impact on "A1" style adresses, but "RC" style addresses use different letters in different Excel language versions. For example, "R1C1" in English is "Z1S1" in German.

You can use CXllApp::GetInternational(XlInternationalUpperCaseRowLetter) and CXllApp::GetInternational(XlInternationalUpperCaseColumnLetter) to get the current letters.

Alternatively, you can use CXlOper::MakeRefIntl to create addresses that work in all Excel language versions.

See Using references and Setting formulae in the User Guide for more information.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::MakeRefIntl() | CXlOper::FromMRef() | CXlOper::FromSRef() | CXllApp::MakeSheetName()


CXlOper::MakeRefIntl

Creates a reference from an address in English

BOOL MakeRefIntl(
   const TCHAR* pszAddress,
   BOOL bA1 = TRUE,
   BOOL bLocal = FALSE
);

Parameters

pszAddress

The address of a cell or range of cells.

This can include a worksheet name, in "[book]sheet" format. If the worksheet name is omitted, the address will be assumed to be in the worksheet of the cell from which the current add-in function was called.

The following addresses are all valid

[Book1.xls]Sheet2!A2
[Book1.xls]Sheet2!A1:C3
[Book1.xls]Sheet2!R1C5
A2

The address can also contain a named range.

Note that if RC style addresses are used, they should always use the letters "R" anc "C" for row and column respectively, e.g.: "R1C1" for cell A1.
bA1

TRUE if the address is in A1 format; FALSE if the address is in R1C1 format.
bLocal

If bLocal is TRUE then the reference will always be external, i.e. it will include a sheet ID and IsMRef() will return TRUE. If bLocal is FALSE then the reference will only be external if it refers to a sheet other than the current sheet. If it refers to the current sheet, then it will not include a sheet ID and IsSRef() will return TRUE.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the address string is not valid for any reason.

Remarks

This function will create a reference from a string address. The reference can then be used to access the contents of the cell, for example with the methods SetValue() and Coerce(). The function will fail if the address is not found.

International considerations

Be aware when creating a reference using this method that the address should be formatted as if for the English language version of Excel. This has no impact on "A1" style adresses, but "RC" style addresses should always use the letters "R" anc "C" for row and column respectively, e.g.: "R1C1" for cell A1.

Alternatively, you can use CXlOper::MakeRef to create addresses for the current Excel language version.

See Using references and Setting formulae in the User Guide for more information.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::MakeRef() | CXlOper::FromMRef() | CXlOper::FromSRef() | CXllApp::MakeSheetName()


CXlOper::MakeRefIntlA

Creates a reference from an address in English

BOOL MakeRefIntlA(
   const char* pszAddress,
   BOOL bA1 = TRUE,
   BOOL bLocal = FALSE
);

Parameters

pszAddress

The address of a cell or range of cells.

This can include a worksheet name, in "[book]sheet" format. If the worksheet name is omitted, the address will be assumed to be in the worksheet of the cell from which the current add-in function was called.

The following addresses are all valid

[Book1.xls]Sheet2!A2
[Book1.xls]Sheet2!A1:C3
[Book1.xls]Sheet2!R1C5
A2

The address can also contain a named range.

Note that if RC style addresses are used, they should always use the letters "R" anc "C" for row and column respectively, e.g.: "R1C1" for cell A1.
bA1

TRUE if the address is in A1 format; FALSE if the address is in R1C1 format.
bLocal

If bLocal is TRUE then the reference will always be external, i.e. it will include a sheet ID and IsMRef() will return TRUE. If bLocal is FALSE then the reference will only be external if it refers to a sheet other than the current sheet. If it refers to the current sheet, then it will not include a sheet ID and IsSRef() will return TRUE.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the address string is not valid for any reason.

Remarks

This function will create a reference from a string address. The reference can then be used to access the contents of the cell, for example with the methods SetValue() and Coerce(). The function will fail if the address is not found.

International considerations

Be aware when creating a reference using this method that the address should be formatted as if for the English language version of Excel. This has no impact on "A1" style adresses, but "RC" style addresses should always use the letters "R" anc "C" for row and column respectively, e.g.: "R1C1" for cell A1.

Alternatively, you can use CXlOper::MakeRef to create addresses for the current Excel language version.

See Using references and Setting formulae in the User Guide for more information.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::MakeRef() | CXlOper::FromMRef() | CXlOper::FromSRef() | CXllApp::MakeSheetName()


CXlOper::MakeRefIntlW

Creates a reference from an address in English

BOOL MakeRefIntlW(
   const wchar_t* pszAddress,
   BOOL bA1 = TRUE,
   BOOL bLocal = FALSE
);

Parameters

pszAddress

The address of a cell or range of cells.

This can include a worksheet name, in "[book]sheet" format. If the worksheet name is omitted, the address will be assumed to be in the worksheet of the cell from which the current add-in function was called.

The following addresses are all valid

[Book1.xls]Sheet2!A2
[Book1.xls]Sheet2!A1:C3
[Book1.xls]Sheet2!R1C5
A2

The address can also contain a named range.

Note that if RC style addresses are used, they should always use the letters "R" anc "C" for row and column respectively, e.g.: "R1C1" for cell A1.
bA1

TRUE if the address is in A1 format; FALSE if the address is in R1C1 format.
bLocal

If bLocal is TRUE then the reference will always be external, i.e. it will include a sheet ID and IsMRef() will return TRUE. If bLocal is FALSE then the reference will only be external if it refers to a sheet other than the current sheet. If it refers to the current sheet, then it will not include a sheet ID and IsSRef() will return TRUE.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the address string is not valid for any reason.

Remarks

This function will create a reference from a string address. The reference can then be used to access the contents of the cell, for example with the methods SetValue() and Coerce(). The function will fail if the address is not found.

International considerations

Be aware when creating a reference using this method that the address should be formatted as if for the English language version of Excel. This has no impact on "A1" style adresses, but "RC" style addresses should always use the letters "R" anc "C" for row and column respectively, e.g.: "R1C1" for cell A1.

Alternatively, you can use CXlOper::MakeRef to create addresses for the current Excel language version.

See Using references and Setting formulae in the User Guide for more information.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::MakeRef() | CXlOper::FromMRef() | CXlOper::FromSRef() | CXllApp::MakeSheetName()


CXlOper::MakeRefW

Creates a reference from an address

BOOL MakeRefW(
   const wchar_t* pszAddress,
   BOOL bA1 = TRUE,
   BOOL bLocal = FALSE
);

Parameters

pszAddress

The address of a cell or range of cells.

This can include a worksheet name, in "[book]sheet" format. If the worksheet name is omitted, the address will be assumed to be in the worksheet of the cell from which the current add-in function was called.

The following addresses are all valid:

[Book1.xls]Sheet2!A2
[Book1.xls]Sheet2!A1:C3
A2

The following address is valid in English only:

[Book1.xls]Sheet2!R1C5

The address can also contain a named range.
bA1

TRUE if the address is in A1 format; FALSE if the address is in R1C1 format.
bLocal

If bLocal is TRUE then the reference will always be external, i.e. it will include a sheet ID and IsMRef() will return TRUE. If bLocal is FALSE then the reference will only be external if it refers to a sheet other than the current sheet. If it refers to the current sheet, then it will not include a sheet ID and IsSRef() will return TRUE.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the address string is not valid for any reason.

Remarks

This function will create a reference from a string address. The reference can then be used to access the contents of the cell, for example with the methods SetValue() and Coerce(). The function will fail if the address is not found.

International considerations

Be aware when creating a reference using this method that the address should be formatted for the current language settings. This has no impact on "A1" style adresses, but "RC" style addresses use different letters in different Excel language versions. For example, "R1C1" in English is "Z1S1" in German.

You can use CXllApp::GetInternational(XlInternationalUpperCaseRowLetter) and CXllApp::GetInternational(XlInternationalUpperCaseColumnLetter) to get the current letters.

Alternatively, you can use CXlOper::MakeRefIntl to create addresses that work in all Excel language versions.

See Using references and Setting formulae in the User Guide for more information.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::MakeRefIntl() | CXlOper::FromMRef() | CXlOper::FromSRef() | CXllApp::MakeSheetName()


CXlOper::MissingArg

Returns a placeholder to send to SDK calls as a missing argument

static const CXlOper& MissingArg( );

Return Value

A reference to a CXlOper instance in static memory, with type xltypeMissing.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::MissingArgP

Returns a placeholder to send to SDK calls as a missing argument

static const CXlOper* MissingArgP( );

Return Value

A pointer to a CXlOper instance in static memory, with type xltypeMissing.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::MoveRefBy

Moves a reference by the specified number of rows and columns

BOOL MoveRefBy(
   long nRows,
   long nCols
);

Parameters

nRows

Number of rows to move by (negative is up, positive is down).
nCols

Number of columns to move by (negative is left, positive is right).

Remarks

The function will throw an exception of type CXlBadOperTypeException if the object does not contain a single or multiple reference.

The function will throw an exception of type CXlOutOfRangeException if the new position would be out of range.

This method is a short-hand for getting a reference, moving it, and setting it. Thus, the following:

xloRef.MoveRefBy(0, 1);

is a short-hand for:

CXlRef xlr = xloRef.GetRef();
xlr.MoveBy(0, 1);
xloRef.SetRef(xlr);

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetRef() | CXlOper::SetRef()


CXlOper::Offset

Returns a reference moved by the specified number of rows and columns

CXlOper Offset(
   long nRows,
   long nCols
) const;

Parameters

nRows

Number of rows to move by (negative is up, positive is down).
nCols

Number of columns to move by (negative is left, positive is right).

Return Value

Returns a new reference, offset from this reference by the specified number of rows and columns. The function will throw an exception if the new reference is not valid.

Remarks

The function will throw an exception of type CXlBadOperTypeException if the object does not contain a single or multiple reference.

The function will throw an exception of type CXlOutOfRangeException if the new position would be out of range.

This method is a short-hand for getting a reference, moving it, and setting it. Thus, the following:

xlo2 = xlo1.Offset(0, 1);

is a short-hand for:

xlo2 = xlo1;
CXlRef xlr = xlo2.GetRef();
xlr.MoveBy(0, 1);
xlo2.SetRef(xlr);

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::Resize() | CXlOper::MoveRefBy()


CXlOper::operator !=

Compare the contents of this CXlOper with another

int operator !=(
   const CXlOper& xlo
) const;

Parameters

xlo

A reference to another CXlOper.

Return Value

Returns TRUE if the value in this object is not equal to that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are compared by type first and then by value. Thus a string containing "123" will not be equal to an integer containing 123.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::operator []

Returns an item from an array

CXlCell operator [](
   size_t szItem = 0
);
CXlConstCell operator [](
   size_t szItem
) const;

Parameters

szItem

The row or column of the required value within the array. The first item is at szItem = 0.

Return Value

This operator returns an object which contains a reference to a cell contained within a single-dimensional array.

The operator is equivalent to a call to VectorCell().

Remarks

If the CXlOper does not contain a one-dimensional array, or if szItem is out of range, then the function will throw an exception of type CXlOutOfRangeException.

Breaking change

Under previous versions of XLL+ (5 and below), this operator returned a reference to a CXlOper type, which was contained within the outer CXlOper. In order to support both Excel 2007 and older versions of Excel, this functionality has had to be changed.

The operator now returns a new class of object, CXlCell or CXlConstCell, which can be used to refer to the cell, but is not itself of type CXlOper.

If your code retained a copy of the return value, as in for instance:

const CXlOper& item = xloArray[i];
total += item.ToDouble();

then it must be changed. The code above becomes:

CXlConstCell item = xloArray[i];
total += item.ToDouble();

If your code simply used the returned value without retaining a copy of it, then it will continue to compile. For example, the following code does not need to change:

xloArray[i] = 0.0;

Example

CXlOper::operator [] Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlCell | CXlConstCell | CXlOper::VectorCell


CXlOper::operator <

Compare the contents of this CXlOper with another

int operator <(
   const CXlOper& xlo
) const;

Parameters

xlo

A reference to another CXlOper.

Return Value

Returns TRUE if the value in this object is less than that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::operator <=

Compare the contents of this CXlOper with another

int operator <=(
   const CXlOper& xlo
) const;

Parameters

xlo

A reference to another CXlOper.

Return Value

Returns TRUE if the value in this object is less than or equal to that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::operator =

Assigns a new value to the CXlOper, using a variety of input types

const CXlOper& operator =(
   const CXlOper& xlo
);
const CXlOper& operator =(
   const CXlCell& cell
);
const CXlOper& operator =(
   const CXlConstCell& ccell
);
const CXlOper& operator =(
   double d
);
const CXlOper& operator =(
   XlErrorType xlerr
);
const CXlOper& operator =(
   BOOL wboolean
); [Deprecated]
const CXlOper& operator =(
   bool boolean
);
const CXlOper& operator =(
   const char* psz
);
const CXlOper& operator =(
   const wchar_t* wpsz
);
const CXlOper& operator =(
   const std::string& str_stl
);
const CXlOper& operator =(
   const std::wstring& wstr_stl
);
const CXlOper& operator =(
   const CString& str
);
const CXlOper& operator =(
   const CStringA& astr
);
const CXlOper& operator =(
   const CStringW& wstr
);
const CXlOper& operator =(
   const CXlRef& xlr
);
const CXlOper& operator =(
   const std::vector<T>& vec
);
const CXlOper& operator =(
   const ple::imtx<T>& mat1
);
const CXlOper& operator =(
   const xlp::matrix<T>& mat2
); [Deprecated]

Parameters

xlo

An initialised CXlOper, whose contents will be copied to this object.
cell

An initialised CXlCell, which points to a cell in a CXlOper whose contents will be copied to this object. See CXlCell.

ccell

An initialised CXlConstCell, which points to a cell in a CXlOper whose contents will be copied to this object. See CXlConstCell.

d

A double-precision floating-point number.
xlerr

An error number (see also Error Values).

wboolean

A boolean value: TRUE (1) or FALSE (0).
boolean

A boolean value: true or false.
psz

A pointer to a null-terminated ASCII string. Note that under Excel 2007 and above, the string wil be converted to Unicode.
wpsz

A pointer to a null-terminated Unicode string. Note that under Excel 2003 and below, the string will be converted to a multibyte ASCII string, and limited to 255 bytes.
str_stl

A reference to an STL ASCII string. Note that under Excel 2007 and above, the string will be converted to Unicode.

wstr_stl

A reference to an STL Unicode string. Note that under Excel 2003 and below, the string will be converted to a multibyte character ASCII string, and limited to 255 bytes.

str

A reference to a compiler-dependent string. Note that under Excel 2007 and above, the string will be converted to Unicode if necessary. Under Excel 2003 and below, the string will be converted to a multibyte character ASCII string if necessary, and limited to 255 bytes.

astr

A reference to an ASCII string. Note that under Excel 2007 and above, the string will be converted to Unicode.

wstr

A reference to a Unicode string. Note that under Excel 2003 and below, the string will be converted to a multibyte character ASCII string, and limited to 255 bytes.

xlr

A populated Excel range reference. If the range reference is valid, the object will become a single reference type.
vec

A vector of doubles, booleans or strings.

The following types for T are directly supported:

  • bool
  • long
  • unsigned long
  • int
  • unsigned int
  • short
  • unsigned short
  • double
  • float
  • CString
  • CStringA
  • CStringW
  • std::string
  • std::wstring
Any other type is treated as an enumerated type, and converted first to long and then to the specified type.

mat1

2-dimensional array of data, contained in an object which supports the imtx interface.

The supported data types for T are as for vec.
mat2

2-dimensional array of data.

The supported data types for T are as for vec.

Remarks

These operators assign a new value to the CXlOper. If the CXlOper already contains data, then it will be appropriately cleared before the assignment.

Examples

MyDaysInFeb Example | MySort Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::operator ==

Compare the contents of this CXlOper with another

int operator ==(
   const CXlOper& xlo
) const;

Parameters

xlo

A reference to another CXlOper.

Return Value

Returns TRUE if the value in this object is equal to that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are compared by type first and then by value. Thus a string containing "123" will not be equal to an integer containing 123.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::operator >

Compare the contents of this CXlOper with another

int operator >(
   const CXlOper& xlo
) const;

Parameters

xlo

A reference to another CXlOper.

Return Value

Returns TRUE if the value in this object is greater than that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::operator >=

Compare the contents of this CXlOper with another

int operator >=(
   const CXlOper& xlo
) const;

Parameters

xlo

A reference to another CXlOper.

Return Value

Returns TRUE if the value in this object is greater than or equal to that in xlo; returns FALSE otherwise.

Remarks

Note that CXlOpers are sorted by type first and then value. Thus a string containing "123" will not necessarily sort later than an integer containing 122. For CXlOpers of the same type, sort order is always by value.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::operator BOOL

Returns a boolean value

operator BOOL( ) const;

Return Value

This function returns the value of a boolean contained in a CXlOper, or throws an exception of type CXlConversionException if the CXlOper contains any other data type.

Example

CXlOper::operator BOOL() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::operator bool

Returns a boolean value

operator bool( ) const;

Return Value

This function returns the value of a boolean contained in a CXlOper, or throws an exception of type CXlConversionException if the CXlOper contains any other data type.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::operator CString

Returns a string value

operator CString( ) const;

Return Value

This function returns the value of a string contained in a CXlOper, or throws an exception of type CXlConversionException if the CXlOper contains any other data type.

Example

CXlOper::operator CString() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::operator double

Returns a numeric value

operator double( ) const;

Return Value

This function returns the value of a double contained in a CXlOper, or throws an exception of type CXlConversionException if the CXlOper contains any other data type.

Example

CXlOper::operator double() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::ReadMatrix

Reads data from a 2-dimensional array into a matrix of numbers or strings

template< class T >
BOOL ReadMatrix(
   ple::imtx<T>& mat1,
   const char* pszArgName,
   CString& strError,
   long* plUBound1 = 0,
   long* plUBound2 = 0,
   long lFlags = XLA_ARRAY_FLAGS_STD,
   long lLBound1 = 0,
   long lLBound2 = 0,
   long lIgnoreRows = 0,
   long lIgnoreCols = 0
) const;
template< class T >
BOOL ReadMatrix(
   ple::imtx<T>& mat1,
   const char* pszArgName,
   CXlOper& xloError,
   long* plUBound1 = 0,
   long* plUBound2 = 0,
   long lFlags = XLA_ARRAY_FLAGS_STD,
   long lLBound1 = 0,
   long lLBound2 = 0,
   long lIgnoreRows = 0,
   long lIgnoreCols = 0
) const;
template< class T >
BOOL ReadMatrix(
   xlp::matrix<T>& mat2,
   const char* pszArgName,
   CString& strError,
   long* plUBound1 = 0,
   long* plUBound2 = 0,
   long lFlags = XLA_ARRAY_FLAGS_STD,
   long lLBound1 = 0,
   long lLBound2 = 0,
   long lIgnoreRows = 0,
   long lIgnoreCols = 0
) const;
template< class T >
BOOL ReadMatrix(
   xlp::matrix<T>& mat2,
   const char* pszArgName,
   CXlOper& xloError,
   long* plUBound1 = 0,
   long* plUBound2 = 0,
   long lFlags = XLA_ARRAY_FLAGS_STD,
   long lLBound1 = 0,
   long lLBound2 = 0,
   long lIgnoreRows = 0,
   long lIgnoreCols = 0
) const;

Parameters

mat1

A matrix class (descended from class imtx<T>) containing items of type T, whose contents will be replaced by the contents of the CXlOper.

The following types are directly supported for T:

  • bool
  • long
  • unsigned long
  • int
  • unsigned int
  • short
  • unsigned short
  • double
  • float
  • CString
  • std::string
Any other type is treated as an enumerated type, and converted first to long and then to the specified type.

A matrix of double, whose contents will be replaced by the contents of the CXlOper.
pszArgName

The name of the argument that is being read. This will be used in any error strings that are generated.
strError

Reference to an error string buffer. If the function fails for any reason, a useful error string will be placed here, e.g. "MyArgName: expected number in cell 3".
plUBound1

Pointer to upper bound of first dimension (height). If it is null, then it is ignored. If it is not null then it is used to check that the upper bounds of various arrays are consistent.

See Bounded input arrays for more information on the use of upper bounds.
plUBound2

Pointer to upper bound of second dimension (width). If it is null, then it is ignored. If it is not null then it is used to check that the upper bounds of various arrays are consistent.

See Bounded input arrays for more information on the use of upper bounds.
lFlags

Flags controlling the conversion. See matrix & vector flags for a full list of flag values.
lLBound1

This will be used as a lower bound in the output matrix. lLBound rows containing default values (zero or blank) will be inserted at the start of the output matrix.
lLBound2

This will be used as a lower bound in the output matrix. lLBound columns containing default values (zero or blank) will be inserted at the start of the output matrix.
lIgnoreRows

The first lIgnoreRows rows of input will be ignored. This option can be useful for excluding labels.
lIgnoreCols

The first lIgnoreCols columns of input will be ignored. This option can be useful for excluding labels.
xloError

If any error occurs, a description will be put into xloError. It can then conveniently be returned as the result of the add-in function.
mat2

A matrix of the deprecated class matrix<T>, containing items of type T, whose contents will be replaced by the contents of the CXlOper.

Types supported are the same as for mat1.

A matrix of double, whose contents will be replaced by the contents of the CXlOper.

Return Value

The function returns TRUE if the conversion was successful, FALSE if it failed for any reason.

If it fails, an explanatory error string will be written to strError or xloError. This should be returned to the user.

Remarks

This function extracts a rectangular range of numbers or strings from an array argument. Using the default flag values, it is reasonably 'smart': by default it truncates any empty cells at the end (right or bottom) of the input range.

However, a wide variety of other options are available, if you use other flag values and optional arguments. See matrix & vector flags for a full list of flag values.

See Bounded input arrays for more information on the use of upper bounds.

Note Note:

This method is deprecated. Use XlReadMatrix instead.

Coercion

If the CXlOper contains a reference to a range of cells, rather than the values of the cells, then this function will fail, and will return a message stating that the argument must be coerced before use.

You should write code to Coerce the input to a value, e.g.:

extern "C" __declspec( dllexport )
LPXLOPER ReadXlOper(const CXlOper* Arg1)
{
    CXlOper xloResult;
//}}XLP_SRC

    CXlOper valArg1;
    if (valArg1.Coerce(*Arg1) != 0)
        return CXlOper::RetError(xlerrValue);
    ple::mtx_ptrs<bool> matB;
    if (!valArg1.ReadMatrix(matB, "Arg1", strError))
        return CXlOper::RetString(strError);
    ...
}

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | Bounded input arrays | CXlOper::ReadVector()


CXlOper::ReadVector

Reads a row or a column from an array into a vector of numbers or strings

template< class T >
BOOL ReadVector(
   std::vector<T>& vecResult,
   const char* pszArgName,
   CString& strError,
   long* plUBound = 0,
   long lRowOrCol = XLA_UNIQUE_VECTOR,
   long lFlags = XLA_ARRAY_FLAGS_STD,
   long lLBound = 0,
   long lIgnoreItems = 0
) const;
template< class T >
BOOL ReadVector(
   std::vector<T>& vecResult,
   const char* pszArgName,
   CXlOper& xloError,
   long* plUBound = 0,
   long lRowOrCol = XLA_UNIQUE_VECTOR,
   long lFlags = XLA_ARRAY_FLAGS_STD,
   long lLBound = 0,
   long lIgnoreItems = 0
) const;

Parameters

vecResult

A vector containing items of type T, whose contents will be replaced by the contents of the CXlOper.

The following types are directly supported for T:

  • bool
  • long
  • unsigned long
  • int
  • unsigned int
  • short
  • unsigned short
  • double
  • float
  • CString
  • std::string
Any other type is treated as an enumerated type, and converted first to long and then to the specified type.

pszArgName

The name of the argument that is being read. This will be used in any error strings that are generated.
strError

Reference to an error string buffer. If the function fails for any reason, a useful error string will be placed here, e.g. "MyArgName: expected number in cell 3".
plUBound

Pointer to upper bound. If it is null, then it is ignored. If it is not null then it is used to check that the upper bounds of various arrays are consistent.

See Bounded input arrays for more information on the use of upper bounds.
lRowOrCol

Zero-based index of row or column to be extracted. If it is out of range, the function will fail.

If lRowOrCol is set to XLA_UNIQUE_VECTOR, then the only row of a single-row array (or the only column of a one-column array) will be returned: if the array has more than one row and more than one column, the function will report an error and return FALSE.
lFlags

Flags controlling the conversion. See matrix & vector flags for a full list of flag values.
lLBound

This will be used as a lower bound in the output vector. lLBound cells containing the default value will be inserted at the start of the output vector.
lIgnoreItems

The first lIgnoreItems of input will be ignored. This option can be useful for excluding labels.
xloError

If any error occurs, a description will be put into xloError. It can then conveniently be returned as the result of the add-in function.

Return Value

The function returns TRUE if the conversion was successful, FALSE if it failed for any reason.

If it fails, an explanatory error string will be written to strError or xloError. This should be returned to the user.

Remarks

This function extracts a single row of numbers or strings from an array argument. Using the default flag values, it is reasonably 'smart': by default it truncates any empty cells at the end (right or bottom) of the input range.

However, a wide variety of other options are available, if you use other flag values and optional arguments. See matrix & vector flags for a full list of flag values.

See Bounded input arrays for more information on the use of upper bounds.

Note Note:

This method is deprecated. Use XlReadVector instead.

Coercion

If the CXlOper contains a reference to a range of cells, rather than the values of the cells, then this function will fail, and will return a message stating that the argument must be coerced before use.

You should write code to Coerce the input to a value, e.g.:

extern "C" __declspec( dllexport )
LPXLOPER ReadXlOper(const CXlOper* Arg1)
{
    CXlOper xloResult;
//}}XLP_SRC

    CXlOper valArg1;
    if (valArg1.Coerce(*Arg1) != 0)
        return CXlOper::RetError(xlerrValue);
    std::vector<bool> vecB;
    if (!valArg1.ReadVector(vecB, "Arg1", strError))
        return CXlOper::RetString(strError);
    ...
}

It is generally simpler and faster to use a value type to handle an array input. You should only use CXlOper to handle an array input if you need a CXlOper feature, such as a heterogeneous input that can contain either a value or a reference.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | Bounded input arrays | CXlOper::ReadMatrix()


CXlOper::Resize

Returns a reference resized to the specified number of rows and columns

CXlOper Resize(
   RW12 nRows,
   COL12 nCols
) const;

Parameters

nRows

Number of rows reference should contain.
nCols

Number of columns reference should contain.

Return Value

Returns a new reference, with the same top and left as this reference, and with the specified number of rows and columns. The function will throw an exception if the new reference is not valid.

Remarks

The function will throw an exception of type CXlBadOperTypeException if the object does not contain a single or multiple reference.

The function will throw an exception of type CXlOutOfRangeException if the new position would be out of range.

This method is a short-hand for getting a reference, resizing it, and setting it. Thus, the following:

xlo2 = xlo1.Resize(3, 2);

is a short-hand for:

xlo2 = xlo1;
CXlRef xlr = xlo2.GetRef();
xlr.Resize(3, 2);
xlo2.SetRef(xlr);

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::Offset() | CXlOper::MoveRefBy()


CXlOper::Ret

Prepares a CXlOper to be returned as a value to Excel

CXlOper* Ret( );

Return Value

This function returns a pointer to some static memory containing a copy of this CXlOper.

Remarks

The Ret() function is essential to the implementation of the memory management features of the library. When you return data to Excel from an add-in function, the data must be contained in memory which remains in scope even when the function goes out of scope.

The Ret() function takes the current value in the CXlOper and copies it into heap memory. It then releases the memory of the original copy and sets flags in the new copy so that Excel will properly manage the memory clean-up on your behalf.

Once you have called Ret(), a CXlOper is no longer valid, and cannot be used for any purpose.

Ret() is only used in the return statements of add-in functions, for example:

CXlOper xloResult;
xloResult = 123.456;
return xloResult.Ret();

Examples

MySqrt Example | MyCorrel Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::RetError() | CXlOper::RetString()


CXlOper::RetError

Returns an error value to Excel

static CXlOper* RetError(
   XlErrorType xlerr
);

Parameters

xlerr

An error number (see also Error Values).

Return Value

This function returns a pointer to some static memory containing an error code.

Remarks

This static function can be used to return a CXlOper result containing an error code from an add-in function, instead of CXlOper::Ret().

For example:

if (input < 0)
    return CXlOper::RetError(xlerrNum);

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::Ret() | CXlOper::RetString()


CXlOper::RetString

Returns a string value to Excel

static CXlOper* RetString(
   const char* lpszFormat,
    ...
);
static CXlOper* RetString(
   const wchar_t* lpszFormat,
    ...
);

Parameters

lpszFormat

A string template, which may include tokens preceded by %, like printf.
...

The remaining arguments to the function will be substituted into the returned string, as in the standard C library function printf. Arguments of type CString should be cast to (const char*) or (const wchar_t*) as appropriate.

Return Value

This function returns a pointer to some static memory containing a string.

Remarks

This static function can be used to return a CXlOper result containing a string from an add-in function, instead of CXlOper::Ret().

For example:

if (input < 0)
    return CXlOper::RetString("#Error: input (%lf) must be >= 0", input);

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::Ret() | CXlOper::RetError()


CXlOper::RetVal

Returns a pointer to Excel's return value

static LPCXLOPER RetVal( );

Return Value

This function returns a read-only pointer to some static memory containing a copy of the CXlOper data about to be returned to Excel.

Remarks

The statement is only valid between a call to CXlOper::Ret() and the return from an add-in function. (Note that CXlOper::RetString() and CXlOper::RetError() both call CXlOper::Ret(), and therefore use the same buffer.)

Thus it is only safe to call it during the destructor of an object which is at function scope in an add-in function. It is used by the destructor of CXlCacheBinding to add new results to the cache.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::Ret() | CXlOper::RetError() | CXlOper::RetString()


CXlOper::SetActiveCell

Sets the active cell to be the cell referred to by this CXlOper

BOOL SetActiveCell( ) const;

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if there is no current cell, or if the function cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetActiveCell() | CXlOper::MakeRef()


CXlOper::SetFormula

Set the formula of the referenced cell, in local format

BOOL SetFormula(
   const TCHAR* pszFormula,
   BOOL bArray = FALSE,
   BOOL bA1 = TRUE
) const;

Parameters

pszFormula

String buffer containing the formula. The formula is assumed to be in the current language (i.e. in "local" form), using punctuation derived from the user's regional settings, and function names derived from the Excel version.

If the formula is not in the correct format for the current settings, then the call will fail. To use a formula which works under all language settings, see CXlOper::SetFormulaIntl.
bArray

TRUE if the target should be filled with an array formula; FALSE if each cell should be filled with a standard formula.
bA1

If TRUE, then the formula should contain references in A1 format; if FALSE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, if the formula is invalid, or if the function cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

International considerations

Be careful when setting formulae that the formula is formatted correctly for the current language settings. For example, arguments in English are separated by commas; in German, semi-colons are used.

You can use CXllApp::GetInternational to get the current list separators and other punctuation characters.

Alternatively, you can use CXlOper::SetFormulaIntl to apply formulae that work in all languages.

Version history

Before XLL+ version 4.3.1, this method contained a bug which caused relative addresses to be wrongly transformed. This has now been fixed.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetFormula() | CXlOper::ConvertFormula() | CXllApp::GetInternational() | CXlOper::SetFormulaIntl()


CXlOper::SetFormulaA

Set the formula of the referenced cell, in local format

BOOL SetFormulaA(
   const char* pszFormula,
   BOOL bArray = FALSE,
   BOOL bA1 = TRUE
) const;

Parameters

pszFormula

String buffer containing the formula. The formula is assumed to be in the current language (i.e. in "local" form), using punctuation derived from the user's regional settings, and function names derived from the Excel version.

If the formula is not in the correct format for the current settings, then the call will fail. To use a formula which works under all language settings, see CXlOper::SetFormulaIntl.
bArray

TRUE if the target should be filled with an array formula; FALSE if each cell should be filled with a standard formula.
bA1

If TRUE, then the formula should contain references in A1 format; if FALSE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, if the formula is invalid, or if the function cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

International considerations

Be careful when setting formulae that the formula is formatted correctly for the current language settings. For example, arguments in English are separated by commas; in German, semi-colons are used.

You can use CXllApp::GetInternational to get the current list separators and other punctuation characters.

Alternatively, you can use CXlOper::SetFormulaIntl to apply formulae that work in all languages.

Version history

Before XLL+ version 4.3.1, this method contained a bug which caused relative addresses to be wrongly transformed. This has now been fixed.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetFormula() | CXlOper::ConvertFormula() | CXllApp::GetInternational() | CXlOper::SetFormulaIntl()


CXlOper::SetFormulaIntl

Set the formula of the referenced cell, in English

BOOL SetFormulaIntl(
   const TCHAR* pszFormula,
   BOOL bArray = FALSE,
   BOOL bA1 = TRUE
) const;

Parameters

pszFormula

String buffer containing the formula. The formula is assumed to be in English, using US English regional settings - i.e. arguments and lists are separated by commas; rows in arrays are separated by semi-colons; the full stop is used as a decimal point.

If the formula is not in the correct English format, then the call will fail. To use a formula which works using local language settings, see CXlOper::SetFormula.
bArray

TRUE if the target should be filled with an array formula; FALSE if each cell should be filled with a standard formula.
bA1

If TRUE, then the formula should contain references in A1 format; if FALSE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, if the formula is invalid, or if the function cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

International considerations

This method will work in all Excel language versions and under any user-selected regional settings. Note that all formulae must be in English.

Alternatively, you can use CXlOper::SetFormula to apply formulae in the local language.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetFormulaIntl() | CXlOper::ConvertFormulaIntl() | CXlOper::SetLongFormulaIntl() | CXlOper::SetFormula()


CXlOper::SetFormulaIntlA

Set the formula of the referenced cell, in English

BOOL SetFormulaIntlA(
   const char* pszFormula,
   BOOL bArray = FALSE,
   BOOL bA1 = TRUE
) const;

Parameters

pszFormula

String buffer containing the formula. The formula is assumed to be in English, using US English regional settings - i.e. arguments and lists are separated by commas; rows in arrays are separated by semi-colons; the full stop is used as a decimal point.

If the formula is not in the correct English format, then the call will fail. To use a formula which works using local language settings, see CXlOper::SetFormula.
bArray

TRUE if the target should be filled with an array formula; FALSE if each cell should be filled with a standard formula.
bA1

If TRUE, then the formula should contain references in A1 format; if FALSE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, if the formula is invalid, or if the function cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

International considerations

This method will work in all Excel language versions and under any user-selected regional settings. Note that all formulae must be in English.

Alternatively, you can use CXlOper::SetFormula to apply formulae in the local language.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetFormulaIntl() | CXlOper::ConvertFormulaIntl() | CXlOper::SetLongFormulaIntl() | CXlOper::SetFormula()


CXlOper::SetFormulaIntlW

Set the formula of the referenced cell, in English

BOOL SetFormulaIntlW(
   const wchar_t* pszFormula,
   BOOL bArray = FALSE,
   BOOL bA1 = TRUE
) const;

Parameters

pszFormula

String buffer containing the formula. The formula is assumed to be in English, using US English regional settings - i.e. arguments and lists are separated by commas; rows in arrays are separated by semi-colons; the full stop is used as a decimal point.

If the formula is not in the correct English format, then the call will fail. To use a formula which works using local language settings, see CXlOper::SetFormula.
bArray

TRUE if the target should be filled with an array formula; FALSE if each cell should be filled with a standard formula.
bA1

If TRUE, then the formula should contain references in A1 format; if FALSE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, if the formula is invalid, or if the function cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

International considerations

This method will work in all Excel language versions and under any user-selected regional settings. Note that all formulae must be in English.

Alternatively, you can use CXlOper::SetFormula to apply formulae in the local language.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetFormulaIntl() | CXlOper::ConvertFormulaIntl() | CXlOper::SetLongFormulaIntl() | CXlOper::SetFormula()


CXlOper::SetFormulaW

Set the formula of the referenced cell, in local format

BOOL SetFormulaW(
   const wchar_t* pszFormula,
   BOOL bArray = FALSE,
   BOOL bA1 = TRUE
) const;

Parameters

pszFormula

String buffer containing the formula. The formula is assumed to be in the current language (i.e. in "local" form), using punctuation derived from the user's regional settings, and function names derived from the Excel version.

If the formula is not in the correct format for the current settings, then the call will fail. To use a formula which works under all language settings, see CXlOper::SetFormulaIntl.
bArray

TRUE if the target should be filled with an array formula; FALSE if each cell should be filled with a standard formula.
bA1

If TRUE, then the formula should contain references in A1 format; if FALSE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, if the formula is invalid, or if the function cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

International considerations

Be careful when setting formulae that the formula is formatted correctly for the current language settings. For example, arguments in English are separated by commas; in German, semi-colons are used.

You can use CXllApp::GetInternational to get the current list separators and other punctuation characters.

Alternatively, you can use CXlOper::SetFormulaIntl to apply formulae that work in all languages.

Version history

Before XLL+ version 4.3.1, this method contained a bug which caused relative addresses to be wrongly transformed. This has now been fixed.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetFormula() | CXlOper::ConvertFormula() | CXllApp::GetInternational() | CXlOper::SetFormulaIntl()


CXlOper::SetLongFormula

Set the formula of the referenced cell, in local format, for formulae of more than 255 characters

BOOL SetLongFormula(
   const TCHAR* pszFormula,
   BOOL bArray = FALSE,
   BOOL bA1 = TRUE
) const;

Parameters

pszFormula

String buffer containing the formula. Formulae must contain less than 1024 characters.

The formula is assumed to be in the current language (i.e. in "local" form), using punctuation derived from the user's regional settings, and function names derived from the Excel version.

If the formula is not in the correct format for the current settings, then the call will fail. To use a formula which works under all language settings, see CXlOper::SetLongFormulaIntl.
bArray

TRUE if the target should be filled with an array formula; FALSE if each cell should be filled with a standard formula.
bA1

If TRUE, then the formula should contain references in A1 format; if FALSE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, if the formula is invalid, or if the function cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

It makes use of the COM interface, and is much slower than CXlOper::SetFormula, SetFormula should always be used in preference to SetLongFormula, except for the rare case where a very long formula is unavoidable.

Note also that each of the literal values contained within the string must have 255 characters or less. The entire formula may have up to 1024 characters, but no single argument within it may have more than 255 characters.

International considerations

Be careful when setting formulae that the formula is formatted correctly for the current language settings. For example, arguments in English are separated by commas; in German, semi-colons are used.

You can use CXllApp::GetInternational to get the current list separators and other punctuation characters.

Alternatively, you can use CXlOper::SetFormulaIntl to apply formulae that work in all languages.

Example

CXlOper::SetLongFormula() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetFormula() | CXlOper::SetLongFormulaIntl()


CXlOper::SetLongFormulaA

Set the formula of the referenced cell, in local format, for formulae of more than 255 characters

BOOL SetLongFormulaA(
   const char* pszFormula,
   BOOL bArray = FALSE,
   BOOL bA1 = TRUE
) const;

Parameters

pszFormula

String buffer containing the formula. Formulae must contain less than 1024 characters.

The formula is assumed to be in the current language (i.e. in "local" form), using punctuation derived from the user's regional settings, and function names derived from the Excel version.

If the formula is not in the correct format for the current settings, then the call will fail. To use a formula which works under all language settings, see CXlOper::SetLongFormulaIntl.
bArray

TRUE if the target should be filled with an array formula; FALSE if each cell should be filled with a standard formula.
bA1

If TRUE, then the formula should contain references in A1 format; if FALSE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, if the formula is invalid, or if the function cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

It makes use of the COM interface, and is much slower than CXlOper::SetFormula, SetFormula should always be used in preference to SetLongFormula, except for the rare case where a very long formula is unavoidable.

Note also that each of the literal values contained within the string must have 255 characters or less. The entire formula may have up to 1024 characters, but no single argument within it may have more than 255 characters.

International considerations

Be careful when setting formulae that the formula is formatted correctly for the current language settings. For example, arguments in English are separated by commas; in German, semi-colons are used.

You can use CXllApp::GetInternational to get the current list separators and other punctuation characters.

Alternatively, you can use CXlOper::SetFormulaIntl to apply formulae that work in all languages.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetFormula() | CXlOper::SetLongFormulaIntl()


CXlOper::SetLongFormulaIntl

Set the formula of the referenced cell, in English, for formulae of more than 255 characters

BOOL SetLongFormulaIntl(
   const TCHAR* pszFormula,
   BOOL bArray = FALSE,
   BOOL bA1 = TRUE
) const;

Parameters

pszFormula

String buffer containing the formula. Formulae must contain less than 1024 characters.

The formula is assumed to be in English, using US English regional settings - i.e. arguments and lists are separated by commas; rows in arrays are separated by semi-colons; the full stop is used as a decimal point.

If the formula is not in the correct English format, then the call will fail. To use a formula which works using local language settings, see CXlOper::SetFormula.
bArray

TRUE if the target should be filled with an array formula; FALSE if each cell should be filled with a standard formula.
bA1

If TRUE, then the formula should contain references in A1 format; if FALSE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, if the formula is invalid, or if the function cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

It makes use of the COM interface, and is much slower than CXlOper::SetFormulaIntl, SetFormulaIntl should always be used in preference to SetLongFormulaIntl, except for the rare case where a very long formula is unavoidable.

Note also that each of the literal values contained within the string must have 255 characters or less. The entire formula may have up to 1024 characters, but no single argument within it may have more than 255 characters.

International considerations

This method will work in all Excel language versions and under any user-selected regional settings. Note that all formulae must be in English.

Alternatively, you can use CXlOper::SetLongFormula to apply long formulae in the local language.

Example

CXlOper::SetLongFormulaIntl() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetFormulaIntl() | CXlOper::SetLongFormula()


CXlOper::SetLongFormulaIntlA

Set the formula of the referenced cell, in English, for formulae of more than 255 characters

BOOL SetLongFormulaIntlA(
   const char* pszFormula,
   BOOL bArray = FALSE,
   BOOL bA1 = TRUE
) const;

Parameters

pszFormula

String buffer containing the formula. Formulae must contain less than 1024 characters.

The formula is assumed to be in English, using US English regional settings - i.e. arguments and lists are separated by commas; rows in arrays are separated by semi-colons; the full stop is used as a decimal point.

If the formula is not in the correct English format, then the call will fail. To use a formula which works using local language settings, see CXlOper::SetFormula.
bArray

TRUE if the target should be filled with an array formula; FALSE if each cell should be filled with a standard formula.
bA1

If TRUE, then the formula should contain references in A1 format; if FALSE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, if the formula is invalid, or if the function cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

It makes use of the COM interface, and is much slower than CXlOper::SetFormulaIntl, SetFormulaIntl should always be used in preference to SetLongFormulaIntl, except for the rare case where a very long formula is unavoidable.

Note also that each of the literal values contained within the string must have 255 characters or less. The entire formula may have up to 1024 characters, but no single argument within it may have more than 255 characters.

International considerations

This method will work in all Excel language versions and under any user-selected regional settings. Note that all formulae must be in English.

Alternatively, you can use CXlOper::SetLongFormula to apply long formulae in the local language.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetFormulaIntl() | CXlOper::SetLongFormula()


CXlOper::SetLongFormulaIntlW

Set the formula of the referenced cell, in English, for formulae of more than 255 characters

BOOL SetLongFormulaIntlW(
   const wchar_t* pszFormula,
   BOOL bArray = FALSE,
   BOOL bA1 = TRUE
) const;

Parameters

pszFormula

String buffer containing the formula. Formulae must contain less than 1024 characters.

The formula is assumed to be in English, using US English regional settings - i.e. arguments and lists are separated by commas; rows in arrays are separated by semi-colons; the full stop is used as a decimal point.

If the formula is not in the correct English format, then the call will fail. To use a formula which works using local language settings, see CXlOper::SetFormula.
bArray

TRUE if the target should be filled with an array formula; FALSE if each cell should be filled with a standard formula.
bA1

If TRUE, then the formula should contain references in A1 format; if FALSE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, if the formula is invalid, or if the function cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

It makes use of the COM interface, and is much slower than CXlOper::SetFormulaIntl, SetFormulaIntl should always be used in preference to SetLongFormulaIntl, except for the rare case where a very long formula is unavoidable.

Note also that each of the literal values contained within the string must have 255 characters or less. The entire formula may have up to 1024 characters, but no single argument within it may have more than 255 characters.

International considerations

This method will work in all Excel language versions and under any user-selected regional settings. Note that all formulae must be in English.

Alternatively, you can use CXlOper::SetLongFormula to apply long formulae in the local language.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetFormulaIntl() | CXlOper::SetLongFormula()


CXlOper::SetLongFormulaW

Set the formula of the referenced cell, in local format, for formulae of more than 255 characters

BOOL SetLongFormulaW(
   const wchar_t* pszFormula,
   BOOL bArray = FALSE,
   BOOL bA1 = TRUE
) const;

Parameters

pszFormula

String buffer containing the formula. Formulae must contain less than 1024 characters.

The formula is assumed to be in the current language (i.e. in "local" form), using punctuation derived from the user's regional settings, and function names derived from the Excel version.

If the formula is not in the correct format for the current settings, then the call will fail. To use a formula which works under all language settings, see CXlOper::SetLongFormulaIntl.
bArray

TRUE if the target should be filled with an array formula; FALSE if each cell should be filled with a standard formula.
bA1

If TRUE, then the formula should contain references in A1 format; if FALSE, the references should be in RC format.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, if the formula is invalid, or if the function cannot be run in Excel at this time.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

It makes use of the COM interface, and is much slower than CXlOper::SetFormula, SetFormula should always be used in preference to SetLongFormula, except for the rare case where a very long formula is unavoidable.

Note also that each of the literal values contained within the string must have 255 characters or less. The entire formula may have up to 1024 characters, but no single argument within it may have more than 255 characters.

International considerations

Be careful when setting formulae that the formula is formatted correctly for the current language settings. For example, arguments in English are separated by commas; in German, semi-colons are used.

You can use CXllApp::GetInternational to get the current list separators and other punctuation characters.

Alternatively, you can use CXlOper::SetFormulaIntl to apply formulae that work in all languages.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::SetFormula() | CXlOper::SetLongFormulaIntl()


CXlOper::SetRef

Sets the first (or only) single reference in a single or multiple range reference

void SetRef(
   const CXlRef& xlr
);
void SetRef(
   RW12 rTop,
   COL12 cLeft,
   RW12 rBottom,
   COL12 cRight
);
void SetRef(
   RW12 rRow,
   COL12 cColumn
);

Parameters

xlr

A reference to a block of cells.

rTop

The top row of a range.
cLeft

The left-most column of a range.
rBottom

The bottom row of a range.
cRight

The right-most column of a range.
rRow

The row of a single cell.
cColumn

The column of a single cell.

Remarks

This method sets the XLREF contained by the CXlRef to reflect the values passed as parameters.

Remarks

The function will throw an exception of type CXlBadOperTypeException if the object does not contain a single or multiple reference. SetRef() should be used only if IsRef() returns TRUE, as in:

if ( xlo.IsRef() )
{
    CXlRef xlr(0, 0, 2, 3);
    xlo.SetRef(xlr);
}

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetRef() | CXlOper::GetRefCount() | CXlOper::SetRefItem()


CXlOper::SetRefItem

Sets one of the single references in a multiple reference

CXlRef SetRefItem(
   WORD wItem,
   const CXlRef& xlr
);

Parameters

wItem

The index of the range to retrieve. The first item is at position 0.
xlr

A reference to a block of cells.

Return Value

Sets the value of one of the single ranges in a multiple reference. If the CXlOper contains a single reference, and wItem is 0, then the function will affect the single reference itself.

Remarks

The function will throw an exception of type CXlBadOperTypeException if the object does not contain a single or multiple reference, or of type CXlOutOfRangeException if wItem is out of range.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetRefCount() | CXlOper::GetRefItem()


CXlOper::SetValue

Set the value of the referenced cells

BOOL SetValue(
   const CXlOper& xloValue
) const;

Parameters

xloValue

CXlOper containing the new value of the range referenced by this CXlOper. This can be an array.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the CXlOper does not contain a reference, or if it cannot be run in Excel at this time or if xloValue is not valid.

Remarks

This function can only be called from macro functions. It will always fail if called from worksheet functions.

The function is extremely fast, particularly when compared to equivalent VBA methods. It is by far the fastest way to pump large amounts of data into Excel.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::Coerce() | CXlOper::GetActiveCell() | CXlOper::MakeRef()


CXlOper::ToBool

Returns a boolean value

bool ToBool(
   bool bStrict = FALSE
) const;

Parameters

bStrict

If bStrict is false (the default) then, if the CXlOper does not contain a boolean value, the function will safely return an appropriate converted value.

If bStrict is true then the function will throw an exception of type CXlConversionException unless the CXlOper contains a boolean.

Return Value

This function returns the boolean value contained in a CXlOper.

Example

CXlOper::ToBool() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::ToDouble

Retrieves a numeric value from the CXlOper

double ToDouble(
   bool bStrict = FALSE
) const;

Parameters

bStrict

If bStrict is false (the default) then, if the CXlOper does not contain a double, the function will safely return an appropriate converted double (0 for blanks).

If bStrict is true then the function will throw an exception of type CXlConversionException unless the CXlOper contains a double.

Return Value

This function returns the double value contained in a CXlOper.

Examples

CXlOper::ToDouble() Example | MySum Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::ToDoubleArray

Copies the contents of an OPER into a 'C' array of doubles or pointers to doubles

BOOL ToDoubleArray(
   double* pd,
   USHORT cRows,
   BOOL bStrict = FALSE
) const;
BOOL ToDoubleArray(
   double* pd,
   USHORT cRows,
   USHORT cCols,
   BOOL bByRows = FALSE,
   BOOL bStrict = FALSE
) const;
BOOL ToDoubleArray(
   double** apd,
   USHORT cRows,
   USHORT cCols,
   BOOL bByRows = FALSE,
   BOOL bStrict = FALSE
) const;

Parameters

pd

An array of double's, containing either cRows items, or (cRows x cCols) items, depending on the function variant used. For the latter type, the values will be arranged in the order specified by the bByRows parameter.
cRows

The number of rows contained in the supplied array of doubles.
bStrict

If bStrict is FALSE (the default) then, if any of the cells in the CXlOper do not contain a double, the function will safely return an appropriate converted value.

If bStrict is TRUE then the function will fail and return FALSE unless every cell in CXlOper contains a double.
cCols

The number of columns contained in the supplied array of doubles.
bByRows

Storage order of arrays of double's. If TRUE, then values in the same row are stored contiguously, otherwise values in the same column are assumed to be stored contiguously.
apd

An array of pointers to double, containing either cRows arrays each of size cCols, or cCols arrays each of size cRows, depending on the order specified by the bByRows parameter

Return Value

This function returns TRUE if any of the cells in a CXlOper have been successfully read into the array(s) as numbers, FALSE otherwise.

Example

CXlOper::ToDoubleArray() Examples

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::ToInt

Returns an integer value

short int ToInt(
   bool bStrict = FALSE
) const;

Parameters

bStrict

If bStrict is false (the default) then, if the CXlOper does not contain an integer value, the function will safely return an appropriate converted value.

If bStrict is true then the function will throw an exception of type CXlConversionException unless the CXlOper contains an integer.

Return Value

This function returns the integer value contained in a CXlOper.

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::ToString

Returns a string value

CString ToString(
   bool bStrict = FALSE
) const;

Parameters

bStrict

If bStrict is false (the default) then, if the CXlOper does not contain a string, the function will safely return an appropriate converted string.

If bStrict is true then the function will throw an exception of type CXlConversionException unless the CXlOper contains a string.

Return Value

This function returns the string value contained in a CXlOper.

Example

CXlOper::ToString() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods


CXlOper::VectorCell

Returns a reference to an item in a one-dimensional array

CXlCell VectorCell(
   size_t szItem
);
const CXlConstCell VectorCell(
   size_t szItem
) const;

Parameters

szItem

The row or column containing the item of interest (the top row and the leftmost column are 0).

Return Value

This function returns a reference to an item contained in a one-dimensional array.

If szItem is out of range then an exception of type CXlOutOfRangeException will be thrown.

Remarks

The function should only be used for arrays containing one row or one column.

The reference returned by this function can be used to read the item or (if the CXlOper itself is writeable) to update it.

Breaking change

Under previous versions of XLL+ (5 and below), this method returned a reference to a CXlOper type, which was contained within the outer CXlOper. In order to support both Excel 2007 and older versions of Excel, this functionality has had to be changed.

The method now returns a new class of object, CXlCell or CXlConstCell, which can be used to refer to the cell, but is not itself of type CXlOper.

If your code retained a copy of the return value, as in for instance:

const CXlOper& item = xloArray.VectorCell(i);
total += item.ToDouble();

then it must be changed. The code above becomes:

CXlConstCell item = xloArray.VectorCell(i);
total += item.ToDouble();

If your code simply used the returned value without retaining a copy of it, then it will continue to compile. For example, the following code does not need to change:

xloArray.VectorCell(i) = 0.0;

Example

CXlOper::VectorCell() Example

Requirements

Header: xllplus.h

See Also

CXlOper Class | CXlOper Methods | CXlOper::GetVectorCount() | CXlOper::IsVector()


CXlRef Class

Describes a single rectangular range of cells.

class CXlRef

Overview

The CXlRef class is a thin wrapper around the Excel SDK structures XLREF4 and XLREF12.

It describes a single rectangular range of cells. It does not contain the name of the sheet in which the range is situated, or any other information.

Instances of CXlRef are usually obtained from reference arguments to add-in functions (which may contain multiple CXlRefs) and from the CXlOper::GetCaller() method.

Examples

CXlOper::GetCaller() Example | CXlRef Example

Requirements

Header: xllplus.h

See Also

CXlRef Methods | xllplus.h | CXlOper object


CXlRef Methods

The methods of the CXlRef class are listed here.

Construction

public method CXlRef Constructs a CXlRef object

Assignment operators

public method operator = Assigns a new value to the XLREF, using a variety of input types

Operations

public method | Init | Initialise the CXlRef contents
public method | MoveBy | Moves a reference by the specified number of rows and columns
public method | Normalize | Normalize the coordinates of the reference
public method | Resize | Resizes a reference to the specified number of rows and columns
public method | SetRef | Sets the values in the CXlRef

Attributes

public method | Bottom | Returns a reference to the bottom row number of the reference
public method | Height | Returns the number of rows in the reference
public method | IsSingle | Is this a reference to a single cell ?
public method | Left | Returns a reference to the leftmost column number of the reference
public method | Right | Returns a reference to the rightmost column number of the reference
public method | Top | Returns a reference to the top row number of the reference
public method | Width | Returns the number of columns in the reference

String Conversion

public method | BottomRightToString | Converts the bottom right corner of the reference to a string address
public method | BottomRightToStringA | Converts the bottom right corner of the reference to a string address
public method | BottomRightToStringW | Converts the bottom right corner of the reference to a string address
public method | ColToA | Converts a column number to its A1 style column letter(s)
public method | ColToAA | Converts a column number to its A1 style column letter(s)
public method | ColToAW | Converts a column number to its A1 style column letter(s)
public method | FromString | Reads a string address into the reference
 | GetRowColumnLetters | Returns the letters used for RC style addresses
public method | TopLeftToString | Converts the top left corner of the reference to a string address
public method | TopLeftToStringA | Converts the top left corner of the reference to a string address
public method | TopLeftToStringW | Converts the top left corner of the reference to a string address
public method | ToString | Returns the string address of the reference
public method | ToStringA | Returns the string address of the reference
public method | ToStringW | Returns the string address of the reference

Limits

MaxCol | Returns the maximum legal column number (counting from 0)
MaxRow | Returns the maximum legal column number (counting from 0)

Comparisons

public method | Compare | Compare the contents of this CXlRef with another
public method | operator != | Compare the contents of this CXlRef with another
public method | operator < | Compare the contents of this CXlRef with another
public method | operator <= | Compare the contents of this CXlRef with another
public method | operator == | Compare the contents of this CXlRef with another
public method | operator > | Compare the contents of this CXlRef with another
public method | operator >= | Compare the contents of this CXlRef with another

Requirements

Header: xllplus.h

See Also

CXlRef Class | xllplus.h | CXlOper object


CXlRef::Bottom

Returns a reference to the bottom row number of the reference

RW12& Bottom( );
RW12 Bottom( ) const;

Return Value

A reference to, or the value of, the bottom row number of the CXlRef.

Remarks

This function can be used to update and to read the value contained in the CXlRef.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::BottomRightToString

Converts the bottom right corner of the reference to a string address

CString BottomRightToString(
   BOOL bA1 = FALSE,
   BOOL bLocalLanguage = FALSE
) const;

Parameters

bA1

TRUE to have the address in A1 format; FALSE for R1C1 format.
bLocalLanguage

TRUE to have the address in the local language; FALSE for English. This setting as no impact on A1-style addresses. R1C1 format addresses use different letters in different languages: thus the English address "R1C2" is written as "Z1S2" in German, if bLocalLanguage is TRUE.

Return Value

A string containing the address of the bottom right cell of the range.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::BottomRightToStringA

Converts the bottom right corner of the reference to a string address

CStringA BottomRightToStringA(
   BOOL bA1 = FALSE,
   BOOL bLocalLanguage = FALSE
) const;

Parameters

bA1

TRUE to have the address in A1 format; FALSE for R1C1 format.
bLocalLanguage

TRUE to have the address in the local language; FALSE for English. This setting as no impact on A1-style addresses. R1C1 format addresses use different letters in different languages: thus the English address "R1C2" is written as "Z1S2" in German, if bLocalLanguage is TRUE.

Return Value

A string containing the address of the bottom right cell of the range.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::BottomRightToStringW

Converts the bottom right corner of the reference to a string address

CStringW BottomRightToStringW(
   BOOL bA1 = FALSE,
   BOOL bLocalLanguage = FALSE
) const;

Parameters

bA1

TRUE to have the address in A1 format; FALSE for R1C1 format.
bLocalLanguage

TRUE to have the address in the local language; FALSE for English. This setting as no impact on A1-style addresses. R1C1 format addresses use different letters in different languages: thus the English address "R1C2" is written as "Z1S2" in German, if bLocalLanguage is TRUE.

Return Value

A string containing the address of the bottom right cell of the range.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::ColToA

Converts a column number to its A1 style column letter(s)

CString ColToA(
   COL12 cColumn
) const;

Parameters

cColumn

Column number - 0 represents the left-most column.

Return Value

A string containing the column's name in A1 format. This may contain one, two or three letters.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::ColToAA

Converts a column number to its A1 style column letter(s)

CStringA ColToAA(
   COL12 cColumn
) const;

Parameters

cColumn

Column number - 0 represents the left-most column.

Return Value

A string containing the column's name in A1 format. This may contain one, two or three letters.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::ColToAW

Converts a column number to its A1 style column letter(s)

CStringW ColToAW(
   COL12 cColumn
) const;

Parameters

cColumn

Column number - 0 represents the left-most column.

Return Value

A string containing the column's name in A1 format. This may contain one, two or three letters.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::Compare

Compare the contents of this CXlRef with another

int Compare(
   const CXlRef& other
) const;

Parameters

other

An initialised CXlRef.

Return Value

Returns 1 if the value in this object is greater than that in other, -1 if other is less and 0 if the two are equal.

Remarks

This function acts like strcmp() and similar 'C' library functions.

Note that CXlRefs are sorted by rows first and then by columns.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::CXlRef

Constructs a CXlRef object

CXlRef( );
CXlRef(
   const char* psz
);
CXlRef(
   const wchar_t* psz
);
CXlRef(
   RW12 rTop,
   COL12 cLeft,
   RW12 rBottom,
   COL12 cRight
);
CXlRef(
   RW12 wRow,
   COL12 bColumn
);
CXlRef(
   const XLREF4& xlref4
);
CXlRef(
   const XLREF12& xlref12
);

Parameters

psz

The string address of a cell or a range.
rTop

The top row of a range.
cLeft

The left-most column of a range.
rBottom

The bottom row of a range.
cRight

The right-most column of a range.
wRow

The row of a single cell.
bColumn

The column of a single cell.
xlref4

An initialised XLREF4.
xlref12

An initialised XLREF12.

Remarks

This constructor initialises the XLREF contained by the CXlRef to reflect the values passed as parameters.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::FromString

Reads a string address into the reference

BOOL FromString(
   const char* psz,
   BOOL bLocalLanguage = FALSE,
   BOOL allowA1 = TRUE,
   BOOL allowRC = TRUE
);
BOOL FromString(
   const wchar_t* psz,
   BOOL bLocalLanguage = FALSE,
   BOOL allowA1 = TRUE,
   BOOL allowRC = TRUE
);
BOOL FromString(
   const char* psz,
   BOOL bLocalLanguage,
   BOOL allowA1,
   BOOL allowRC,
   BOOL& isRC
);
BOOL FromString(
   const wchar_t* psz,
   BOOL bLocalLanguage,
   BOOL allowA1,
   BOOL allowRC,
   BOOL& isRC
);

Parameters

psz

The string address of a cell or a range.
bLocalLanguage

TRUE if the address is in the local language; FALSE for English. This setting as no impact on A1-style addresses. R1C1 format addresses use different letters in different languages: thus the English address "R1C2" is written as "Z1S2" in German. If bLocalLanguage is TRUE, then the local letters are expected.

allowA1

TRUE if the address may be in A1 format, FALSE if A1 format will be rejected.

allowRC

TRUE if the address may be in R1C1 format, FALSE if R1C1 format will be rejected.

psz

The string address of a cell or a range.
isRC

This will be set to TRUE if the fuinction succeeds and the address was in R1C1 format, and will be set to FALSE otherwise.

Return Value

TRUE if the string address is valid; FALSE otherwise.

Remarks

This function translates the cell address given in the parameter to a range.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::GetRowColumnLetters

Returns the letters used for RC style addresses

static BOOL GetRowColumnLetters(
   char& chRow,
   char& chColumn,
   BOOL bLocalLanguage
);
static BOOL GetRowColumnLetters(
   wchar_t& chRow,
   wchar_t& chColumn,
   BOOL bLocalLanguage
);

Parameters

chRow

If successful, will contain the letter used for rows in RC-style addresses.
chColumn

If successful, will contain the letter used for columns in RC-style addresses.
bLocalLanguage

TRUE if the letters are for the local language; FALSE for English. R1C1 format addresses use different letters in different languages: thus the English address "R1C2" is written as "Z1S2" in German. If bLocalLanguage is TRUE, then the local letters are returned; if bLocalLanguage is FALSE, then the results are always "R" and "C".

Return Value

TRUE if the letters are found; FALSE otherwise.

Remarks

This function gets the letters used in RC-style addresses. These are used in the string functions ToString() and FromString().

Availability

If bLocalLanguage is TRUE, this function can only be called from macro functions, or from worksheet functions that have been marked as "Defer recalculation". It will always fail if called from worksheet functions that have not been marked as "Defer recalculation", if bLocalLanguage is TRUE.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::Height

Returns the number of rows in the reference

RW12 Height( ) const;

Return Value

The number of rows contained by the CXlRef, equal to Bottom() + 1 - Top().

Example

CXlOper::GetCaller() Example

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::Init

Initialise the CXlRef contents

void Init( );

Remarks

This function initialises all the values in the CXlRef to zero. These values represent the single cell A1.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::IsSingle

Is this a reference to a single cell ?

BOOL IsSingle( ) const;

Return Value

TRUE if the range contains only one cell; FALSE otherwise.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::Left

Returns a reference to the leftmost column number of the reference

COL12& Left( );
COL12 Left( ) const;

Return Value

A reference to, or the value of, the left column number of the CXlRef.

Remarks

This function can be used to update and to read the value contained in the CXlRef.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::MaxCol

Returns the maximum legal column number (counting from 0)

static long MaxCol( );

Return Value

The maximum legal column number, counting from 0 as column A.

Remarks

This is 255 in all versions of Excel up to Excel 11 (Excel 97). For Excel 12 it is 16384.

You can find more information about the limits of array sizes in System Limits.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods | CXlRef::MaxRow() | System Limits


CXlRef::MaxRow

Returns the maximum legal column number (counting from 0)

static long MaxRow( );

Return Value

The maximum legal row number, counting from 0 for the top-most row.

Remarks

This is 16383 in all versions of Excel before 8 (Excel 97). For Excel 8 to 11 it is 65535. For Excel 12 it is 1048575.

You can find more information about the limits of array sizes in System Limits.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods | CXlRef::MaxCol() | System Limits


CXlRef::MoveBy

Moves a reference by the specified number of rows and columns

BOOL MoveBy(
   long nRows,
   long nCols
);

Parameters

nRows

Number of rows to move by (negative is up, positive is down).
nCols

Number of columns to move by (negative is left, positive is right).

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the resulting address would be out of range.

Remarks

This method moves the CXlRef by the offsets provided. Left and Right will each be moved by nCols; Top and Bottom will each be moved by nRows. (Height and Width will be unaffected.)

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::Normalize

Normalize the coordinates of the reference

void Normalize( );

Remarks

This function normalises the coordinates of the reference. Thus if the left column is greater than the right, the two values are swapped. If the top row is greater than the bottom, the two values are swapped.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::operator !=

Compare the contents of this CXlRef with another

int operator !=(
   const CXlRef& other
) const;

Parameters

other

An initialised CXlRef.

Return Value

Returns TRUE if the value in this object is not equal to other; returns FALSE otherwise.

Remarks

Note that CXlRefs are sorted by rows first and then by columns.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::operator <

Compare the contents of this CXlRef with another

int operator <(
   const CXlRef& other
) const;

Parameters

other

An initialised CXlRef.

Return Value

Returns TRUE if the value in this object is less than other; returns FALSE otherwise.

Remarks

Note that CXlRefs are sorted by rows first and then by columns.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::operator <=

Compare the contents of this CXlRef with another

int operator <=(
   const CXlRef& other
) const;

Parameters

other

An initialised CXlRef.

Return Value

Returns TRUE if the value in this object is less than or equal to other; returns FALSE otherwise.

Remarks

Note that CXlRefs are sorted by rows first and then by columns.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::operator =

Assigns a new value to the XLREF, using a variety of input types

const CXlRef& operator =(
   const CXlRef& xlref
);
const CXlRef& operator =(
   const char* psz
);
const CXlRef& operator =(
   const wchar_t* psz
);
const CXlRef& operator =(
   const XLREF4& xlref4
);
const CXlRef& operator =(
   const XLREF12& xlref12
);

Parameters

xlref

An initialised instance of CXlRef, which will be copied.
psz

The string address of a cell or a range.
xlref4

An initialised XLREF4.
xlref12

An initialised XLREF12.

Remarks

This second and third forms of the operator are equivalent to the FromString() method.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::operator ==

Compare the contents of this CXlRef with another

int operator ==(
   const CXlRef& other
) const;

Parameters

other

An initialised CXlRef.

Return Value

Returns TRUE if the value in this object is equal to other; returns FALSE otherwise.

Remarks

Note that CXlRefs are sorted by rows first and then by columns.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::operator >

Compare the contents of this CXlRef with another

int operator >(
   const CXlRef& other
) const;

Parameters

other

An initialised CXlRef.

Return Value

Returns TRUE if the value in this object is greater than other; returns FALSE otherwise.

Remarks

Note that CXlRefs are sorted by rows first and then by columns.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::operator >=

Compare the contents of this CXlRef with another

int operator >=(
   const CXlRef& other
) const;

Parameters

other

An initialised CXlRef.

Return Value

Returns TRUE if the value in this object is greater than or equal to other; returns FALSE otherwise.

Remarks

Note that CXlRefs are sorted by rows first and then by columns.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::Resize

Resizes a reference to the specified number of rows and columns

BOOL Resize(
   RW12 nRows,
   COL12 nCols
);

Parameters

nRows

Number of rows reference should contain.
nCols

Number of columns reference should contain.

Return Value

Returns TRUE if the function was successful, FALSE if it failed. The function can fail if the resulting address would be out of range.

Remarks

This method resizes the CXlRef to the sizes provided. Left and Top will be unaffected; Right and Bottom will each be changed (to Left + nCols - 1 and Top + nRows - 1 respectively).

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::Right

Returns a reference to the rightmost column number of the reference

COL12& Right( );
COL12 Right( ) const;

Return Value

A reference to, or the value of, the right column number of the CXlRef.

Remarks

This function can be used to update and to read the value contained in the CXlRef.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::SetRef

Sets the values in the CXlRef

void SetRef(
   RW12 rTop,
   COL12 cLeft,
   RW12 rBottom,
   COL12 cRight
);
void SetRef(
   RW12 rRow,
   COL12 cColumn
);

Parameters

rTop

The top row of a range.
cLeft

The left-most column of a range.
rBottom

The bottom row of a range.
cRight

The right-most column of a range.
rRow

The row of a single cell.
cColumn

The column of a single cell.

Remarks

This method sets the XLREF contained by the CXlRef to reflect the values passed as parameters.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::Top

Returns a reference to the top row number of the reference

RW12& Top( );
RW12 Top( ) const;

Return Value

A reference to, or the value of, the top row number of the CXlRef.

Remarks

This function can be used to update and to read the value contained in the CXlRef.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::TopLeftToString

Converts the top left corner of the reference to a string address

CString TopLeftToString(
   BOOL bA1 = FALSE,
   BOOL bLocalLanguage = FALSE
) const;

Parameters

bA1

TRUE to have the address in A1 format; FALSE for R1C1 format.
bLocalLanguage

TRUE to have the address in the local language; FALSE for English. This setting as no impact on A1-style addresses. R1C1 format addresses use different letters in different languages: thus the English address "R1C2" is written as "Z1S2" in German, if bLocalLanguage is TRUE.

Return Value

A string containing the address of the top left cell of the range.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::TopLeftToStringA

Converts the top left corner of the reference to a string address

CStringA TopLeftToStringA(
   BOOL bA1 = FALSE,
   BOOL bLocalLanguage = FALSE
) const;

Parameters

bA1

TRUE to have the address in A1 format; FALSE for R1C1 format.
bLocalLanguage

TRUE to have the address in the local language; FALSE for English. This setting as no impact on A1-style addresses. R1C1 format addresses use different letters in different languages: thus the English address "R1C2" is written as "Z1S2" in German, if bLocalLanguage is TRUE.

Return Value

A string containing the address of the top left cell of the range.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::TopLeftToStringW

Converts the top left corner of the reference to a string address

CStringW TopLeftToStringW(
   BOOL bA1 = FALSE,
   BOOL bLocalLanguage = FALSE
) const;

Parameters

bA1

TRUE to have the address in A1 format; FALSE for R1C1 format.
bLocalLanguage

TRUE to have the address in the local language; FALSE for English. This setting as no impact on A1-style addresses. R1C1 format addresses use different letters in different languages: thus the English address "R1C2" is written as "Z1S2" in German, if bLocalLanguage is TRUE.

Return Value

A string containing the address of the top left cell of the range.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::ToString

Returns the string address of the reference

CString ToString(
   BOOL bA1 = FALSE,
   BOOL bLocalLanguage = FALSE
) const;

Parameters

bA1

TRUE to have the address in A1 format; FALSE for R1C1 format.
bLocalLanguage

TRUE to have the address in the local language; FALSE for English. This setting as no impact on A1-style addresses. R1C1 format addresses use different letters in different languages: thus the English address "R1C2" is written as "Z1S2" in German, if bLocalLanguage is TRUE.

Return Value

A string containing the address of the CXlRef.

Example

MyAddress Example

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::ToStringA

Returns the string address of the reference

CStringA ToStringA(
   BOOL bA1 = FALSE,
   BOOL bLocalLanguage = FALSE
) const;

Parameters

bA1

TRUE to have the address in A1 format; FALSE for R1C1 format.
bLocalLanguage

TRUE to have the address in the local language; FALSE for English. This setting as no impact on A1-style addresses. R1C1 format addresses use different letters in different languages: thus the English address "R1C2" is written as "Z1S2" in German, if bLocalLanguage is TRUE.

Return Value

A string containing the address of the CXlRef.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::ToStringW

Returns the string address of the reference

CStringW ToStringW(
   BOOL bA1 = FALSE,
   BOOL bLocalLanguage = FALSE
) const;

Parameters

bA1

TRUE to have the address in A1 format; FALSE for R1C1 format.
bLocalLanguage

TRUE to have the address in the local language; FALSE for English. This setting as no impact on A1-style addresses. R1C1 format addresses use different letters in different languages: thus the English address "R1C2" is written as "Z1S2" in German, if bLocalLanguage is TRUE.

Return Value

A string containing the address of the CXlRef.

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


CXlRef::Width

Returns the number of columns in the reference

COL12 Width( ) const;

Return Value

The number of columns contained by the CXlRef, equal to Right() + 1 - Left().

Example

CXlOper::GetCaller() Example

Requirements

Header: xllplus.h

See Also

CXlRef Class | CXlRef Methods


Global functions & macros

Global functions & macros are listed here.

Registration

public method | IMPLEMENT_XLLFN_EX | Declare and describe an add-in function
public method | IMPLEMENT_XLLFN2 | Declare and describe an add-in function
public method | IMPLEMENT_XLLFN3 | Declare and describe an add-in function
public method | IMPLEMENT_XLLFN4 | Declare and describe an add-in function

Global data

public method | XLL_FIX_STATE | Ensure that global data is in scope (MFC calls only)
public method | XllGetApp | Get a pointer to the global application object
public method | XllGetTypedApp | Get a correctly typed pointer to the global application object
public method | XllGetVersion | Get the XLL+ version number

Requirements

Header: xllplus.h

See Also

xllplus.h


::IMPLEMENT_XLLFN_EX

Declare and describe an add-in function

IMPLEMENT_XLLFN_EX(
   LABEL nmEntryPoint,
   const char* pszArgTemplate,
   const char* pszName,
   const char* pszCategory,
   const char* pszArgNames,
   const char* pszHelpText,
   const char* pszArgHelpText,
   int usAvailability
);

Parameters

nmEntryPoint

Name of the 'C' function. Note that the function name is not in quotes - it is a label, not a string. Most of the other arguments to the macro are strings, so they can be either string literals (such as "RB") or references to strings (e.g. CMyXllApp::m_pszDefCategory).
pszArgTemplate

The type text of the function, containing the data type of the return value and data types of the arguments. The first letter of the type text specifies the return value. Subsequent letters, starting with the second, specify the data types of the arguments, in order. For a list of data types and the letters used to represent them see Data types. Thus if, for example, if the string is "AB", it represents a function that returns a Boolean result and takes one double argument. See the table in Data types for a full list of the data types supported.

In addition, the string can be terminated by one or both of the characters '#' and '!'. The hash symbol ('#') indicates that resolution of the function's arguments is delayed. Experienced SDK programmers will appreciate the occasional utility of this option. See the Excel 97 Developer's Kit (Microsoft Press) for more information.

The '!' suffix makes the function volatile. Volatile functions are resolved every time any part of a worksheet is recalculated, or when the F9 function key is pressed or when Application.Calculate() is invoked. This option is useful when the results of functions are determined by outside factors (such as the current time, or data held in a database) in addition to the value of their arguments.
pszName

Name of function as exported to Excel. This is the function's name as you will use it in Excel - it does not need to be the same as the 'C' name of the function.
pszCategory

The category under which the function will appear in the Excel Function Wizard.
pszArgNames

The names of the function's arguments, separated by commas. For example, "Arg1,Arg2".
pszHelpText

The description of the function which will appear in the Excel Function Wizard.
pszArgHelpText

The descriptions of the function's arguments which will appear in the Excel Function Wizard. Each description should be separated from the next by a null character ("\0"). An extra null character should terminate the string. Thus a function that concatenates its two arguments might have argument help text as follows: "Left-hand string\0Right-hand string\0\0".
usAvailability

Flag indicating from where the function may be invoked. 1 indicates that the function is available only from Excel worksheets; 2 that it is available only from Excel macro sheets; 3 that it is available in both. No other values are acceptable.

Remarks

Note: The IMPLEMENT_XLLFN_EX macro is deprecated. The macro IMPLEMENT_XLLFN3 should be used instead. IMPLEMENT_XLLFN3 offers a more powerful set of arguments.

The IMPLEMENT_XLLFN_EX macro manages the registration of a 'C' function as an Excel add-in function. It is supported by the XLL Plus Function Wizard, which can be used to maintain the code for both the macro and the function definition.

The macro defines a static instance of a 'C' structure (XLLFN) which contains the details that define the add-in function. It also defines another 'C' structure (XLLFN_INIT) whose constructor function will add the address of the XLLFN to a global chain intitialised at DLL load time, before any other methods or call-back functions are invoked.

When the function AddStaticFns() is called during the DLL's InitInstance() method, the functions defined in the global chain are added to the CXllApp object's function list. During the XllLoad operation invoked by Excel when the XLL is opened, this list of functions is registered with Excel using the SDK xlfRegister entry-point.

Note Note:

This macro is deprecated. Use IMPLEMENT_XLLFN4 instead.

Requirements

Header: xllplus.h

See Also

Global functions & macros


::IMPLEMENT_XLLFN2

Declare and describe an add-in function

IMPLEMENT_XLLFN2(
   LABEL nmEntryPoint,
   const char* pszArgTemplate,
   const char* pszName,
   const char* pszCategory,
   const char* pszArgNames,
   const char* pszHelpText,
   const char* pszArgHelpText,
   const char* pszExt,
   int usAvailability
);

Parameters

nmEntryPoint

Name of the 'C' function. Note that the function name is not in quotes - it is a label, not a string. Most of the other arguments to the macro are strings, so they can be either string literals (such as "RB") or references to strings (e.g. CMyXllApp::m_pszDefCategory).
pszArgTemplate

The type text of the function, containing the data type of the return value and data types of the arguments. The first letter of the type text specifies the return value. Subsequent letters, starting with the second, specify the data types of the arguments, in order. For a list of data types and the letters used to represent them see Data types. Thus if, for example, if the string is "AB", it represents a function that returns a Boolean result and takes one double argument. See the table in Data types for a full list of the data types supported.

In addition, the string can be terminated by one or both of the characters '#' and '!'. The hash symbol ('#') indicates that resolution of the function's arguments is delayed. Experienced SDK programmers will appreciate the occasional utility of this option. See the Excel 97 Developer's Kit (Microsoft Press) for more information.

The '!' suffix makes the function volatile. Volatile functions are resolved every time any part of a worksheet is recalculated, or when the F9 function key is pressed or when Application.Calculate() is invoked. This option is useful when the results of functions are determined by outside factors (such as the current time, or data held in a database) in addition to the value of their arguments.
pszName

Name of function as exported to Excel. This is the function's name as you will use it in Excel - it does not need to be the same as the 'C' name of the function.
pszCategory

The category under which the function will appear in the Excel Function Wizard.

This argument is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Category for more information.
pszArgNames

The names of the function's arguments, separated by commas. For example, "Arg1,Arg2".

See pszExt below for information on localizing the argument name.
pszHelpText

The description of the function which will appear in the Excel Function Wizard.

This help text is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Help text for more information.
pszArgHelpText

The descriptions of the function's arguments which will appear in the Excel Function Wizard. Each description should be separated from the next by a null character ("\0"). An extra null character should terminate the string. Thus a function that concatenates its two arguments might have argument help text as follows: "Left-hand string\0Right-hand string\0\0".

Each of the arguments' help texts is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Help text for more information.
pszExt

The extended properties used by the add-in function's arguments. These can include, for instance, the fact that an argument is a vector or matrix of a specific type, it's bounds, and various other flag settings. These extended properties are read and written by the XLL+ Function Wizard, and are used to generate code to read and translate the arguments. They are ignored by the run-time library, with the exception of argument resource IDs, as described below.

If the extension for an argument contains a resource ID, as entered into the Resource ID column of the XLL+ Function Wizard, then it is transformed with XllLoadString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Argument names for more information.
usAvailability

Flag indicating from where the function may be invoked. 1 indicates that the function is available only from Excel worksheets; 2 that it is available only from Excel macro sheets; 3 that it is available in both. No other values are acceptable.

Remarks

Note: The IMPLEMENT_XLLFN2 macro is deprecated. The macro IMPLEMENT_XLLFN3 should be used instead. IMPLEMENT_XLLFN3 offers a more powerful set of arguments.

The IMPLEMENT_XLLFN2 macro manages the registration of a 'C' function as an Excel add-in function. It is supported by the XLL Plus Function Wizard, which can be used to maintain the code for both the macro and the function definition.

Note that several of the string arguments to the macro accept resource ID strings which are loaded from the application resource file at run-time.

The macro defines a static instance of a 'C' structure (XLLFN) which contains the details that define the add-in function. It also defines another 'C' structure (XLLFN_INIT) whose constructor function will add the address of the XLLFN to a global chain intitialised at DLL load time, before any other methods or call-back functions are invoked.

When the function AddStaticFns() is called during the DLL's InitInstance() method, the functions defined in the global chain are added to the CXllApp object's function list. During the XllLoad operation invoked by Excel when the XLL is opened, this list of functions is registered with Excel using the SDK xlfRegister entry-point.

Note Note:

This macro is deprecated. Use IMPLEMENT_XLLFN4 instead.

Requirements

Header: xllplus.h

See Also

Global functions & macros


::IMPLEMENT_XLLFN3

Declare and describe an add-in function

IMPLEMENT_XLLFN3(
   LABEL nmEntryPoint,
   LABEL nmEntryPoint4,
   LABEL nmEntryPoint12,
   const char* pszArgTemplate4,
   const wchar_t* pszArgTemplate12,
   const wchar_t* pszName,
   const char* pszArgNames4,
   const wchar_t* pszArgNames12,
   const char* pszCategory4,
   const wchar_t* pszCategory12,
   const char* pszHelpText4,
   const wchar_t* pszHelpText12,
   const char* pszArgHelpText4,
   const wchar_t* pszArgHelpText12,
   unsigned int usHelpTopic,
   const wchar_t* pszHelpTopic,
   const wchar_t* pszExt12,
   int usType
);

Parameters

nmEntryPoint

Unique name of the add-in function. Note that the function name is not in quotes - it is a label, not a string. Most of the other arguments to the macro are strings, so they can be either string literals (such as _T("RB")) or references to strings (e.g. CMyXllApp::m_pszDefCategory).

nmEntryPoint4

Unique name of the add-in function's wrapper function, as used by Excel 2003 and earlier. Note that the function name is not in quotes - it is a label, not a string.

nmEntryPoint12

Unique name of the add-in function's wrapper function, as used by Excel 2007 and above. Note that the function name is not in quotes - it is a label, not a string.

pszArgTemplate4

The type text of the function as used by Excel 2003 and earlier, containing the data type of the return value and data types of the arguments. The first letter of the type text specifies the return value. Subsequent letters, starting with the second, specify the data types of the arguments, in order. For a list of data types and the letters used to represent them see Data types. Thus if, for example, if the string is "AB", it represents a function that returns a Boolean result and takes one double argument. See the table in Data types for a full list of the data types supported.

In addition, the string can be terminated by one or both of the characters '#' and '!'. The hash symbol ('#') indicates that resolution of the function's arguments is delayed. Experienced SDK programmers will appreciate the occasional utility of this option. See the Excel 97 Developer's Kit (Microsoft Press) for more information.

The '!' suffix makes the function volatile. Volatile functions are resolved every time any part of a worksheet is recalculated, or when the F9 function key is pressed or when Application.Calculate() is invoked. This option is useful when the results of functions are determined by outside factors (such as the current time, or data held in a database) in addition to the value of their arguments.

pszArgTemplate12

The type text of the function as used by Excel 2007 and above, containing the data type of the return value and data types of the arguments. The first letter of the type text specifies the return value. Subsequent letters, starting with the second, specify the data types of the arguments, in order. For a list of data types and the letters used to represent them see Data types. Thus if, for example, if the string is "AB", it represents a function that returns a Boolean result and takes one double argument. See the table in Data types for a full list of the data types supported.

In addition, the string can be terminated by any or all of the characters '#', '!' and '$'. The hash symbol ('#') indicates that resolution of the function's arguments is delayed. Experienced SDK programmers will appreciate the occasional utility of this option. See the Excel 97 Developer's Kit (Microsoft Press) for more information.

The '!' suffix makes the function volatile. Volatile functions are resolved every time any part of a worksheet is recalculated, or when the F9 function key is pressed or when Application.Calculate() is invoked. This option is useful when the results of functions are determined by outside factors (such as the current time, or data held in a database) in addition to the value of their arguments.

The '$' suffix declares that the function is thread-safe. This permits the Excel calculation engine to call the function in multiple threads and on multiple processors.
pszName

Name of function as exported to Excel. This is the function's name as you will use it in Excel - it does not need to be the same as the 'C' name of the function.

pszArgNames4

The names of the function's arguments, as used by Excel 2003 and earlier, separated by commas. For example, "Arg1,Arg2".

You can localize each argument name by using resoure IDs.

pszArgNames12

The names of the function's arguments, as used by Excel 2007 and above, separated by commas. For example, L"Arg1,Arg2".

You can localize each argument name by using resoure IDs.

pszCategory4

The category under which the function will appear in the Excel Function Wizard, under Excel 2003 and below.

This argument is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Category for more information.

pszCategory12

The category under which the function will appear in the Excel Function Wizard, under Excel 2007 and above.

This argument is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Category for more information.

pszHelpText4

The description of the function which will appear in the Excel Function Wizard, under Excel 2003 and below.

This help text is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Help text for more information.

pszHelpText12

The description of the function which will appear in the Excel Function Wizard, under Excel 2007 and above.

This help text is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Help text for more information.

pszArgHelpText4

The descriptions of the function's arguments which will appear in the Excel Function Wizard, under Excel 2003 and below. Each description should be separated from the next by a null character ("\0"). An extra null character should terminate the string. Thus a function that concatenates its two arguments might have argument help text as follows: "Left-hand string\0Right-hand string\0\0".

Each of the arguments' help texts is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Help text for more information.

pszArgHelpText12

The descriptions of the function's arguments which will appear in the Excel Function Wizard, under Excel 2007 and above. Each description should be separated from the next by a null character ("\0"). An extra null character should terminate the string. Thus a function that concatenates its two arguments might have argument help text as follows: L"Left-hand string\0Right-hand string\0\0".

Each of the arguments' help texts is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Help text for more information.

usHelpTopic

The Help ID of the topic that describes this add-in function. 0 indicates that no help is available.

pszHelpTopic

The name of the topic that describes this add-in function. If this string is empty, then usHelpTopic will be used.

pszExt12

A full definition of the function, in a proprietary format. It is this string that is read by the XLL+ Function Wizard, since it contains a complete definition of the function.

usType

Flag indicating from where the function may be invoked. 1 indicates that the function is available only from Excel worksheets; 2 that it is available only from Excel macro sheets; 3 that it is available in both. No other values are acceptable.

Remarks

The IMPLEMENT_XLLFN3 macro manages the registration of a 'C' function as an Excel add-in function. It is supported by the XLL Plus Function Wizard, which can be used to maintain the code for both the macro and the function definition.

Note that several of the string arguments to the macro accept resource ID strings which are loaded from the application resource file at run-time.

The macro defines a static instance of a 'C' structure (XLLFN) which contains the details that define the add-in function. It also defines another 'C' structure (XLLFN_INIT) whose constructor function will add the address of the XLLFN to a global chain intitialised at DLL load time, before any other methods or call-back functions are invoked.

When the function AddStaticFns() is called during the DLL's InitInstance() method, the functions defined in the global chain are added to the CXllApp object's function list. During the XllLoad operation invoked by Excel when the XLL is opened, this list of functions is registered with Excel using the SDK xlfRegister entry-point.

Note Note:

This macro is deprecated. Use IMPLEMENT_XLLFN4 instead.

Requirements

Header: xllplus.h

See Also

Global functions & macros


::IMPLEMENT_XLLFN4

Declare and describe an add-in function

IMPLEMENT_XLLFN4(
   LABEL nmEntryPoint,
   LABEL nmEntryPoint4,
   LABEL nmEntryPoint12,
   const char* pszArgTemplate4,
   const wchar_t* pszArgTemplate12,
   const wchar_t* pszName,
   const char* pszArgNames4,
   const wchar_t* pszArgNames12,
   const char* pszCategory4,
   const wchar_t* pszCategory12,
   const char* pszHelpText4,
   const wchar_t* pszHelpText12,
   const char* pszArgHelpText4,
   const wchar_t* pszArgHelpText12,
   unsigned int usHelpTopic,
   const wchar_t* pszHelpTopic,
   const wchar_t* pszExt12,
   int usType,
   int usMinVersion,
   int usMaxVersion
);

Parameters

nmEntryPoint

Unique name of the add-in function. Note that the function name is not in quotes - it is a label, not a string. Most of the other arguments to the macro are strings, so they can be either string literals (such as _T("RB")) or references to strings (e.g. CMyXllApp::m_pszDefCategory).

nmEntryPoint4

Unique name of the add-in function's wrapper function, as used by Excel 2003 and earlier. Note that the function name is not in quotes - it is a label, not a string.

nmEntryPoint12

Unique name of the add-in function's wrapper function, as used by Excel 2007 and above. Note that the function name is not in quotes - it is a label, not a string.

pszArgTemplate4

The type text of the function as used by Excel 2003 and earlier, containing the data type of the return value and data types of the arguments. The first letter of the type text specifies the return value. Subsequent letters, starting with the second, specify the data types of the arguments, in order. For a list of data types and the letters used to represent them see Data types. Thus if, for example, if the string is "AB", it represents a function that returns a Boolean result and takes one double argument. See the table in Data types for a full list of the data types supported.

In addition, the string can be terminated by one or both of the characters '#' and '!'. The hash symbol ('#') indicates that resolution of the function's arguments is delayed. Experienced SDK programmers will appreciate the occasional utility of this option. See the Excel 97 Developer's Kit (Microsoft Press) for more information.

The '!' suffix makes the function volatile. Volatile functions are resolved every time any part of a worksheet is recalculated, or when the F9 function key is pressed or when Application.Calculate() is invoked. This option is useful when the results of functions are determined by outside factors (such as the current time, or data held in a database) in addition to the value of their arguments.

pszArgTemplate12

The type text of the function as used by Excel 2007 and above, containing the data type of the return value and data types of the arguments. The first letter of the type text specifies the return value. Subsequent letters, starting with the second, specify the data types of the arguments, in order. For a list of data types and the letters used to represent them see Data types. Thus if, for example, if the string is "AB", it represents a function that returns a Boolean result and takes one double argument. See the table in Data types for a full list of the data types supported.

In addition, the string can be terminated by any or all of the characters '#', '!' and '$'. The hash symbol ('#') indicates that resolution of the function's arguments is delayed. Experienced SDK programmers will appreciate the occasional utility of this option. See the Excel 97 Developer's Kit (Microsoft Press) for more information.

The '!' suffix makes the function volatile. Volatile functions are resolved every time any part of a worksheet is recalculated, or when the F9 function key is pressed or when Application.Calculate() is invoked. This option is useful when the results of functions are determined by outside factors (such as the current time, or data held in a database) in addition to the value of their arguments.

The '$' suffix declares that the function is thread-safe. This permits the Excel calculation engine to call the function in multiple threads and on multiple processors.
pszName

Name of function as exported to Excel. This is the function's name as you will use it in Excel - it does not need to be the same as the 'C' name of the function.

pszArgNames4

The names of the function's arguments, as used by Excel 2003 and earlier, separated by commas. For example, "Arg1,Arg2".

You can localize each argument name by using resoure IDs.

pszArgNames12

The names of the function's arguments, as used by Excel 2007 and above, separated by commas. For example, L"Arg1,Arg2".

You can localize each argument name by using resoure IDs.

pszCategory4

The category under which the function will appear in the Excel Function Wizard, under Excel 2003 and below.

This argument is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Category for more information.

pszCategory12

The category under which the function will appear in the Excel Function Wizard, under Excel 2007 and above.

This argument is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Category for more information.

pszHelpText4

The description of the function which will appear in the Excel Function Wizard, under Excel 2003 and below.

This help text is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Help text for more information.

pszHelpText12

The description of the function which will appear in the Excel Function Wizard, under Excel 2007 and above.

This help text is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Help text for more information.

pszArgHelpText4

The descriptions of the function's arguments which will appear in the Excel Function Wizard, under Excel 2003 and below. Each description should be separated from the next by a null character ("\0"). An extra null character should terminate the string. Thus a function that concatenates its two arguments might have argument help text as follows: "Left-hand string\0Right-hand string\0\0".

Each of the arguments' help texts is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Help text for more information.

pszArgHelpText12

The descriptions of the function's arguments which will appear in the Excel Function Wizard, under Excel 2007 and above. Each description should be separated from the next by a null character ("\0"). An extra null character should terminate the string. Thus a function that concatenates its two arguments might have argument help text as follows: L"Left-hand string\0Right-hand string\0\0".

Each of the arguments' help texts is transformed with XllTranslateString before it is sent to Excel. Any numeric string resource IDs will be translated to strings from the resource file, if available. See International : Help text for more information.

usHelpTopic

The Help ID of the topic that describes this add-in function. 0 indicates that no help is available.

pszHelpTopic

The name of the topic that describes this add-in function. If this string is empty, then usHelpTopic will be used.

pszExt12

A full definition of the function, in a proprietary format. It is this string that is read by the XLL+ Function Wizard, since it contains a complete definition of the function.

usType

Flag indicating from where the function may be invoked. 1 indicates that the function is available only from Excel worksheets; 2 that it is available only from Excel macro sheets; 3 that it is available in both. No other values are acceptable.

usMinVersion

The minimum Excel major version number required. If the Excel major version number is less than this value, then the function will not be registered. Ignored if zero.

usMaxVersion

The maximum Excel major version number allowed. If the Excel major version number is greater than this value, then the function will not be registered. Ignored if zero.

Remarks

The IMPLEMENT_XLLFN4 macro manages the registration of a 'C' function as an Excel add-in function. It is supported by the XLL Plus Function Wizard, which can be used to maintain the code for both the macro and the function definition.

Note that several of the string arguments to the macro accept resource ID strings which are loaded from the application resource file at run-time.

The macro defines a static instance of a 'C' structure (XLLFN) which contains the details that define the add-in function. It also defines another 'C' structure (XLLFN_INIT) whose constructor function will add the address of the XLLFN to a global chain intitialised at DLL load time, before any other methods or call-back functions are invoked.

When the function AddStaticFns() is called during the DLL's InitInstance() method, the functions defined in the global chain are added to the CXllApp object's function list. During the XllLoad operation invoked by Excel when the XLL is opened, this list of functions is registered with Excel using the SDK xlfRegister entry-point.

Example

MySquare Example

Requirements

Header: xllplus.h

See Also

Global functions & macros


::XLL_FIX_STATE

Ensure that global data is in scope (MFC calls only)

XLL_FIX_STATE( );

Remarks

When Excel calls an add-in function, the static data structures which lie at the heart of the Microsoft Foundation Classes (MFC) are not yet properly initialised. It is necessary to ensure that MFC's static pointers are pointing to the frame of reference of the XLL.

The XLL_FIX_STATE macro achieves this. An instance of this macro will ensure the correct state of all MFC variables within the same scope as the macro. In particular, calls to AfxGetApp() will only succeed within the scope of an XLL_FIX_STATE macro.

Exceptions

All add-in functions generated by XLL+ version 6 have an instance of XLL_FIX_STATE in their outer "shell" function. There is therefore no requirement for the add-in function to have its own XLL_FIX_STATE.

The following virtual functions are always called within the scope of XLL_FIX_STATE, and thus do not need their own instance of XLL_FIX_STATE.

CXllApp::InitInstance
CXllApp::ExitInstance
CXllApp::OnXllRegister
CXllApp::OnXllRegisterEx
CXllApp::OnXllUnregister
CXllApp::OnXllLoad
CXllApp::OnXllUnload
CXllApp::OnXllOpen
CXllApp::OnXllOpenEx
CXllApp::OnXllClose

STL libraries

Note - this macro is required only for add-ins built using MFC. It is not required for add-ins that only use the STL libraries. In the STL build the macro is defined as empty. However, if you are writing reusable code that may later be included in an MFC project, then you should use the macro as instructed above.

Requirements

Header: xllplus.h

See Also

Global functions & macros


::XllGetApp

Get a pointer to the global application object

CXllApp* XllGetApp( );

Return Value

A pointer to the one and only application object.

Remarks

Your instance will be of a class descended from CXllApp, so you may wish to cast the result, thus:

CMyXllApp* pApp = (CMyXllApp*)XllGetApp();

MFC support

Note - The following applies only to add-ins built using the MFC libraries.

The function will ASSERT if MFC's state variables are not correctly set. In methods other than add-in functions that use MFC, you may need to declare the XLL_FIX_STATE macro (with function scope) before using XllGetApp().

Requirements

Header: xllplus.h

See Also

Global functions & macros | ::XllGetTypedApp | XLL_FIX_STATE


::XllGetTypedApp

Get a correctly typed pointer to the global application object

[CXllApp descended class]* XllGetTypedApp( );

Return Value

A correctly typed pointer to the one and only application object. The type will be the same as that of your application class.

Remarks

This function is defined by the XLL+ AppWizard in your project file.

It returns a pointer cast to the type of your project's application class.

Defining XllGetTypedApp

Projects generated by versions of XLL+ AppWizard before 4.2.4 will not include this function. If you want to add it yourself, add a line similar to the following to the main header file, just after the class definition.

inline CMyXllApp* XllGetTypedApp() { return (CMyXllApp*)XllGetApp(); }

MFC support

Note - The following applies only to add-ins built using the MFC libraries.

The function will ASSERT if MFC's state variables are not correctly set. In methods other than add-in functions that use MFC, you may need to declare the XLL_FIX_STATE macro (with function scope) before using XllGetApp().

Requirements

Header: xllplus.h

See Also

Global functions & macros | ::XllGetApp | XLL_FIX_STATE


::XllGetVersion

Get the XLL+ version number

CString XllGetVersion( );

Return Value

A string containing the XLL+ version against which this XLL was built, in the form "[major].[minor].[revision]", e.g. "6.0.1".

Requirements

Header: xllplus.h

See Also

Global functions & macros | CXllApp::GetXlVersion


Enumerations

The enumerations declared in xllplus.h are listed below.

XlErrorType
XlMessageBoxTypes

Requirements

Header: xllplus.h

See Also

xllplus.h


XlErrorType Enumeration

The set of error values that can be displayed in Excel.

enum XlErrorType

Overview

The XlErrorType enumeration lists the values that are used to indicate error results in Excel.

Members

xlerrValue | 15 | #VALUE! Occurs when the wrong type of argument or operand is used.
xlerrDiv0 | 7 | #DIV/0! Occurs when a number is divided by zero (0).
xlerrName | 29 | #NAME? Occurs when Microsoft Excel doesn't recognize text in a formula.
xlerrNA | 42 | #N/A Occurs when a value is not available to a function or formula.
xlerrRef | 23 | #REF! Occurs when a cell reference is not valid.
xlerrNum | 36 | #NUM! Occurs with invalid numeric values in a formula or function.
xlerrNull | 0 | #NULL! Occurs when you specify an intersection of two areas that do not intersect. The intersection operator is a space between references.

Requirements

Header: xllplus.h

See Also

xllplus.h | Exceptions | CXlErrorException


XlMessageBoxTypes Enumeration

The set of message box types that can be used to show Excel modal message boxes.

enum XlMessageBoxTypes

Overview

The XlMessageBoxTypes enumeration lists the values that can be passed to CXllApp::XlMessageBox.

Members

XlMessageBoxTypeQuestion | 1 | Displays a dialog box containing the OK and Cancel buttons, and a Question icon. CXllApp::XlMessageBox() returns TRUE if the user chooses the OK button and FALSE if they choose the Cancel button.
XlMessageBoxTypeInformation | 2 | Displays a dialog box containing an OK button and an Information icon.
XlMessageBoxTypeExclamation | 3 | Displays a dialog box containing an OK button and an Exclamation icon.

Requirements

Header: xllplus.h

See Also

xllplus.h | CXllApp::XlMessageBox


cpplog.h

Overview

cpplog.h contains all the core classes and macro definitions for a simple logging mechanism based on the Apache log4j and log4cxx frameworks.

For an introduction to the design and use of the framework, see Logging in the User Guide.

Classes

The table below lists the C++ object classes declared in the header file.

Class | Description
Logger | A log reporting node, which passes log reports up a tree, and delivers them to log appenders.
LoggerPtr | A shared pointer to a logger.
Appender | The abstract base class from which all appenders are descended.
FileAppender | An appender which writes to a file.
RollingFileAppender | An appender which writes to a file, whose name changes at the start of each time period.
ConsoleAppender | An appender which writes to the console.
TraceAppender | An appender class which writes to the TRACE macro.
AtlTraceAppender | An appender class which writes to the ATLTRACE2 macro.
BasicConfigurator | Configures the logging framework to write errors to the console.
PropertyConfigurator | Configures the logging framework by reading a text file.
ModulePropertyConfigurator | Configures the logging framework by reading a text file, whose name and location is relative to the currently executing module.
XllConfigurator | Configures the logging framework for an XLL add-in, by reading a text file, whose name and location is relative to the currently executing module.

Macros

The table below lists the principal macros declared in the header file, in descending order of severity.

Name | Description
LOG_FATAL | Write a fatal error report to log.
LOG_ERROR | Write a non-fatal error report to log.
LOG_WARN | Write a warning to log.
LOG_INFO | Write an information report to log.
LOG_DEBUG | Write a debugging report to log.
LOG_TRACE | Write a very low-level report to log.

Enumerations

The table below lists the enumerations declared in the header file.

Enumeration | Description
LogLevel | Severity levels of log events.


Appender Class

An abstract base class for any stream, file or device to which logging events are to be written.

class psl::log::Appender

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

Appender Methods | cpplog.h | Logging (User Guide)


Appender Methods

The methods of the Appender class are listed here.

Properties

public method | getLayout | Returns the Layout object used for formatting log events
public method | setLayout | Sets the Layout object used for formatting log events

Overrideable functions

public method emitText Transforms an event to a text string

Construction

public method Appender Constructs a Appender object

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

Appender Class | cpplog.h | Logging (User Guide)


Appender::Appender

Constructs a Appender object

Appender( );

Requirements

Header: cpplog.h

See Also

Appender Class | Appender Methods


Appender::emitText

Transforms an event to a text string

virtual void emitText(
   const std::basic_string<TCHAR>& text
);

Parameters

text

The buffer to which the text will be written. Depending on the formatting pattern used, this may or may not include a new line.

Requirements

Header: cpplog.h

See Also

Appender Class | Appender Methods


Appender::getLayout

Returns the Layout object used for formatting log events

Layout* getLayout( ) const;

Requirements

Header: cpplog.h

See Also

Appender Class | Appender Methods


Appender::setLayout

Sets the Layout object used for formatting log events

void setLayout(
   ple::simple_shared_ptr<Layout>& layout
);

Parameters

layout

A shared pointer to an object descended from Layout.

Requirements

Header: cpplog.h

See Also

Appender Class | Appender Methods


AtlTraceAppender Class

An implementation of Appender that appends to the trace stream using ATLTRACE2.

class psl::log::AtlTraceAppender : public Appender

Requirements

To use this appender class in your code, ensure that the macro ATLTRACE2 is defined.

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

AtlTraceAppender Methods | cpplog.h | Logging (User Guide) | Appender class


AtlTraceAppender Methods

The methods of the AtlTraceAppender class are listed here.

Construction

public method AtlTraceAppender Constructs an AtlTraceAppender object

Methods of Appender

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

AtlTraceAppender Class | cpplog.h | Logging (User Guide) | Appender class


AtlTraceAppender::AtlTraceAppender

Constructs an AtlTraceAppender object

AtlTraceAppender( );
AtlTraceAppender(
   ple::simple_shared_ptr<Layout>& layout
);
AtlTraceAppender(
   Layout* playout
);

Parameters

layout

A shared pointer to an object descended from Layout.

playout

A pointer to an object descended from Layout. The Layout object (if not null) will now be owned by the FileAppender, and will be deleted when the FileAppender is destroyed.

Requirements

Header: cpplog.h

See Also

AtlTraceAppender Class | AtlTraceAppender Methods


BasicConfigurator Class

A simple class which configures the logging framework to write error messages to the console.

class psl::log::BasicConfigurator

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

BasicConfigurator Methods | cpplog.h | Logging (User Guide)


BasicConfigurator Methods

The methods of the BasicConfigurator class are listed here.

Configuration

configure Configures the logging framework

Construction

public method BasicConfigurator Constructs a BasicConfigurator object

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

BasicConfigurator Class | cpplog.h | Logging (User Guide)


BasicConfigurator::BasicConfigurator

Constructs a BasicConfigurator object

BasicConfigurator( );

Requirements

Header: cpplog.h

See Also

BasicConfigurator Class | BasicConfigurator Methods


BasicConfigurator::configure

Configures the logging framework

static void configure(
   const TCHAR* pattern = 0,
   LogLevel level = LL_DEFAULT
);

Parameters

pattern

A formatting pattern which wil be used to format the log messages sent to the console.

If a null string is used, then the default pattern, %-5p %c - %m%n, will be used.

See Formatting patterns for details.
level

The severity level which will be applied to the root logger. If omitted, the default level, ERROR, will be used.

Requirements

Header: cpplog.h

See Also

BasicConfigurator Class | BasicConfigurator Methods


ConsoleAppender Class

An implementation of Appender that appends to the console.

class psl::log::ConsoleAppender : public Appender

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

ConsoleAppender Methods | cpplog.h | Logging (User Guide) | Appender class


ConsoleAppender Methods

The methods of the ConsoleAppender class are listed here.

Construction

public method ConsoleAppender Constructs a ConsoleAppender object

Methods of Appender

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

ConsoleAppender Class | cpplog.h | Logging (User Guide) | Appender class


ConsoleAppender::ConsoleAppender

Constructs a ConsoleAppender object

ConsoleAppender( );
ConsoleAppender(
   ple::simple_shared_ptr<Layout>& layout
);
ConsoleAppender(
   Layout* playout
);

Parameters

layout

A shared pointer to an object descended from Layout.

playout

A pointer to an object descended from Layout. The Layout object (if not null) will now be owned by the FileAppender, and will be deleted when the FileAppender is destroyed.

Requirements

Header: cpplog.h

See Also

ConsoleAppender Class | ConsoleAppender Methods


FileAppender Class

An implementation of Appender that appends to a file on disk.

class psl::log::FileAppender : public Appender

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

FileAppender Methods | cpplog.h | Logging (User Guide) | Appender class


FileAppender Methods

The methods of the FileAppender class are listed here.

Construction

public method FileAppender Constructs a FileAppender object, without opening the destination file

Properties

public method | getFile | Returns the destination file
public method | setFile | Sets the destination file

Methods of Appender

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

FileAppender Class | cpplog.h | Logging (User Guide) | Appender class


FileAppender::FileAppender

Constructs a FileAppender object, without opening the destination file

FileAppender( );
FileAppender(
   ple::simple_shared_ptr<Layout>& layout
);
FileAppender(
   Layout* playout
);
FileAppender(
   const std::basic_string<TCHAR>& file
);
FileAppender(
   ple::simple_shared_ptr<Layout>& layout,
   const std::basic_string<TCHAR>& file
);
FileAppender(
   Layout* playout,
   const std::basic_string<TCHAR>& file
);

Parameters

layout

A shared pointer to an object descended from Layout.

playout

A pointer to an object descended from Layout. The Layout object (if not null) will now be owned by the FileAppender, and will be deleted when the FileAppender is destroyed.

file

A complete file name, including path. The path may include environment variables, e.g. %TMP%\MyLogFile.log.

Requirements

Header: cpplog.h

See Also

FileAppender Class | FileAppender Methods


FileAppender::getFile

Returns the destination file

const std::basic_string<TCHAR>& getFile( ) const;

Return Value

Returns the full path of the file being written to.

Requirements

Header: cpplog.h

See Also

FileAppender Class | FileAppender Methods


FileAppender::setFile

Sets the destination file

void setFile(
   const std::basic_string<TCHAR>& file
);

Parameters

file

A complete file name, including path. The path may include environment variables, e.g. %TMP%\MyLogFile.log.

Requirements

Header: cpplog.h

See Also

FileAppender Class | FileAppender Methods


Logger Class

A routing mechanism through which log reports can be written to files and other destinations.

class psl::log::Logger

Overview

All log events are routed through loggers. A named logger can be retrieved by calling Logger::getLogger.

A logger has a severity level which can be accessed in code via Logger::getLevel and Logger::setLevel. However, it is more usually controlled by configuration at run-time.

A logger may have one or more appenders attached. Whenever a logger receives an event of sufficient severity, it will write it in appropriate format to each of the appenders which is attached. Appenders can be attached using Logger::addAppender, but are more usually controlled by run-time configuration.

LoggerPtr

Pointers to loggers are retrieved as the smart pointer type LoggerPtr. This is a simple shared pointer to a logger.

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

Logger Methods | cpplog.h | Logging (User Guide)


Logger Methods

The methods of the Logger class are listed here.

Creation

getLogger | Retrieves a pointer to the named logger
getRootLogger | Retrieves a pointer to the root logger

Properties

public method | getLevel | Returns the current severity level of the logger
public method | setLevel | Sets the severity level of the logger

Appenders

public method addAppender Adds an appender to the logger

Construction

public method Logger Constructs a Logger object

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

Logger Class | cpplog.h | Logging (User Guide)


Logger::addAppender

Adds an appender to the logger

void addAppender(
   ple::simple_shared_ptr<Appender> appender
);

Parameters

appender

A non-null pointer to a class descended from Appender If the level is set to LL_DEFAULT, then the severity level of the parent logger will be used. (Note that LL_DEFAULT may not be applied to the root logger.)

Remarks

Messages sent to this logger which are of lower severity than the level set with this method will be discarded.

Messages sent to this logger which are of the same or higher severity than the level set with this method will be streamed to any appenders, and will be passed on to the parent logger.

Requirements

Header: cpplog.h

See Also

Logger Class | Logger Methods | Appender class


Logger::getLevel

Returns the current severity level of the logger

LogLevel getLevel( ) const;

Return Value

Returns a severity level of type LogLevel. If the value has been set to LL_DEFAULT, then the severity level of the parent logger will be returned.

Remarks

Messages sent to this logger which are of lower severity than the level returned by this method will be discarded.

Messages sent to this logger which are of the same or higher severity than the level returned by this method will be streamed to any appenders, and will be passed on to the parent logger.

Requirements

Header: cpplog.h

See Also

Logger Class | Logger Methods | LogLevel enumeration


Logger::getLogger

Retrieves a pointer to the named logger

static LoggerPtr getLogger(
   const std::basic_string<TCHAR>& name = true
);

Parameters

name

The name of the logger, which may contain dots, to indicate a hierarchy, e.g. a.b, where logger a.b is the child of logger a, which is turn the child of the root logger.

If the empy string is used, then the root logger will be returned.

Remarks

If the named logger does not yet exist, it will be created. If any of it's ancestors do not exist, they will also be created at this time.

Requirements

Header: cpplog.h

See Also

Logger Class | Logger Methods


Logger::getRootLogger

Retrieves a pointer to the root logger

static LoggerPtr getRootLogger( );

Requirements

Header: cpplog.h

See Also

Logger Class | Logger Methods


Logger::Logger

Constructs a Logger object

Logger( );

Requirements

Header: cpplog.h

See Also

Logger Class | Logger Methods


Logger::setLevel

Sets the severity level of the logger

void setLevel(
   LogLevel level
);

Parameters

level

If the level is set to LL_DEFAULT, then the severity level of the parent logger will be used. (Note that LL_DEFAULT may not be applied to the root logger.)

Remarks

Messages sent to this logger which are of lower severity than the level set with this method will be discarded.

Messages sent to this logger which are of the same or higher severity than the level set with this method will be streamed to any appenders, and will be passed on to the parent logger.

Requirements

Header: cpplog.h

See Also

Logger Class | Logger Methods | LogLevel enumeration


LoggerPtr Class

A shared pointer to a unique logger instance.

class psl::log::LoggerPtr

Overview

Whenever logger pointers are returned by Logger::getLogger(), they are returned within this smart pointer type. It can be used as a pointer wherever Logger* might be used.

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

LoggerPtr Methods | cpplog.h | Logger class


LoggerPtr Methods

The methods of the LoggerPtr class are listed here.

Creation

operator -> Returns a pointer to the Logger object

Construction

public method LoggerPtr Constructs a LoggerPtr object

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

LoggerPtr Class | cpplog.h | Logger class


LoggerPtr::LoggerPtr

Constructs a LoggerPtr object

LoggerPtr( );

Requirements

Header: cpplog.h

See Also

LoggerPtr Class | LoggerPtr Methods


LoggerPtr::operator ->

Returns a pointer to the Logger object

static Logger* operator ->( );

Requirements

Header: cpplog.h

See Also

LoggerPtr Class | LoggerPtr Methods


ModulePropertyConfigurator Class

A logging configuration class which configures the logging framework by reading a text file, whose name and location is relative to the currently executing module.

class psl::log::ModulePropertyConfigurator

Configuration files

The configuration file is expected to be in the same directory as the executing module. Its name should be the same as the executing module, with the addition of the suffix .log.ini. For example, a module MyLib.dll will search for a log configuration file MyLib.dll.log.ini and a program program.exe will search for a log configuration file program.exe.log.ini.

For the format of the configuration file, see Configuration files.

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

ModulePropertyConfigurator Methods | cpplog.h | Logging (User Guide)


ModulePropertyConfigurator Methods

The methods of the ModulePropertyConfigurator class are listed here.

Configuration

configure Configures the logging framework

Construction

public method ModulePropertyConfigurator Constructs a ModulePropertyConfigurator object

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

ModulePropertyConfigurator Class | cpplog.h | Logging (User Guide)


ModulePropertyConfigurator::configure

Configures the logging framework

static bool configure(
   HINSTANCE hinstance,
   bool bIgnoreMissingFile,
   std::basic_string<TCHAR>& strErrorString,
   bool& bConfigFileWasMissing,
   std::basic_string<TCHAR>& strConfigFile,
   bool& bErrorFileWritten,
   const TCHAR* strErrorFileName,
   std::basic_string<TCHAR>& strErrorFilePath
);

Parameters

hinstance

The module of the binary file (EXE, DLL or XLL) whose location and name controls the location and name of the configuration file.

bIgnoreMissingFile

If true, then a missing configuration file is not considered an error, and in this event true will be returned. If false, then the configuration file must be present; if it is not found, the function will return false.

strErrorString

If an error occurs, a description of the problem will be placed in this variable, and false will be returned. If no error occurs, strErrorString will be cleared.

bConfigFileWasMissing

This parameter will be set to true if the required configuration file was not found. If the file was found, it will be set to false.

strConfigFile

This variable will contain the full path of the configuration file which the configurator searched for, and may have loaded or attempted to load.

bErrorFileWritten

This parameter will be set to true if an error occurred, and information about the failure was written to an error file. The full name and path of the error file will be found in strErrorFilePath. If no error occurred, or if no error file name was specified, then, it will be set to false.

strErrorFileName

The name (excluding path) of an error file where configurator errors will be reported. If this is not specified, then errors will be written only to strErrorString.

strErrorFilePath

If an error occured, and strErrorFileName is specified, then this variable will contain the full path of the error file to which errors were written. The error file will always be located in the current user's temporary directory.

Return Value

If the method returns false, an error occurred, and a description can be found in errorString.

Remarks

The configuration file is expected to be in the same directory as the executing module. Its name should be the same as the executing module, with the addition of the suffix .log.ini. For example, a module MyLib.dll will search for a log configuration file MyLib.dll.log.ini and a program program.exe will search for a log configuration file program.exe.log.ini.

For the format of the configuration file, see Configuration files.

Requirements

Header: cpplog.h

See Also

ModulePropertyConfigurator Class | ModulePropertyConfigurator Methods


ModulePropertyConfigurator::ModulePropertyConfigurator

Constructs a ModulePropertyConfigurator object

ModulePropertyConfigurator( );

Requirements

Header: cpplog.h

See Also

ModulePropertyConfigurator Class | ModulePropertyConfigurator Methods


PropertyConfigurator Class

A logging configuration class which loads configuration details from a file.

class psl::log::PropertyConfigurator

Configuration files

For the format of the configuration file, see Configuration files.

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

PropertyConfigurator Methods | cpplog.h | Logging (User Guide) | Configuration files


PropertyConfigurator Methods

The methods of the PropertyConfigurator class are listed here.

Configuration

configure Configures the logging framework

Construction

public method PropertyConfigurator Constructs a PropertyConfigurator object

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

PropertyConfigurator Class | cpplog.h | Logging (User Guide) | Configuration files


PropertyConfigurator::configure

Configures the logging framework

static void configure(
   const TCHAR* fileName,
   bool ignoreMissingFile = false
);
static bool configure(
   const TCHAR* fileName,
   bool ignoreMissingFile,
   std::basic_string<TCHAR>& errorString
);

Parameters

fileName

The full name of the configuration file, including its directory.

ignoreMissingFile

If true, then a missing configuration file is not considered an error, and in this event true will be returned. If false or omitted, then the configuration file must be present. If missing, the function will return false.

fileName

The full name of the configuration file, including its directory.

ignoreMissingFile

If true, then a missing configuration file is not considered an error, and in this event true will be returned. If false, then the configuration file must be present. If false, then the configuration file must be present; if it is not found, the function will return false, and errorString will be set to an error message.

errorString

If an error occurs, a description of the problem will be placed in this variable, and false will be returned. If no error occurs, errorString will be cleared.

Return Value

If the method returns false, an error occurred, and a description can be found in errorString.

Remarks

Configuration files

Requirements

Header: cpplog.h

See Also

PropertyConfigurator Class | PropertyConfigurator Methods


PropertyConfigurator::PropertyConfigurator

Constructs a PropertyConfigurator object

PropertyConfigurator( );

Requirements

Header: cpplog.h

See Also

PropertyConfigurator Class | PropertyConfigurator Methods


RollingFileAppender Class

An implementation of Appender that appends to a file on disk. A new file is opened at the start of each rolling time period, which may be an hour, a day or a week. This approach prevents the log file from building up to a huge size.

class psl::log::RollingFileAppender : public Appender

Rolling log file name

The name of the log file is constructed by the appender object by substituting the current date/time for the characters %t. The formats shown below are used for the substitutions.

Period | Format
Hour | YYYYMMDD_HH
Day | YYYYMMDD
Month | YYYYMM

Thus, for example, log files with the periods and names below might be expanded as shown at 2:00 pm on 12th April 2013.

Period | Unexpanded | Expanded
Hour | C:\log_%t.txt | C:\log_20130412_14.txt
Day | %TMP%\excel_addin_log%t.log | C:\Temp\excel_addin_log20130412.log
Day | %TMP%\logs\log_for_%t.log | C:\Users\MyName\AppData\Local\Temp\log_for_201304.log

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

RollingFileAppender Methods | cpplog.h | Logging (User Guide) | Appender class


RollingFileAppender Methods

The methods of the RollingFileAppender class are listed here.

Construction

public method RollingFileAppender Constructs a RollingFileAppender object, without opening the destination file

Properties

public method | getExpandedFile | Returns the complete destination file name, including the substituted date/time part
public method | getFile | Returns the destination file
public method | getPeriod | Gets the period of the appender
public method | setFile | Sets the destination file
public method | setPeriod | Sets the period of the appender

Methods of Appender

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

RollingFileAppender Class | cpplog.h | Logging (User Guide) | Appender class


RollingFileAppender::getExpandedFile

Returns the complete destination file name, including the substituted date/time part

const std::basic_string<TCHAR>& getExpandedFile( ) const;

Return Value

Returns the full path of the file being written to. The date/time part (%t) will be substituted by the date/time of the current log file.

Requirements

Header: cpplog.h

See Also

RollingFileAppender Class | RollingFileAppender Methods


RollingFileAppender::getFile

Returns the destination file

const std::basic_string<TCHAR>& getFile( ) const;

Return Value

Returns the full path of the file being written to. The date/time part (%t) will not be substituted.

Requirements

Header: cpplog.h

See Also

RollingFileAppender Class | RollingFileAppender Methods


RollingFileAppender::getPeriod

Gets the period of the appender

PeriodTypes getPeriod( ) const;

Return Value

Returns the period of the appender. This will be one of: RollingFileAppender::PERIOD_HOUR, RollingFileAppender::PERIOD_DAY, RollingFileAppender::PERIOD_MONTH.

Requirements

Header: cpplog.h

See Also

RollingFileAppender Class | RollingFileAppender Methods


RollingFileAppender::RollingFileAppender

Constructs a RollingFileAppender object, without opening the destination file

RollingFileAppender( );
RollingFileAppender(
   ple::simple_shared_ptr<Layout>& layout
);
RollingFileAppender(
   Layout* playout
);
RollingFileAppender(
   const std::basic_string<TCHAR>& file,
   PeriodTypes period = PERIOD_DAY
);
RollingFileAppender(
   ple::simple_shared_ptr<Layout>& layout,
   const std::basic_string<TCHAR>& file,
   PeriodTypes period = PERIOD_DAY
);
RollingFileAppender(
   Layout* playout,
   const std::basic_string<TCHAR>& file,
   PeriodTypes period = PERIOD_DAY
);

Parameters

layout

A shared pointer to an object descended from Layout.

playout

A pointer to an object descended from Layout. The Layout object (if not null) will now be owned by the RollingFileAppender, and will be deleted when the RollingFileAppender is destroyed.

file

A complete file name, including path. The file name should include the character pair %t. This pair will be replaced by a representation of the time and/or date in the complete log file name. The path may include environment variables, e.g. %TMP%\MyLogFile.log.

period

The desired period for the log file, which must be one of: RollingFileAppender::PERIOD_HOUR, RollingFileAppender::PERIOD_DAY, RollingFileAppender::PERIOD_MONTH.

Requirements

Header: cpplog.h

See Also

RollingFileAppender Class | RollingFileAppender Methods


RollingFileAppender::setFile

Sets the destination file

void setFile(
   const std::basic_string<TCHAR>& file
);

Parameters

file

A complete file name, including path. The file name should include the character pair %t. This pair will be replaced by a representation of the time and/or date in the complete log file name. The path may include environment variables, e.g. %TMP%\MyLogFile.log.

Requirements

Header: cpplog.h

See Also

RollingFileAppender Class | RollingFileAppender Methods


RollingFileAppender::setPeriod

Sets the period of the appender

void setPeriod(
   PeriodTypes period
);

Parameters

period

The desired period for the log file, which must be one of: RollingFileAppender::PERIOD_HOUR, RollingFileAppender::PERIOD_DAY, RollingFileAppender::PERIOD_MONTH.

Requirements

Header: cpplog.h

See Also

RollingFileAppender Class | RollingFileAppender Methods


TraceAppender Class

An implementation of Appender that appends to the MFC or XLL+ TRACE sink.

class psl::log::TraceAppender : public Appender

Requirements

To use this appender class in your code, ensure that the macro TRACE is defined.

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

TraceAppender Methods | cpplog.h | Logging (User Guide) | Appender class


TraceAppender Methods

The methods of the TraceAppender class are listed here.

Construction

public method TraceAppender Constructs a TraceAppender object

Methods of Appender

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

TraceAppender Class | cpplog.h | Logging (User Guide) | Appender class


TraceAppender::TraceAppender

Constructs a TraceAppender object

TraceAppender( );
TraceAppender(
   ple::simple_shared_ptr<Layout>& layout
);
TraceAppender(
   Layout* playout
);

Parameters

layout

A shared pointer to an object descended from Layout.

playout

A pointer to an object descended from Layout. The Layout object (if not null) will now be owned by the FileAppender, and will be deleted when the FileAppender is destroyed.

Requirements

Header: cpplog.h

See Also

TraceAppender Class | TraceAppender Methods


XllConfigurator Class

A logging configuration class which configures the logging framework by reading a text file, whose name and location is relative to the currently executing XLL add-in.

class psl::log::XllConfigurator

Configuration files

The configuration file is expected to be in the same directory as the XLL file. Its name should be the same as the XLL, with the addition of the suffix .log.ini. For example, an add-in MyAddin.xll will search for a log configuration file MyAddin.xll.log.ini.

For the format of the configuration file, see Configuration files.

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

XllConfigurator Methods | cpplog.h | Logging (User Guide)


XllConfigurator Methods

The methods of the XllConfigurator class are listed here.

Configuration

configure Configures the logging framework

Construction

public method XllConfigurator Constructs a XllConfigurator object

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

XllConfigurator Class | cpplog.h | Logging (User Guide)


XllConfigurator::configure

Configures the logging framework

static bool configure(
   bool bIgnoreMissingFile = true
);

Parameters

bIgnoreMissingFile

If true, then a missing configuration file is not considered an error, and in this event true will be returned. If false, then the configuration file must be present; if it is not found, the function will return false.

Return Value

If the method returns false, an error occurred, and a message box will be displayed to the user.

Remarks

The configuration file is expected to be in the same directory as the XLL file. Its name should be the same as the XLL, with the addition of the suffix .log.ini. For example, an add-in MyAddin.xll will search for a log configuration file MyAddin.xll.log.ini.

For the format of the configuration file, see Configuration files.

Requirements

Header: cpplog.h

See Also

XllConfigurator Class | XllConfigurator Methods


XllConfigurator::XllConfigurator

Constructs a XllConfigurator object

XllConfigurator( );

Requirements

Header: cpplog.h

See Also

XllConfigurator Class | XllConfigurator Methods


Logging macros

Logging macros are listed here.

Logging macros

public method | LOG_DEBUG | Write debugging information to the log
public method | LOG_ERROR | Write an error report to the log
public method | LOG_FATAL | Write a fatal error report to the log
public method | LOG_INFO | Write information about a user action or other event to the log
public method | LOG_TRACE | Write low-level information to the log
public method | LOG_WARN | Write a warning to the log

Requirements

Header: cpplog.h

See Also

cpplog.h


::LOG_DEBUG

Write debugging information to the log

LOG_DEBUG(
   LoggerPtr logger,
   EXPRESSION expression
);

Parameters

logger

A pointer to a logger, which will have been retrieved using Logger::getLogger().

expression

An expression that it is to be written to the log. Any expression can be used that works as the right-hand-side of os << expression where os is of type std::ostream (or std::wostream under Unicode builds).

It can be a simple string, a number, or any object that supports the output stream operator. The expression may include any number of items, each separated by a << operator.

Remarks

For examples of use, see Using the logging macros.

Requirements

Header: cpplog.h

See Also

Logging macros | Logging


::LOG_ERROR

Write an error report to the log

LOG_ERROR(
   LoggerPtr logger,
   EXPRESSION expression
);

Parameters

logger

A pointer to a logger, which will have been retrieved using Logger::getLogger().

expression

An expression that it is to be written to the log. Any expression can be used that works as the right-hand-side of os << expression where os is of type std::ostream (or std::wostream under Unicode builds).

It can be a simple string, a number, or any object that supports the output stream operator. The expression may include any number of items, each separated by a << operator.

Remarks

For examples of use, see Using the logging macros.

Requirements

Header: cpplog.h

See Also

Logging macros | Logging


::LOG_FATAL

Write a fatal error report to the log

LOG_FATAL(
   LoggerPtr logger,
   EXPRESSION expression
);

Parameters

logger

A pointer to a logger, which will have been retrieved using Logger::getLogger().

expression

An expression that it is to be written to the log. Any expression can be used that works as the right-hand-side of os << expression where os is of type std::ostream (or std::wostream under Unicode builds).

It can be a simple string, a number, or any object that supports the output stream operator. The expression may include any number of items, each separated by a << operator.

Remarks

For examples of use, see Using the logging macros.

Requirements

Header: cpplog.h

See Also

Logging macros | Logging


::LOG_INFO

Write information about a user action or other event to the log

LOG_INFO(
   LoggerPtr logger,
   EXPRESSION expression
);

Parameters

logger

A pointer to a logger, which will have been retrieved using Logger::getLogger().

expression

An expression that it is to be written to the log. Any expression can be used that works as the right-hand-side of os << expression where os is of type std::ostream (or std::wostream under Unicode builds).

It can be a simple string, a number, or any object that supports the output stream operator. The expression may include any number of items, each separated by a << operator.

Remarks

For examples of use, see Using the logging macros.

Requirements

Header: cpplog.h

See Also

Logging macros | Logging


::LOG_TRACE

Write low-level information to the log

LOG_TRACE(
   LoggerPtr logger,
   EXPRESSION expression
);

Parameters

logger

A pointer to a logger, which will have been retrieved using Logger::getLogger().

expression

An expression that it is to be written to the log. Any expression can be used that works as the right-hand-side of os << expression where os is of type std::ostream (or std::wostream under Unicode builds).

It can be a simple string, a number, or any object that supports the output stream operator. The expression may include any number of items, each separated by a << operator.

Remarks

For examples of use, see Using the logging macros.

Requirements

Header: cpplog.h

See Also

Logging macros | Logging


::LOG_WARN

Write a warning to the log

LOG_WARN(
   LoggerPtr logger,
   EXPRESSION expression
);

Parameters

logger

A pointer to a logger, which will have been retrieved using Logger::getLogger().

expression

An expression that it is to be written to the log. Any expression can be used that works as the right-hand-side of os << expression where os is of type std::ostream (or std::wostream under Unicode builds).

It can be a simple string, a number, or any object that supports the output stream operator. The expression may include any number of items, each separated by a << operator.

Remarks

For examples of use, see Using the logging macros.

Requirements

Header: cpplog.h

See Also

Logging macros | Logging


Enumerations

The enumerations declared in cpplog.h are listed below.

LogLevel

Requirements

Header: cpplog.h

See Also

cpplog.h


LogLevel Enumeration

The set of severity levels that can be applied to log events and loggers.

enum LogLevel

Members

LL_DEFAULT | -1 | If a logger is set to this level, then the severity level of its parent log will be used.
LL_TRACE | 0 | The lowest severity level. Use this for detailed context dumps, and within loops.
LL_DEBUG | 1 | The second lowest severity level. Use this for events which will be useful when debugging.
LL_INFO | 2 | Use this to record user input or commands, or for significant events.
LL_WARN | 3 | The lowest error level. Warnings are worth recording for later analysis, but do not require immediate action.
LL_ERROR | 4 | An error condition occurred, but the application can continue.
LL_FATAL | 5 | A fatal error occurred, and the application or module must cease operation.

Requirements

Header: cpplog.h
Namespace: psl::log

See Also

cpplog.h | Logging (User Guide)


xlfuncs.h

Overview

xlfuncs.h contains classes that allows you to call Excel worksheet functions from C++ code.

For details on how to use the classes see CXlFuncs overview and CXlMacros overview

Classes

Class | Description
CXlFuncs | A class containing static methods for calling Excel worksheet functions.
CXlMacros | A class containing static methods for calling Excel macro functions.

See Also

CXlFuncs object | CXlMacros object | xllplus.h


CXlFuncs Class

Supports calls to Excel worksheet functions.

class CXlFuncs

Overview

The CXlFuncs class contains only static methods. Each of these methods calls the corresponding Excel worksheet function.

Any of these functions may normally be called from worksheet functions.

Return values

All methods return a result code, which is zero if the function has succeeded, and non-zero if the function has failed for any reason. See Error codes for a list of return values.

Note that the results of some functions may still contain Excel error values, even if a zero result code is returned, and you should take care to test the type of these results where appropriate.

Macro functions

CXlFuncs only contains worksheet functions. If you want to call an Excel macro function, use the CXlMacros class.

Other worksheet functions

The CXlFuncs class does not implement all Excel worksheet functions. If the function you want is not implemented, you can call it yourself via the CXlOper::Excel() method using the techniques described in Calling an Excel built-in function from your add-in.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Methods | xlfuncs.h | CXlMacros object | CXllApp::Excel | CXlOper::Excel


CXlFuncs Methods

The methods of the CXlFuncs class are listed here.

Date & Time Functions

Date | Returns the serial number of a particular date
DateValue | Returns the serial number of the date represented by date_text
Day | Returns the day of the month for a date
Days360 | Returns the number of days between two dates based on a 360-day year
Hour | Returns the hour for a particular date value
Minute | Returns the minute for a particular date value
Month | Returns the number of the month for a date
Now | Returns the serial number of the current date and time
Second | Returns the second for a particular date value
Time | Returns the serial number of a particular time
TimeValue | Returns the serial number of the time represented by date_text
Today | Returns the serial number of the current date
Weekday | Returns the day of the week corresponding to a date
Year | Returns the year for a date

Math & Trig Functions

MDeterm | Returns the matrix determinant of an array
MInverse | Returns the inverse matrix for the matrix stored in an array
Roman | Converts an arabic numeral to roman, as text

Information Functions

Cell | Returns information about the formatting, location, or contents of a cell
CellAddress | Returns address of a referenced cell, as text
CellCol | Returns column number of a referenced cell
CellColor | Returns whether a referenced cell is colored when negative
CellContents | Returns contents of a referenced cell
CellFileName | Returns name of file containing a referenced cell
CellFormat | Returns format string of a referenced cell
CellParentheses | Returns whether a referenced cell is shown in parentheses when negative
CellPrefix | Returns the label prefix of a referenced cell
CellProtect | Returns whether a referenced cell is shown is protected
CellRow | Returns row number of a referenced cell
CellType | Returns the data type of a referenced cell
CellWidth | Returns the width of a referenced cell in characters
Info | Returns information about the current operating environment
InfoDirectory | Returns the current working directory
InfoMemAvail | Returns the amount of memory available, in bytes
InfoMemUsed | Returns the amount of memory used for data, in bytes
InfoNumFile | Returns the number of active worksheets
InfoOrigin | Returns a reference to the top-left visible cell
InfoOSVersion | Returns current operating system version, as text
InfoRecalc | Returns current recalculation mode
InfoRecalcAutomatic | Returns whether current calculation mode is automatic
InfoRecalcManual | Returns whether current calculation mode is manual
InfoRelease | Returns version number of Microsoft Excel
InfoSystem | Returns name of the operating environment
InfoSystemMac | Returns whether current operating environment is Macintosh
InfoSystemWindows | Returns whether current operating environment is Windows
InfoTotMem | Returns total memory available, including memory already in use, in bytes
N | Returns a value converted to a number
Type | Returns the type of value

Lookup & Reference Functions

Address | Creates a cell address as text, given specified row and column numbers
HLookup | Looks in the top row of an array and returns the value of the indicated cell
Index | Uses an index to choose a value from a reference or array
Indirect | Returns a reference indicated by a text value
Lookup | Looks up values in a vector or array
Match | Returns the relative position of an item in an array that matches a specified value in a specified order
Offset | Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells
Transpose | Returns a vertical range of cells as a horizontal range, or vice versa
VLookup | Looks in the first column of an array and returns the value of the indicated cell

Text Functions

Char | Returns the character specified by a number
Clean | Removes all nonprintable characters from text
Code | Returns a numeric code for the first character in a text string
Text | Converts a value to text in a specific number format
Value | Converts a text string that represents a number to a number

Construction

public method CXlFuncs Constructs a CXlFuncs object

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | xlfuncs.h | CXlMacros object | CXllApp::Excel | CXlOper::Excel


CXlFuncs::Address

Creates a cell address as text, given specified row and column numbers

static int Address(
   CString& straddress,
   unsigned long row_num,
   unsigned long column_num,
   short int abs_num = 1,
   bool a1 = true,
   LPCTSTR sheet_text = ""
);

Parameters

straddress

A reference to a string that will contain the requested data if the macro succeeds.
row_num

Row number.
column_num

Column number.
abs_num

Type of reference to return.
a1

Style of reference to return.
sheet_text

Text specifying the name of the worksheet to be used as the external reference.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Cell

Returns information about the formatting, location, or contents of a cell

static int Cell(
   CXlOper& xloData,
   LPCTSTR info_type,
   const CXlOper& reference
);

Parameters

xloData

A reference to a CXlOper object that will contain the requested data if the macro succeeds.
info_type

Text value that specifies what type of cell information you want.
reference

Reference to the cell that you want information about.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::CellAddress

Returns address of a referenced cell, as text

static int CellAddress(
   CString& straddress,
   const CXlOper& reference
);

Parameters

straddress

A reference to a string that will contain the requested data if the macro succeeds.
reference

Reference to the cell that you want information about.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::CellCol

Returns column number of a referenced cell

static int CellCol(
   long& lcol,
   const CXlOper& reference
);
static int CellCol(
   unsigned short& uscol,
   const CXlOper& reference
);
static int CellCol(
   BYTE& bytecol,
   const CXlOper& reference
);

Parameters

lcol

A reference to an integer that will contain the requested data if the macro succeeds.
reference

Reference to the cell that you want information about.
uscol

A reference to an integer that will contain the requested data if the macro succeeds.
bytecol

A reference to an integer that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::CellColor

Returns whether a referenced cell is colored when negative

static int CellColor(
   bool& bcolor,
   const CXlOper& reference
);
static int CellColor(
   BOOL& shcolor,
   const CXlOper& reference
);

Parameters

bcolor

A reference to a boolean value that will contain the requested data if the macro succeeds.
reference

Reference to the cell that you want information about.
shcolor

A reference to a boolean value that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::CellContents

Returns contents of a referenced cell

static int CellContents(
   CXlOper& xloContents,
   const CXlOper& reference
);

Parameters

xloContents

A reference to a CXlOper that will contain the requested data if the macro succeeds.
reference

Reference to the cell that you want information about.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::CellFileName

Returns name of file containing a referenced cell

static int CellFileName(
   CString& strfilename,
   const CXlOper& reference
);

Parameters

strfilename

A reference to a string that will contain the requested data if the macro succeeds.
reference

Reference to the cell that you want information about.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::CellFormat

Returns format string of a referenced cell

static int CellFormat(
   CString& strformat,
   const CXlOper& reference
);

Parameters

strformat

A reference to a string that will contain the requested data if the macro succeeds.
reference

Reference to the cell that you want information about.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::CellParentheses

Returns whether a referenced cell is shown in parentheses when negative

static int CellParentheses(
   bool& bparentheses,
   const CXlOper& reference
);
static int CellParentheses(
   BOOL& shparentheses,
   const CXlOper& reference
);

Parameters

bparentheses

A reference to a boolean value that will contain the requested data if the macro succeeds.
reference

Reference to the cell that you want information about.
shparentheses

A reference to a boolean value that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::CellPrefix

Returns the label prefix of a referenced cell

static int CellPrefix(
   CString& strprefix,
   const CXlOper& reference
);

Parameters

strprefix

A reference to a string that will contain the requested data if the macro succeeds.
reference

Reference to the cell that you want information about.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::CellProtect

Returns whether a referenced cell is shown is protected

static int CellProtect(
   bool& bprotect,
   const CXlOper& reference
);
static int CellProtect(
   BOOL& shprotect,
   const CXlOper& reference
);

Parameters

bprotect

A reference to a boolean value that will contain the requested data if the macro succeeds.
reference

Reference to the cell that you want information about.
shprotect

A reference to a boolean value that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::CellRow

Returns row number of a referenced cell

static int CellRow(
   long& lrow,
   const CXlOper& reference
);
static int CellRow(
   unsigned short& usrow,
   const CXlOper& reference
);

Parameters

lrow

A reference to an integer that will contain the requested data if the macro succeeds.
reference

Reference to the cell that you want information about.
usrow

A reference to an integer that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::CellType

Returns the data type of a referenced cell

static int CellType(
   CString& strtype,
   const CXlOper& reference
);

Parameters

strtype

A reference to a string that will contain the requested data if the macro succeeds.
reference

Reference to the cell that you want information about.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::CellWidth

Returns the width of a referenced cell in characters

static int CellWidth(
   long& lwidth,
   const CXlOper& reference
);
static int CellWidth(
   short int& shwidth,
   const CXlOper& reference
);

Parameters

lwidth

A reference to an integer that will contain the requested data if the macro succeeds.
reference

Reference to the cell that you want information about.
shwidth

A reference to an integer that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Char

Returns the character specified by a number

static int Char(
   CString& strtext,
   unsigned int number
);

Parameters

strtext

A reference to a string that will contain the requested data if the macro succeeds.
number

Character value.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Clean

Removes all nonprintable characters from text

static int Clean(
   CString& strclean,
   LPCTSTR text
);

Parameters

strclean

A reference to a string that will contain the requested data if the macro succeeds.
text

Input string.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Code

Returns a numeric code for the first character in a text string

static int Code(
   long& lcode,
   LPCTSTR text
);

Parameters

lcode

A reference to a value that will contain the requested data if the macro succeeds.
text

Input string.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::CXlFuncs

Constructs a CXlFuncs object

CXlFuncs( );

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Date

Returns the serial number of a particular date

static int Date(
   double& ddt,
   long year,
   long month,
   long day
);
static int Date(
   long& ldt,
   long year,
   long month,
   long day
);

Parameters

ddt

A reference to a value that will contain a serial date if the function succeeds.
year

A number between 1900 and 9999.
month

A positive month number, generally between 1 and 12.
day

A positive day number, generally between 1 and 31.
ldt

A reference to a value that will contain a serial date if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::DateValue

Returns the serial number of the date represented by date_text

static int DateValue(
   double& ddt,
   LPCTSTR date_text
);
static int DateValue(
   long& ldt,
   LPCTSTR date_text
);

Parameters

ddt

A reference to a value that will contain a serial date if the function succeeds.
date_text

A string containing a date.
ldt

A reference to a value that will contain a serial date if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Day

Returns the day of the month for a date

static int Day(
   double& dday,
   long serial_number
);
static int Day(
   long& lday,
   long serial_number
);
static int Day(
   short int& shday,
   long serial_number
);

Parameters

dday

A reference to a value that will contain a day number (between 1 and 31) if the function succeeds.
serial_number

An Excel serial date value.
lday

A reference to a value that will contain a day number (between 1 and 31) if the function succeeds.
shday

A reference to a value that will contain a day number (between 1 and 31) if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Days360

Returns the number of days between two dates based on a 360-day year

static int Days360(
   double& ddays,
   long start_date,
   long end_date,
   bool european_method = false
);
static int Days360(
   long& ldays,
   long serial_number,
   long start_date,
   long end_date,
   bool european_method = false
);

Parameters

ddays

A reference to a value that will contain a day count if the function succeeds.
start_date

An Excel serial date value.
end_date

An Excel serial date value.
european_method

True for european day count method; false for the US method.
ldays

A reference to a value that will contain a day count if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::HLookup

Looks in the top row of an array and returns the value of the indicated cell

static int HLookup(
   CXlOper& xloValue,
   const CXlOper& lookup_value,
   const CXlOper& table_array,
   unsigned long row_index_num,
   bool range_lookup = true
);

Parameters

xloValue

A reference to a CXlOper that will contain the requested data if the macro succeeds.
lookup_value

Value to be found in the first row of the table.
table_array

Table of information in which data is looked up.
row_index_num

Row number in table_array from which the matching value will be returned.
range_lookup

Whether to allow an inexact match.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Hour

Returns the hour for a particular date value

static int Hour(
   double& dhour,
   double serial_number
);
static int Hour(
   long& lhour,
   double serial_number
);
static int Hour(
   short int& shhour,
   double serial_number
);

Parameters

dhour

A reference to a value that will contain an hour value (between 0 and 23) if the function succeeds.
serial_number

An Excel date/time value. The date (integer) part will be ignored.
lhour

A reference to a value that will contain an hour value (between 0 and 23) if the function succeeds.
shhour

A reference to a value that will contain an hour value (between 0 and 23) if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Index

Uses an index to choose a value from a reference or array

static int Index(
   CXlOper& xloValue,
   const CXlOper& array,
   unsigned long row_num,
   unsigned long column_num
);
static int Index(
   CXlOper& xloValue,
   const CXlOper& reference,
   unsigned long row_num,
   unsigned long column_num,
   unsigned short area_num
);

Parameters

xloValue

A reference to a CXlOper that will contain the requested data if the macro succeeds.
array

Range of cells or an array constant.
row_num

Row in array from which to return a value. If row_num is 0, column_num must be non-zero. A zero value is treated as a missing argument.
column_num

Column in array from which to return a value. If column_num is 0, row_num must be non-zero. A zero value is treated as a missing argument.
reference

Reference to one or more cell ranges.
area_num

Range in reference from which to return the intersection of row_num and column_num.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Indirect

Returns a reference indicated by a text value

static int Indirect(
   CXlOper& xloRef,
   LPCTSTR ref_text,
   bool a1 = true
);

Parameters

xloRef

A reference to a CXlOper that will contain the requested data if the macro succeeds.
ref_text

A string reference to a cell.
a1

Style of reference in ref_text.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Info

Returns information about the current operating environment

static int Info(
   CXlOper& xloData,
   LPCTSTR type_text
);

Parameters

xloData

A reference to a CXlOper object that will contain the requested data if the macro succeeds.
type_text

Text value that specifies what type of information you want.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoDirectory

Returns the current working directory

static int InfoDirectory(
   CString& strdirectory
);

Parameters

strdirectory

A reference to a string that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoMemAvail

Returns the amount of memory available, in bytes

static int InfoMemAvail(
   double& dmemavail
);

Parameters

dmemavail

A reference to a value that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoMemUsed

Returns the amount of memory used for data, in bytes

static int InfoMemUsed(
   double& dmemused
);

Parameters

dmemused

A reference to a value that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoNumFile

Returns the number of active worksheets

static int InfoNumFile(
   long& lnumfile
);

Parameters

lnumfile

A reference to a value that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoOrigin

Returns a reference to the top-left visible cell

static int InfoOrigin(
   CString& strorigin
);

Parameters

strorigin

A reference to a string that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoOSVersion

Returns current operating system version, as text

static int InfoOSVersion(
   CString& strosversion
);

Parameters

strosversion

A reference to a string that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoRecalc

Returns current recalculation mode

static int InfoRecalc(
   CString& strrecalc
);

Parameters

strrecalc

A reference to a string that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoRecalcAutomatic

Returns whether current calculation mode is automatic

static int InfoRecalcAutomatic(
   bool& bautomatic
);
static int InfoRecalcAutomatic(
   BOOL& shautomatic
);

Parameters

bautomatic

A reference to a value that will contain the requested data if the macro succeeds.
shautomatic

A reference to a value that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoRecalcManual

Returns whether current calculation mode is manual

static int InfoRecalcManual(
   bool& bmanual
);
static int InfoRecalcManual(
   BOOL& shmanual
);

Parameters

bmanual

A reference to a value that will contain the requested data if the macro succeeds.
shmanual

A reference to a value that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoRelease

Returns version number of Microsoft Excel

static int InfoRelease(
   CString& strrelease
);
static int InfoRelease(
   double& drelease
);

Parameters

strrelease

A reference to a string that will contain the requested data if the macro succeeds.
drelease

A reference to a value that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoSystem

Returns name of the operating environment

static int InfoSystem(
   CString& strsystem
);

Parameters

strsystem

A reference to a string that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoSystemMac

Returns whether current operating environment is Macintosh

static int InfoSystemMac(
   bool& bmac
);
static int InfoSystemMac(
   BOOL& shmac
);

Parameters

bmac

A reference to a value that will contain the requested data if the macro succeeds.
shmac

A reference to a value that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoSystemWindows

Returns whether current operating environment is Windows

static int InfoSystemWindows(
   bool& bwindows
);
static int InfoSystemWindows(
   BOOL& shwindows
);

Parameters

bwindows

A reference to a value that will contain the requested data if the macro succeeds.
shwindows

A reference to a value that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::InfoTotMem

Returns total memory available, including memory already in use, in bytes

static int InfoTotMem(
   double& dtotmem
);

Parameters

dtotmem

A reference to a value that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Lookup

Looks up values in a vector or array

static int Lookup(
   CXlOper& xloValue,
   const CXlOper& lookup_value,
   const CXlOper& array
);
static int Lookup(
   CXlOper& xloValue,
   const CXlOper& lookup_value,
   const CXlOper& lookup_vector,
   const CXlOper& result_vector
);

Parameters

xloValue

A reference to a CXlOper that will contain the requested data if the macro succeeds.
lookup_value

Value to be found in the first column of the table.
array

Range or array to be searched for lookup_value.
lookup_vector

1-dimensional range or array to be searched for lookup_value.
result_vector

1-dimensional range or array containing results.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Match

Returns the relative position of an item in an array that matches a specified value in a specified order

static int Match(
   unsigned short& uspos,
   const CXlOper& lookup_value,
   const CXlOper& lookup_array,
   short match_type = 1
);
static int Match(
   unsigned long& ulpos,
   const CXlOper& lookup_value,
   const CXlOper& lookup_array,
   unsigned short match_type = 1
);

Parameters

uspos

A reference to a value that will contain the requested data if the macro succeeds. It will contain zero if no value matches the lookup_value.
lookup_value

Value to be found in the first column of the table.
lookup_array

Table of information in which data is looked up.
match_type

Match type.
ulpos

A reference to a value that will contain the requested data if the macro succeeds. It will contain zero if no value matches the lookup_value.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::MDeterm

Returns the matrix determinant of an array

static int MDeterm(
   CXlOper& xloDeterm,
   const CXlOper& array
);

Parameters

xloDeterm

A reference to a CXlOper object that will contain the requested data if the macro succeeds.
array

Array is a numeric array with an equal number of rows and columns

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Minute

Returns the minute for a particular date value

static int Minute(
   double& dminute,
   double serial_number
);
static int Minute(
   long& lminute,
   double serial_number
);
static int Minute(
   short int& shminute,
   double serial_number
);

Parameters

dminute

A reference to a value that will contain an minute value (between 0 and 59) if the function succeeds.
serial_number

An Excel date/time value. The date (integer) part will be ignored.
lminute

A reference to a value that will contain an minute value (between 0 and 59) if the function succeeds.
shminute

A reference to a value that will contain an minute value (between 0 and 59) if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::MInverse

Returns the inverse matrix for the matrix stored in an array

static int MInverse(
   CXlOper& xloInverse,
   const CXlOper& array
);

Parameters

xloInverse

A reference to a CXlOper object that will contain the requested data if the macro succeeds.
array

Array is a numeric array with an equal number of rows and columns

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Month

Returns the number of the month for a date

static int Month(
   double& dmonth,
   long serial_number
);
static int Month(
   long& lmonth,
   long serial_number
);
static int Month(
   short int& shmonth,
   long serial_number
);

Parameters

dmonth

A reference to a value that will contain a month number (between 1 and 12) if the function succeeds.
serial_number

An Excel serial date value.
lmonth

A reference to a value that will contain a month number (between 1 and 12) if the function succeeds.
shmonth

A reference to a value that will contain a month number (between 1 and 12) if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::N

Returns a value converted to a number

static int N(
   double& dn,
   const CXlOper& xloCell
);

Parameters

dn

A reference to a value that will contain the requested data if the macro succeeds.
xloCell

Value or reference to a value.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Now

Returns the serial number of the current date and time

static int Now(
   double& dtime
);

Parameters

dtime

A reference to a value that will contain a serial date and time if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Offset

Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells

static int Offset(
   CXlOper& xloOffsetRef,
   const CXlOper& reference,
   long rows,
   long cols,
   unsigned long height = 0,
   unsigned long width = 0
);

Parameters

xloOffsetRef

A reference to a CXlOper that will contain the requested data if the macro succeeds.
reference

The reference from which you want to base the offset.
rows

Row offset.
cols

Column offset.
height

Desired height of resulting reference. Treated as missing if 0.
width

Desired width of resulting reference. Treated as missing if 0.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Roman

Converts an arabic numeral to roman, as text

static int Roman(
   CString& roman,
   long number,
   unsigned short form = 0
);

Parameters

roman

A reference to a string that will contain the requested data if the macro succeeds.
number

Number is the Arabic numeral you want converted.
form

Form is a number specifying the type of roman numeral you want.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Second

Returns the second for a particular date value

static int Second(
   double& dsecond,
   double serial_number
);
static int Second(
   long& lsecond,
   double serial_number
);
static int Second(
   short int& shsecond,
   double serial_number
);

Parameters

dsecond

A reference to a value that will contain an second value (between 0 and 59) if the function succeeds.
serial_number

An Excel date/time value. The date (integer) part will be ignored.
lsecond

A reference to a value that will contain an second value (between 0 and 59) if the function succeeds.
shsecond

A reference to a value that will contain an second value (between 0 and 59) if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Text

Converts a value to text in a specific number format

static int Text(
   CString& strtext,
   double dvalue,
   LPCTSTR format_text
);
static int Text(
   CString& strtext,
   const CXlOper& value,
   LPCTSTR format_text
);

Parameters

strtext

A reference to a string that will contain the requested data if the macro succeeds.
dvalue

Input value.
format_text

Column number.
value

Input value.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Time

Returns the serial number of a particular time

static int Time(
   double& ddt,
   long hour,
   long minute,
   long second
);

Parameters

ddt

A reference to a value that will contain a serial time if the function succeeds.
hour

A number between 0 and 23.
minute

A number between 0 and 59.
second

A number between 0 and 59.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::TimeValue

Returns the serial number of the time represented by date_text

static int TimeValue(
   double& dtime,
   LPCTSTR time_text
);

Parameters

dtime

A reference to a value that will contain a serial time if the function succeeds.
time_text

A string containing a time. Any date portion will be ignored.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Today

Returns the serial number of the current date

static int Today(
   double& ddt
);
static int Today(
   long& ldt
);

Parameters

ddt

A reference to a value that will contain a serial date if the function succeeds.
ldt

A reference to a value that will contain a serial date if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Transpose

Returns a vertical range of cells as a horizontal range, or vice versa

static int Transpose(
   CXlOper& xloValue,
   const CXlOper& array
);

Parameters

xloValue

A reference to a CXlOper that will contain the requested data if the macro succeeds.
array

An array or range of cells on a worksheet that you want to transpose.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Type

Returns the type of value

static int Type(
   long& ltype,
   const CXlOper& xloCell
);
static int Type(
   short int& ltype,
   const CXlOper& xloCell
);

Parameters

ltype

A reference to a value that will contain the requested data if the macro succeeds.
xloCell

Value or reference to a value.
ltype

A reference to a value that will contain the requested data if the macro succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Value

Converts a text string that represents a number to a number

static int Value(
   double& dvalue,
   LPCTSTR text
);

Parameters

dvalue

A reference to a value that will contain the requested data if the macro succeeds.
text

Input string.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::VLookup

Looks in the first column of an array and returns the value of the indicated cell

static int VLookup(
   CXlOper& xloValue,
   const CXlOper& lookup_value,
   const CXlOper& table_array,
   unsigned long col_index_num,
   bool range_lookup = true
);

Parameters

xloValue

A reference to a CXlOper that will contain the requested data if the macro succeeds.
lookup_value

Value to be found in the first column of the table.
table_array

Table of information in which data is looked up.
col_index_num

Column number in table_array from which the matching value will be returned.
range_lookup

Whether to allow an inexact match.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Weekday

Returns the day of the week corresponding to a date

static int Weekday(
   double& dday,
   long serial_number,
   short int return_type = 1
);
static int Weekday(
   long& lday,
   long serial_number,
   short int return_type = 1
);
static int Weekday(
   short int& shday,
   long serial_number,
   short int return_type = 1
);

Parameters

dday

A reference to a value that will contain a day number (between 0 and 7) if the function succeeds.
serial_number

An Excel serial date value.
return_type

A number that determines the type of return value.
lday

A reference to a value that will contain a day number (between 0 and 7) if the function succeeds.
shday

A reference to a value that will contain a day number (between 0 and 7) if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlFuncs::Year

Returns the year for a date

static int Year(
   double& dyear,
   long serial_number
);
static int Year(
   long& lyear,
   long serial_number
);
static int Year(
   short int& shyear,
   long serial_number
);

Parameters

dyear

A reference to a value that will contain a year number (between 1900 and 9999) if the function succeeds.
serial_number

An Excel serial date value.
lyear

A reference to a value that will contain a year number (between 1900 and 9999) if the function succeeds.
shyear

A reference to a value that will contain a year number (between 1900 and 9999) if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlFuncs Class | CXlFuncs Methods


CXlMacros Class

Supports calls to Excel macro functions.

class CXlMacros

Overview

The CXlMacros class contains only static methods. Each of these methods calls the corresponding Excel macro function.

None of these functions may be called from worksheet functions.

Return values

All methods return a result code, which is zero if the function has succeeded, and non-zero if the function has failed for any reason. See Error codes for a list of return values.

Note that the results of some functions may still contain Excel error values, even if a zero result code is returned, and you should take care to test the type of these results where appropriate.

Worksheet functions

CXlFuncs only contains macro functions. If you want to call an Excel worksheet function, use the CXlFuncs class.

Other macro functions

The CXlMacros class does not implement all Excel macro functions. If the function you want is not implemented, you can call it yourself via the CXlOper::Excel() method using the techniques described in Calling an Excel built-in function from your add-in.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Methods | xlfuncs.h | CXlFuncs object | CXllApp::Excel | CXlOper::Excel


CXlMacros Methods

The methods of the CXlMacros class are listed here.

Command-equivalent Macro Functions

Activate | Switches to a window
ActivateA | Switches to a window
ActivateNext | Switches to the next window or switches to the next sheet in a workbook
ActivatePrev | Switches to the previous window or switches to the previous sheet in a workbook
ActivateW | Switches to a window
ActiveCellFont | Equivalent to formatting individual characters in a cell
AddinManager | Adds or removes an add-in from the working set
Alignment | Aligns the contents of the selected cells
ApplyStyle | Applies a previously defined style to the current selection
AppMaximize | Maximizes the Microsoft Excel window
AppMinimize | Minimizes the Microsoft Excel window
AppMove | Moves the Microsoft Excel window
AppRestore | Restores the Microsoft Excel window
AppSize | Resizes the Microsoft Excel window
Border | Adds a border to the selected cell or range of cells
CalculateDocument | Calculates only the active worksheet
CalculateNow | Calculates all sheets in all open workbooks
CellProtection | Allows you to control cell protection and display
Clear | Clears contents, formats, notes, or all of these from the active worksheet
Close | Closes the active window
CloseAll | Equivalent to choosing the Close All command from the File menu
ColumnWidth | Changes the width of the columns in the specified reference
Copy | Equivalent to choosing the Copy command from the Edit menu
Cut | Equivalent to choosing the Cut command from the Edit menu
DataSeries | Equivalent to choosing the Series command from the Fill submenu on the Edit menu
DefineName | Defines a name on the active sheet
DeleteName | Deletes the specified name
EditDelete | Removes the selected cells from the worksheet and shifts other cells to close up the space
FileClose | Closes the active workbook
FileDelete | Deletes a file from the disk
FillAuto | Equivalent to copying cells or automatically filling a selection by dragging the fill selection handle with the mouse
FillDown | Copies the contents and formats of the cells in the top row of a selection into the rest of the rows in the selection
FillGroup | Copies the contents of the active worksheet's selection to the same area on all other worksheets in the group
FillLeft | Copies the contents and formats of the cells in the right column of a selection into the rest of the columns in the selection
FillRight | Copies the contents and formats of the cells in the left column of a selection into the rest of the columns in the selection
FillUp | Copies the contents and formats of the cells in the bottom row of a selection into the rest of the rows in the selection
FontProperties | Equivalent to choosing the Cells command from the Format menu
FormatNumber | Equivalent to choosing the Number tab in the Format Cells dialog box
FormulaFill | Enters a formula in the range specified or in the current selection
FormulaReplace | Finds and replaces characters in cells on your worksheet
FreezePanes | Equivalent to choosing the Freeze Panes command from the Window menu or clicking the Freeze Panes button.
FullScreen | Equivalent to choosing the Full Screen command from the View menu
GoalSeek | Equivalent to choosing the Goal Seek command from the Tools menu
Hide | Hides the active window
HLine | Scrolls through the active window by a specific number of columns
HPage | Scrolls through the active window by a specific number of columns
HScroll | Horizontally scrolls through the active sheet by percentage or by column number
Insert | Inserts a blank cell or range of cells or pastes cells from the Clipboard into a sheet
Justify | Rearranges the text in a range so that it fills the range evenly
Links | Returns the names of all workbooks referred to by external references in the workbook specified
NewDefaultWorkbook | Creates a new workbook containing the default number of worksheets
NewSingleSheetWorkbook | Creates a new workbook containing a single worksheet
NewWindow | Creates a new window for the active workbook
Note | Creates a note or replaces characters in a note
Open | Opens an existing workbook
OptionsCalculation | Controls when and how formulas in open workbooks are calculated
Paste | Equivalent to choosing the Paste command from the Edit menu
PasteSpecial | Equivalent to choosing the Paste Special command from the Edit menu
Patterns | Equivalent to filling in the Patterns dialog
Quit | Quits Microsoft Excel and closes any open documents
RowHeight | Changes the height of the rows in a reference
Save | Saves the active document
SaveAs | Equivalent to choosing the Save As command from the File menu
SaveCopyAs | Saves a copy of the current document using a different name but all the current document settings, such as passwords and file protection
Select | Equivalent to selecting cells or changing the active cell
SelectAll | Equivalent to selecting all the sheets in a workbook
ShowActiveCell | Scrolls the active window so the active cell becomes visible
Split | Equivalent to choosing the Split command from the Window menu or to dragging the split bar in the active window's scroll bar.
StandardWidth | Sets the default width used for all columns in a worksheet
SummaryInfo | Generates the summary information for the active workbook
Undo | Equivalent to choosing the Undo command from the Edit menu
UnfreezePanes | Equivalent to choosing the Unfreeze Panes command from the Window menu or clicking the Unfreeze Panes button.
Unhide | Equivalent to choosing the Unhide command from the Window menu
VLine | Scrolls through the active window vertically by the number of rows you specify
VPage | Vertically scrolls through the active window one window at a time
VScroll | Vertically scrolls through the active sheet by percentage or by row number
WindowMaximize | Changes the active window from its normal size to full size
WindowMinimize | Shrinks a window to an icon
WindowMove | Moves the active window so that its upper-left corner is at the specified horizontal and vertical positions
WindowRestore | Changes the active window from maximized or minimized size to its previous size
WindowSize | Changes the size of the active window by moving its lower-right corner so that the window has the width and height you specify
WorkbookActivate | Equivalent to activating a worksheet by clicking on its tab
WorkbookActivateA | Equivalent to activating a worksheet by clicking on its tab
WorkbookActivateW | Equivalent to activating a worksheet by clicking on its tab
WorkbookCopy | Copies a worksheet from the current workbook to another workbook or to a new position in the current workbook
WorkbookDelete | Deletes a sheet or group of sheets from the current workbook
WorkbookHide | Hides sheets in the active workbook
WorkbookInsert | Inserts one or more new sheets into the current workbook
WorkbookMove | Moves a worksheet from the current workbook to another workbook or to a new position in the current workbook
WorkbookName | Renames a sheet in a workbook
WorkbookNext | Activates the next sheet in the active workbook
WorkbookPrev | Activates the previous sheet in the active workbook
WorkbookProtect | Renames a sheet in a workbook
WorkbookUnhide | Unhides sheets in the active workbook
Zoom | Enlarges or reduces a document in the active window
ZoomMax | The current selection is enlarged or reduced to completely fill the active window
ZoomNormal | The document is restored to normal 100% magnification

Customizing Macro Functions

Alert | Displays a dialog box and message and waits for you to choose a button
AppTitle | Changes the title of the Microsoft Excel application workspace to the title you specify
Beep | Sounds a tone
DisableInput | Blocks all input from the keyboard and mouse to Microsoft Excel
Echo | Controls screen updating while a macro is running
Error | Controls the display of alert dialogs while a macro is running
Formula | Enters a formula in the active cell or in a reference
FormulaArray | Enters a formula as an array formula in the range specified or in the current selection
FormulaArrayIntl | Enters a US English formula as an array formula in the range specified or in the current selection
FormulaIntl | Enters a US English formula in the active cell or in a reference

Information Macro Functions

ActiveCell | Returns the reference of the active cell in the selection as an external reference
Caller | Returns information about the cell, range of cells, command on a menu, tool on a toolbar, or object that called the macro that is currently running
Directory | Sets the current drive and directory or folder to the specified path and returns the name of the new directory or folder as text
Documents | Returns the names of the specified open workbooks
DocumentsA | Returns the names of the specified open workbooks
DocumentsW | Returns the names of the specified open workbooks
Files | Returns the names of all files in the specified directory or folder
GetActiveWorkbookName | Returns the name of the active workbook
GetActiveWorksheetName | Returns the name of the active worksheet
GetCell | Returns information about the cell, range of cells, command on a menu, tool on a toolbar, or object that called the macro that is currently running
GetCellIsArray | Returns whether a cell is part of an array
GetCellIsFormula | Returns whether a cell contains a formula
GetCellIsHidden | Returns whether a cell's formula is hidden
GetCellIsLocked | Returns whether a cell is locked
GetDef | Returns the name, as text, that is defined for a particular area, value, or formula in a workbook
GetDocument | Returns information about a sheet in a workbook
GetFormula | Returns the contents of a cell as they would appear in the formula bar
GetFormulaA | Returns the contents of a cell as they would appear in the formula bar
GetFormulaIntl | Returns the contents of a cell as they would appear in the formula bar with US English settings
GetFormulaIntlA | Returns the contents of a cell as they would appear in the formula bar with US English settings
GetFormulaIntlW | Returns the contents of a cell as they would appear in the formula bar with US English settings
GetFormulaW | Returns the contents of a cell as they would appear in the formula bar
GetName | Returns the definition of a name as it appears in the Refers To box of the Define Name dialog box
GetNameIsLocal | Returns TRUE if the name is defined for just the sheet
GetNote | Returns characters from a note
GetWorkbook | Returns information about a workbook
GetWorkspace | Returns information about the workspace
Names | Returns the specified names defined in the specified workbook
Selection | Returns the reference or object identifier of the selection as an external reference
Windows | Returns the names of the specified open Microsoft Excel windows
WorkbookGetWorksheetNames | Returns a list of all the sheets in a workbook

Lookup & Reference Macro Functions

AbsRef | Returns the absolute reference of the cells that are offset from a reference by a specified amount
DeRef | Returns the value of the cells in a reference
Evaluate | Evaluates a formula or expression that is in the form of text and returns the result
EvaluateIntl | Evaluates a formula or expression that is in the form of English text and returns the result
FormulaConvert | Changes the style and type of references in a formula between A1 and R1C1 and between relative and absolute
RefText | Converts a reference to an absolute reference in the form of text
RelRef | Returns the reference of a cell or cells relative to the upper-left cell of rel_to_ref
TextRef | Converts a reference to an absolute reference in the form of text

Construction

public method CXlMacros Constructs a CXlMacros object

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | xlfuncs.h | CXlFuncs object | CXllApp::Excel | CXlOper::Excel


CXlMacros::AbsRef

Returns the absolute reference of the cells that are offset from a reference by a specified amount

static int AbsRef(
   CXlOper& xloRef,
   LPCTSTR ref_text,
   const CXlOper& reference = CXlOper::MissingArg()
);

Parameters

xloRef

A reference to a CXlOper that will contain the desired data if the function succeeds.
ref_text

Ref_text specifies a position relative to reference.
reference

Reference is a cell or range of cells specifying a starting point that ref_text uses to locate another range of cells.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Activate

Switches to a window

static int Activate(
   const TCHAR* window_text,
   unsigned short pane_num = 1
);

Parameters

window_text

Text specifying the name of a window to switch to: for example, "Book1".
pane_num

Pane number within window.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::ActivateA

Switches to a window

static int ActivateA(
   const char* window_text,
   unsigned short pane_num = 1
);

Parameters

window_text

Text specifying the name of a window to switch to: for example, "Book1".
pane_num

Pane number within window.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::ActivateNext

Switches to the next window or switches to the next sheet in a workbook

static int ActivateNext(
   LPCTSTR workbook_text = 0
);

Parameters

workbook_text

Workbook_text is the name of the workbook for which you want to activate a window. If it is omitted, then the next workbook will be activated.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::ActivatePrev

Switches to the previous window or switches to the previous sheet in a workbook

static int ActivatePrev(
   LPCTSTR workbook_text = 0
);

Parameters

workbook_text

Workbook_text is the name of the workbook for which you want to activate a window. If it is omitted, then the previous workbook will be activated.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::ActivateW

Switches to a window

static int ActivateW(
   const wchar_t* window_text,
   unsigned short pane_num = 1
);

Parameters

window_text

Text specifying the name of a window to switch to: for example, "Book1".
pane_num

Pane number within window.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::ActiveCell

Returns the reference of the active cell in the selection as an external reference

static int ActiveCell(
   CXlOper& xloRef
);

Parameters

xloRef

A reference to a CXlOper that will contain the active cell if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::ActiveCellFont

Equivalent to formatting individual characters in a cell

static int ActiveCellFont(
   LPCTSTR font,
   LPCTSTR font_style = 0,
   unsigned short size = 0,
   short int strikethrough = -1,
   short int superscript = -1,
   short int subscript = -1,
   short int underline = -1,
   short int color = -1,
   short int normal = -1,
   short int background = 0,
   short int start_char = 0,
   short int char_count = -1
);

Parameters

font

Font is the name of the font as it appears in the Font tab. An empty string or a null pointer is treated as a missing argument.
font_style

Font_style is the name of the font style as it appears in the Font tab. An empty string or a null pointer is treated as a missing argument.
size

Size is the font size, in points. A value of 0 is treated as a missing argument.
strikethrough

Strikethrough corresponds to the Strikethrough check box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.
superscript

Superscript corresponds to the Superscript check box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.
subscript

Subscript corresponds to the Subscript check box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.
underline

Underline corresponds to the Underline Drop-down box. A value of -1 is treated as a missing argument, A value greater than or equal to 0 are treated normally.
color

Color is a number from 0 to 56 corresponding to the colors in the Font tab; 0 corresponds to automatic color. A value of -1 is treated as a missing argument, A value greater than or equal to 0 are treated normally.
normal

Normal corresponds to the Normal Font check box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.
background

Background is a number from 1 to 3 specifying which type of background to apply to text in a chart. A value of 0 is treated as a missing argument, Values greater than 0 are treated normally.
start_char

Start_char specifies the first character to be formatted. A value of 0 is treated as a missing argument, Values greater than 0 are treated normally.
char_count

Char_count specifies how many characters to format. A value of 0 is treated as a missing argument, Values greater than 0 are treated normally.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::AddinManager

Adds or removes an add-in from the working set

static int AddinManager(
   unsigned short operation_num,
   LPCTSTR addinname_text,
   bool copy_logical = false
);

Parameters

operation_num

Operation_num determines the operation that the add-in manager will perform.
addinname_text

Addinname_text specifies the name or file name of the add-in.
copy_logical

Copy_logical specifies whether the add-in should be copied to the library directory.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Alert

Displays a dialog box and message and waits for you to choose a button

static int Alert(
   LPCTSTR message_text,
   unsigned short type_num = 2,
   LPCTSTR help_ref = 0
);

Parameters

message_text

Message_text is the message displayed in the dialog box.
type_num

Type_num is a number from 1 to 3 specifying which type of dialog box to display.
help_ref

Help_ref is a reference to a custom online Help topic, in the form "filename! topic_number".

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Alignment

Aligns the contents of the selected cells

static int Alignment(
   unsigned short horiz_align = 0,
   short int wrap = -1,
   short int vert_align = 0,
   short int orientation = -1
);

Parameters

horiz_align

Horiz_align is a number from 1 to 7 specifying the type of horizontal alignment. A value of 0 is treated as a missing argument.
wrap

Wrap corresponds to the Wrap Text check box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.
vert_align

Vert_align is a number from 1 to 4 specifying the vertical alignment of the text. A value of 0 is treated as a missing argument, A value greater than 0 is treated normally.
orientation

Orientation is a number from 0 to 4 specifying the orientation of the text. A value of -1 is treated as a missing argument, A value greater than or equal to 0 is treated normally.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::ApplyStyle

Applies a previously defined style to the current selection

static int ApplyStyle(
   LPCTSTR style_text
);

Parameters

style_text

Name of a previously defined style.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::AppMaximize

Maximizes the Microsoft Excel window

static int AppMaximize( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::AppMinimize

Minimizes the Microsoft Excel window

static int AppMinimize( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::AppMove

Moves the Microsoft Excel window

static int AppMove(
   long x_num,
   long y_num
);

Parameters

x_num

Horizontal position.
y_num

Vertical position.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::AppRestore

Restores the Microsoft Excel window

static int AppRestore( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::AppSize

Resizes the Microsoft Excel window

static int AppSize(
   long x_num,
   long y_num
);

Parameters

x_num

Width.
y_num

Height.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::AppTitle

Changes the title of the Microsoft Excel application workspace to the title you specify

static int AppTitle(
   LPCTSTR text = 0
);

Parameters

text

Text is the title you want to assign to the Microsoft Excel application workspace.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Beep

Sounds a tone

static int Beep(
   unsigned short tone_num = 1
);

Parameters

tone_num

Tone_num is a number from 1 to 4 specifying the tone to be played.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Border

Adds a border to the selected cell or range of cells

static int Border(
   short int outline = -1,
   short int left = -1,
   short int right = -1,
   short int top = -1,
   short int bottom = -1,
   short int outline_color = -1,
   short int left_color = -1,
   short int right_color = -1,
   short int top_color = -1,
   short int bottom_color = -1
);

Parameters

outline

Outline is a number from 0 to 7 specifying the line style. A value of -1 is treated as a missing argument.
left

Left is a number from 0 to 7 specifying the line style. A value of -1 is treated as a missing argument.
right

Right is a number from 0 to 7 specifying the line style. A value of -1 is treated as a missing argument.
top

Top is a number from 0 to 7 specifying the line style. A value of -1 is treated as a missing argument.
bottom

Bottom is a number from 0 to 7 specifying the line style. A value of -1 is treated as a missing argument.
outline_color

A number from 1 to 56 corresponding to the Color box in the Border dialog box. Zero corresponds to automatic color. A value of -1 is treated as a missing argument.
left_color

A number from 1 to 56 corresponding to the Color box in the Border dialog box. Zero corresponds to automatic color. A value of -1 is treated as a missing argument.
right_color

A number from 1 to 56 corresponding to the Color box in the Border dialog box. Zero corresponds to automatic color. A value of -1 is treated as a missing argument.
top_color

A number from 1 to 56 corresponding to the Color box in the Border dialog box. Zero corresponds to automatic color. A value of -1 is treated as a missing argument.
bottom_color

A number from 1 to 56 corresponding to the Color box in the Border dialog box. Zero corresponds to automatic color. A value of -1 is treated as a missing argument.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::CalculateDocument

Calculates only the active worksheet

static int CalculateDocument( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::CalculateNow

Calculates all sheets in all open workbooks

static int CalculateNow( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Caller

Returns information about the cell, range of cells, command on a menu, tool on a toolbar, or object that called the macro that is currently running

static int Caller(
   CXlOper& xloRef
);

Parameters

xloRef

A reference to a CXlOper that will describe the caller if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::CellProtection

Allows you to control cell protection and display

static int CellProtection(
   short int locked,
   short int hidden
);

Parameters

locked

Locked corresponds to the Locked check box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.
hidden

Hidden corresponds to the Hidden check box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Clear

Clears contents, formats, notes, or all of these from the active worksheet

static int Clear(
   unsigned short type_num
);

Parameters

type_num

Type_num is a number from 1 to 4 specifying what to clear.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Close

Closes the active window

static int Close(
   bool save_logical,
   bool route_logical = false
);

Parameters

save_logical

Save_logical is a logical value that specifies whether to save the file before closing the window.
route_logical

Route_logical is a logical value that specifies whether to route the file after closing it.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::CloseAll

Equivalent to choosing the Close All command from the File menu

static int CloseAll( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::ColumnWidth

Changes the width of the columns in the specified reference

static int ColumnWidth(
   double width_num,
   const CXlOper& reference = CXlOper::MissingArg(),
   bool standard = false,
   unsigned short type_num = 0,
   double standard_num = 0.0
);

Parameters

width_num

Width_num specifies how wide you want the columns to be in units of one character of the font corresponding to the Normal cell style.
reference

Reference specifies the columns for which you want to change the width.
standard

Standard is a logical value corresponding to the Standard Width command from the Column submenu on the Format menu.
type_num

Type_num is a number from 1 to 3 corresponding to the Hide, Unhide, or AutoFit Selection commands. Zero is treated as a missing argument.
standard_num

Standard_num specifies how wide the standard width is, and is measured in points. Zero is treated as a missing argument.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Copy

Equivalent to choosing the Copy command from the Edit menu

static int Copy(
   const CXlOper& from_reference = CXlOper::MissingArg(),
   const CXlOper& to_reference = CXlOper::MissingArg()
);

Parameters

from_reference

From_reference is a reference to the cell or range of cells you want to copy. If from_reference is omitted, it is assumed to be the current selection.
to_reference

To_reference is a reference to the cell or range of cells where you want to paste what you have copied.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Cut

Equivalent to choosing the Cut command from the Edit menu

static int Cut(
   const CXlOper& from_reference = CXlOper::MissingArg(),
   const CXlOper& to_reference = CXlOper::MissingArg()
);

Parameters

from_reference

From_reference is a reference to the cell or range of cells you want to cut. If from_reference is omitted, it is assumed to be the current selection.
to_reference

To_reference is a reference to the cell or range of cells where you want to paste what you have copied.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::CXlMacros

Constructs a CXlMacros object

CXlMacros( );

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::DataSeries

Equivalent to choosing the Series command from the Fill submenu on the Edit menu

static int DataSeries(
   unsigned short rowcol = 0,
   unsigned short type_num = 1,
   unsigned short date_num = 1,
   double step_value = 1.0,
   bool has_stop_value = false,
   double stop_value = 0.0,
   short int trend = -1
);

Parameters

rowcol

Rowcol is a number that specifies where the series should be entered. A value of 0 is treated as a missing argument.
type_num

Type_num is a number from 1 to 4 that specifies the type of series.
date_num

Date_num is a number from 1 to 4 that specifies the date unit of the series.
step_value

Step_value is a number that specifies the step value for the series.
has_stop_value

has_stop_value is a logical value that specifies whether the series has a stop_value. If it is false, then stop_value will be treated as missing.
stop_value

Stop_value is a number that specifies the stop value for the series. It is ignored if has_stop_value is false.
trend

Trend is a logical value corresponding to the Trend check box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::DefineName

Defines a name on the active sheet

static int DefineName(
   LPCTSTR name_text,
   const CXlOper& refers_to = CXlOper::MissingArg()
);

Parameters

name_text

Name_text is the text you want to use as the name.
refers_to

Refers_to describes what name_text should refer to.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::DeleteName

Deletes the specified name

static int DeleteName(
   LPCTSTR name_text
);

Parameters

name_text

Name_text is a text value specifying the name that you want to delete.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::DeRef

Returns the value of the cells in a reference

static int DeRef(
   CXlOper& xloValue,
   const CXlOper& reference
);

Parameters

xloValue

A reference to a CXlOper that will contain the desired data if the function succeeds.
reference

Reference is the cell or cells from which you want to obtain a value.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Directory

Sets the current drive and directory or folder to the specified path and returns the name of the new directory or folder as text

static int Directory(
   CString strnewdirectory,
   LPCTSTR path_text = 0
);

Parameters

strnewdirectory

A reference to a string that will contain the desired information if the function succeeds.
path_text

Path_text is the drive and directory or folder you want to change to. An empty or null string is treated as a missing argument.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::DisableInput

Blocks all input from the keyboard and mouse to Microsoft Excel

static int DisableInput(
   bool logical = 1
);

Parameters

logical

Logical is a logical value specifying whether input is currently disabled. If logical is TRUE, input is disabled; if FALSE, input is reenabled.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Documents

Returns the names of the specified open workbooks

static int Documents(
   std::vector<CStringA>& documents,
   short int type_num = 1,
   LPCSTR match_text = 0
);
static int Documents(
   std::vector<CStringW>& documents,
   short int type_num = 1,
   LPCSTR match_text = 0
);

Parameters

documents

A vector of strings which will be populated with the list of names.
type_num

Type_num is a number specifying whether to include add-in workbooks in the array of workbooks.
match_text

Match_text specifies the workbooks whose names you want returned and can include wildcard characters.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::DocumentsA

Returns the names of the specified open workbooks

static int DocumentsA(
   std::vector<CStringA>& documents,
   short int type_num = 1,
   LPCSTR match_text = 0
);

Parameters

documents

A vector of strings which will be populated with the list of names.
type_num

Type_num is a number specifying whether to include add-in workbooks in the array of workbooks.
match_text

Match_text specifies the workbooks whose names you want returned and can include wildcard characters.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::DocumentsW

Returns the names of the specified open workbooks

static int DocumentsW(
   std::vector<CStringW>& documents,
   short int type_num = 1,
   LPCWSTR match_text = 0
);

Parameters

documents

A vector of strings which will be populated with the list of names.
type_num

Type_num is a number specifying whether to include add-in workbooks in the array of workbooks.
match_text

Match_text specifies the workbooks whose names you want returned and can include wildcard characters.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Echo

Controls screen updating while a macro is running

static int Echo(
   short int logical
);

Parameters

logical

Logical is a logical value specifying whether screen updating is on or off. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods | CXlSuspendEcho


CXlMacros::EditDelete

Removes the selected cells from the worksheet and shifts other cells to close up the space

static int EditDelete(
   unsigned short shift_num
);

Parameters

shift_num

Shift_num is a number from 1 to 4 specifying whether to shift cells left or up after deleting the current selection or else to delete the entire row or column.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Error

Controls the display of alert dialogs while a macro is running

static int Error(
   bool enable_logical
);

Parameters

enable_logical

Enable_logical is a logical value specifying whether alerts are on or off. A value of true causes alerts to be displayed, false causes aletrs to be suppressed.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods | CXlSuspendError


CXlMacros::Evaluate

Evaluates a formula or expression that is in the form of text and returns the result

static int Evaluate(
   CXlOper& xloValue,
   LPCTSTR formula_text
);

Parameters

xloValue

A reference to a CXlOper that will contain the desired data if the function succeeds.
formula_text

Formula_text is the expression in the form of text that you want to evaluate.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::EvaluateIntl

Evaluates a formula or expression that is in the form of English text and returns the result

static int EvaluateIntl(
   CXlOper& xloValue,
   LPCTSTR formula_text
);

Parameters

xloValue

A reference to a CXlOper that will contain the desired data if the function succeeds.
formula_text

Formula_text is the expression in the form of text that you want to evaluate. The formula should always be in English, using the separators and syntax of US English settings.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FileClose

Closes the active workbook

static int FileClose(
   bool save_logical,
   bool route_logical = false
);

Parameters

save_logical

Save_logical is a logical value that specifies whether to save the file before closing the window.
route_logical

Route_logical is a logical value that specifies whether to route the file after closing it.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FileDelete

Deletes a file from the disk

static int FileDelete(
   LPCTSTR file_text
);

Parameters

file_text

File_text is the name of the file to delete.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Files

Returns the names of all files in the specified directory or folder

static int Files(
   std::vector<CString>& files,
   LPCTSTR directory_text = 0
);

Parameters

files

A vector of strings which will be populated with the list of names.
directory_text

Directory_text specifies which directories or folders to return filenames from.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FillAuto

Equivalent to copying cells or automatically filling a selection by dragging the fill selection handle with the mouse

static int FillAuto(
   const CXlOper& destination_ref,
   unsigned short copy_only = 0
);

Parameters

destination_ref

Destination_ref is the range of cells into which you want to fill data.
copy_only

Copy_only is a number specifying whether to copy cells or perform an AutoFill operation.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FillDown

Copies the contents and formats of the cells in the top row of a selection into the rest of the rows in the selection

static int FillDown( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FillGroup

Copies the contents of the active worksheet's selection to the same area on all other worksheets in the group

static int FillGroup(
   unsigned short type_num
);

Parameters

type_num

Type_num is a number from 1 to 3 that corresponds to the choices in the Fill Across Worksheets dialog box.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FillLeft

Copies the contents and formats of the cells in the right column of a selection into the rest of the columns in the selection

static int FillLeft( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FillRight

Copies the contents and formats of the cells in the left column of a selection into the rest of the columns in the selection

static int FillRight( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FillUp

Copies the contents and formats of the cells in the bottom row of a selection into the rest of the rows in the selection

static int FillUp( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FontProperties

Equivalent to choosing the Cells command from the Format menu

static int FontProperties(
   LPCTSTR font,
   LPCTSTR font_style = 0,
   unsigned short size = 0,
   short int strikethrough = -1,
   short int superscript = -1,
   short int subscript = -1,
   short int underline = -1,
   short int color = -1,
   short int normal = -1,
   short int background = 0,
   short int start_char = 0,
   short int char_count = -1
);

Parameters

font

Font is the name of the font as it appears in the Font tab. An empty string or a null pointer is treated as a missing argument.
font_style

Font_style is the name of the font style as it appears in the Font tab. An empty string or a null pointer is treated as a missing argument.
size

Size is the font size, in points. A value of 0 is treated as a missing argument.
strikethrough

Strikethrough corresponds to the Strikethrough check box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.
superscript

Superscript corresponds to the Superscript check box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.
subscript

Subscript corresponds to the Subscript check box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.
underline

Underline corresponds to the Underline Drop-down box. A value of -1 is treated as a missing argument, A value greater than or equal to 0 are treated normally.
color

Color is a number from 0 to 56 corresponding to the colors in the Font tab; 0 corresponds to automatic color. A value of -1 is treated as a missing argument, A value greater than or equal to 0 are treated normally.
normal

Normal corresponds to the Normal Font check box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.
background

Background is a number from 1 to 3 specifying which type of background to apply to text in a chart. A value of 0 is treated as a missing argument, Values greater than 0 are treated normally.
start_char

Start_char specifies the first character to be formatted. A value of 0 is treated as a missing argument, Values greater than 0 are treated normally.
char_count

Char_count specifies how many characters to format. A value of 0 is treated as a missing argument, Values greater than 0 are treated normally.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FormatNumber

Equivalent to choosing the Number tab in the Format Cells dialog box

static int FormatNumber(
   LPCTSTR format_text
);

Parameters

format_text

Format_text is a format string, such as "#, ##0.00", specifying which format to apply to the selection.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Formula

Enters a formula in the active cell or in a reference

static int Formula(
   const CXlOper& formula_text,
   const CXlOper& reference = CXlOper::MissingArg()
);

Parameters

formula_text

Formula_text can be text, a number, a reference, or a formula in the form of text, or a reference to a cell containing any of the above.
reference

Reference specifies where formula_text is to be entered.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FormulaArray

Enters a formula as an array formula in the range specified or in the current selection

static int FormulaArray(
   LPCTSTR formula_text,
   const CXlOper& reference = CXlOper::MissingArg()
);

Parameters

formula_text

Formula_text is the text you want to enter in the array.
reference

Reference specifies where formula_text is to be entered.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FormulaArrayIntl

Enters a US English formula as an array formula in the range specified or in the current selection

static int FormulaArrayIntl(
   LPCTSTR formula_text,
   const CXlOper& reference = CXlOper::MissingArg()
);

Parameters

formula_text

Formula_text is the text you want to enter in the array. The formula should appear as it would in an English version of Excel, using US English regional settings.
reference

Reference specifies where formula_text is to be entered.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FormulaConvert

Changes the style and type of references in a formula between A1 and R1C1 and between relative and absolute

static int FormulaConvert(
   CString& strformula,
   LPCTSTR formula_text,
   bool from_a1,
   short int to_a1 = -1,
   unsigned short to_ref_type = 0,
   const CXlOper& rel_to_ref = CXlOper::MissingArg()
);

Parameters

strformula

A reference to a string that will contain the desired data if the function succeeds.
formula_text

Formula_text is the formula, given as text, containing the references you want to change.
from_a1

From_a1 is a logical value specifying whether the references in formula_text are in A1 or R1C1 style.
to_a1

To_a1 is a logical value specifying the form for the references FORMULA.CONVERT returns. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.
to_ref_type

To_ref_type is a number from 1 to 4 specifying the reference type of the returned formula. A value of 0 is treated as a missing argument, A value greater than 0 is treated normally.
rel_to_ref

Rel_to_ref is an absolute reference that specifies what cell the relative references are or should be relative to.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FormulaFill

Enters a formula in the range specified or in the current selection

static int FormulaFill(
   LPCTSTR formula_text,
   const CXlOper& reference = CXlOper::MissingArg()
);

Parameters

formula_text

Formula_text is the text with which you want to fill the range.
reference

Reference specifies where formula_text is entered.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FormulaIntl

Enters a US English formula in the active cell or in a reference

static int FormulaIntl(
   const CXlOper& formula_text,
   const CXlOper& reference = CXlOper::MissingArg()
);

Parameters

formula_text

Formula_text can be text, a number, a reference, or a formula in the form of text, or a reference to a cell containing any of the above. The formula should appear as it would in an English version of Excel, using US English regional settings.
reference

Reference specifies where formula_text is to be entered.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FormulaReplace

Finds and replaces characters in cells on your worksheet

static int FormulaReplace(
   LPCTSTR find_text,
   LPCTSTR replace_text,
   bool look_at_entire_cell,
   bool look_by_rows = true,
   bool active_cell_only = true,
   bool match_case = false
);

Parameters

find_text

Find_text is the text you want to find.
replace_text

Replace_text is the text you want to replace find_text with.
look_at_entire_cell

If true, looks for find_text as the entire contents of a cell. If false, looks for find_text as part of the contents of a cell.
look_by_rows

If true, looks for find_text by rows. If false, looks for find_text by columns.
active_cell_only

If active_cell_only is true, find_text is replaced in the active cell only. If active_cell is false, find_text is replaced in the entire selection, or, if the selection is a single cell, in the entire sheet.
match_case

Match_case is a logical value corresponding to the Match Case check box in the Replace dialog box.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::FreezePanes

Equivalent to choosing the Freeze Panes command from the Window menu or clicking the Freeze Panes button.

static int FreezePanes(
   COL12 col_split,
   RW12 row_split
);

Parameters

col_split

specifies where to split the window vertically and is measured in columns from the left of the window.
row_split

specifies where to split the window horizontally and is measured in rows from the top of the window.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

Splits the active window into panes, creates frozen panes, or freezes existing panes. Use FreezePanes to keep row or column titles on the screen while scrolling to other parts of the sheet.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods | CXlMacros::UnfreezePanes | CXlMacros::Split


CXlMacros::FullScreen

Equivalent to choosing the Full Screen command from the View menu

static int FullScreen(
   bool logical
);

Parameters

logical

Logical switches to fullscreen if TRUE or omitted; exits fullscreen mode if FALSE.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetActiveWorkbookName

Returns the name of the active workbook

static int GetActiveWorkbookName(
   CString& book_name
);

Parameters

book_name

A reference to a string that will contain the desired data if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetActiveWorksheetName

Returns the name of the active worksheet

static int GetActiveWorksheetName(
   CString& book_name,
   bool full_name = false
);

Parameters

book_name

A reference to a string that will contain the desired data if the function succeeds.
full_name

If true, then the full sheet name will be returned, in the form "[BOOK1.XLS]Sheet1". If false, then only the sheet name will be returned.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetCell

Returns information about the cell, range of cells, command on a menu, tool on a toolbar, or object that called the macro that is currently running

static int GetCell(
   CXlOper& xloData,
   short int type_num,
   const CXlOper& reference = CXlOper::MissingArg()
);

Parameters

xloData

A reference to a CXlOper that will contain the desired data if the function succeeds.
type_num

Type_num is a number that specifies what type of cell information you want.
reference

Reference is a cell or a range of cells from which you want information. If it is omitted, then the active cell will be used.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetCellIsArray

Returns whether a cell is part of an array

static int GetCellIsArray(
   bool& barray,
   const CXlOper& reference = CXlOper::MissingArg()
);

Parameters

barray

A reference to a boolean value that will contain the desired data if the function succeeds.
reference

Reference is a cell or a range of cells from which you want information. If it is omitted, then the active cell will be used.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetCellIsFormula

Returns whether a cell contains a formula

static int GetCellIsFormula(
   bool& bformula,
   const CXlOper& reference = CXlOper::MissingArg()
);

Parameters

bformula

A reference to a boolean value that will contain the desired data if the function succeeds.
reference

Reference is a cell or a range of cells from which you want information. If it is omitted, then the active cell will be used.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetCellIsHidden

Returns whether a cell's formula is hidden

static int GetCellIsHidden(
   bool& bhidden,
   const CXlOper& reference = CXlOper::MissingArg()
);

Parameters

bhidden

A reference to a boolean value that will contain the desired data if the function succeeds.
reference

Reference is a cell or a range of cells from which you want information. If it is omitted, then the active cell will be used.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetCellIsLocked

Returns whether a cell is locked

static int GetCellIsLocked(
   bool& blocked,
   const CXlOper& reference = CXlOper::MissingArg()
);

Parameters

blocked

A reference to a boolean value that will contain the desired data if the function succeeds.
reference

Reference is a cell or a range of cells from which you want information. If it is omitted, then the active cell will be used.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetDef

Returns the name, as text, that is defined for a particular area, value, or formula in a workbook

static int GetDef(
   CString& strname,
   const CXlOper& def_text,
   LPCTSTR document_text = 0,
   short int type_num = 1
);

Parameters

strname

A reference to a string that will contain the desired data if the function succeeds.
def_text

Def_text can be anything you can define a name to refer to, including a reference, a value, an object, or a formula.
document_text

Document_text specifies the sheet or macro sheet that def_text is on.
type_num

Type_num is a number from 1 to 3 specifying which types of names are returned.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetDocument

Returns information about a sheet in a workbook

static int GetDocument(
   CXlOper& xloData,
   short int type_num,
   LPCTSTR name_text = 0
);

Parameters

xloData

A reference to a CXlOper that will contain the desired data if the function succeeds.
type_num

Type_num is a number that specifies what type of cell information you want.
name_text

Name_text is the name of an open document.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetFormula

Returns the contents of a cell as they would appear in the formula bar

static int GetFormula(
   CString& strformula,
   const CXlOper& reference
);

Parameters

strformula

A reference to a string that will contain the desired data if the function succeeds.
reference

Reference is a cell or range of cells on a sheet or macro sheet.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetFormulaA

Returns the contents of a cell as they would appear in the formula bar

static int GetFormulaA(
   CStringA& strformula,
   const CXlOper& reference
);

Parameters

strformula

A reference to a string that will contain the desired data if the function succeeds.
reference

Reference is a cell or range of cells on a sheet or macro sheet.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetFormulaIntl

Returns the contents of a cell as they would appear in the formula bar with US English settings

static int GetFormulaIntl(
   CString& strformula,
   const CXlOper& reference
);

Parameters

strformula

A reference to a string that will contain the desired data if the function succeeds.
reference

Reference is a cell or range of cells on a sheet or macro sheet.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetFormulaIntlA

Returns the contents of a cell as they would appear in the formula bar with US English settings

static int GetFormulaIntlA(
   CStringA& strformula,
   const CXlOper& reference
);

Parameters

strformula

A reference to a string that will contain the desired data if the function succeeds.
reference

Reference is a cell or range of cells on a sheet or macro sheet.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetFormulaIntlW

Returns the contents of a cell as they would appear in the formula bar with US English settings

static int GetFormulaIntlW(
   CStringW& strformula,
   const CXlOper& reference
);

Parameters

strformula

A reference to a string that will contain the desired data if the function succeeds.
reference

Reference is a cell or range of cells on a sheet or macro sheet.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetFormulaW

Returns the contents of a cell as they would appear in the formula bar

static int GetFormulaW(
   CStringW& strformula,
   const CXlOper& reference
);

Parameters

strformula

A reference to a string that will contain the desired data if the function succeeds.
reference

Reference is a cell or range of cells on a sheet or macro sheet.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetName

Returns the definition of a name as it appears in the Refers To box of the Define Name dialog box

static int GetName(
   CString& strname,
   const CXlOper& name_text
);

Parameters

strname

A reference to a string that will contain the desired data if the function succeeds.
name_text

Reference is a cell or range of cells on a sheet or macro sheet.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetNameIsLocal

Returns TRUE if the name is defined for just the sheet

static int GetNameIsLocal(
   bool& blocal,
   const CXlOper& name_text
);

Parameters

blocal

A reference to a value that will contain the desired data if the function succeeds.
name_text

Reference is a cell or range of cells on a sheet or macro sheet.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

Calling this function is equivalent to calling =GET.NAME(name_text, 2).

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetNote

Returns characters from a note

static int GetNote(
   CString& strnote,
   const CXlOper& cell_ref = CXlOper::MissingArg(),
   unsigned short start_char = 1,
   short int num_chars = -1
);

Parameters

strnote

A reference to a string that will contain the desired data if the function succeeds.
cell_ref

Cell_ref is the cell to which the note is attached.
start_char

Start_char is the number of the first character in the note to return.
num_chars

Num_chars is the number of characters to return.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetWorkbook

Returns information about a workbook

static int GetWorkbook(
   CXlOper& xloData,
   short int type_num,
   LPCTSTR name_text = 0
);

Parameters

xloData

A reference to a CXlOper that will contain the desired data if the function succeeds.
type_num

Type_num is a number that specifies what type of information you want.
name_text

Name_text is the name of an open workbook. If omitted, the active workbook is used.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GetWorkspace

Returns information about the workspace

static int GetWorkspace(
   CXlOper& xloData,
   short int type_num
);

Parameters

xloData

A reference to a CXlOper that will contain the desired data if the function succeeds.
type_num

Type_num is a number that specifies what type of information you want.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::GoalSeek

Equivalent to choosing the Goal Seek command from the Tools menu

static int GoalSeek(
   const CXlOper& target_cell,
   const CXlOper& target_value,
   const CXlOper& variable_cell
);

Parameters

target_cell

Target_cell corresponds to the Set Cell box in the Goal Seek dialog box and is a reference to the cell containing the formula.
target_value

Target_value corresponds to the To Value box in the Goal Seek dialog box and is the value you want the formula in target_cell to return.
variable_cell

Variable_cell corresponds to the By Changing Cell box in the Goal Seek dialog box and is the single cell that you want Microsoft Excel to change so that the formula in target_cell returns target_value.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Hide

Hides the active window

static int Hide( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::HLine

Scrolls through the active window by a specific number of columns

static int HLine(
   long num_columns
);

Parameters

num_columns

Num_columns is the number of columns in the active worksheet or macro sheet you want to scroll through horizontally.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::HPage

Scrolls through the active window by a specific number of columns

static int HPage(
   long num_windows
);

Parameters

num_windows

Num_windows specifies the number of windows to scroll through the active window horizontally.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::HScroll

Horizontally scrolls through the active sheet by percentage or by column number

static int HScroll(
   double position,
   bool col_logical = false
);

Parameters

position

Position specifies the column you want to scroll to.
col_logical

Col_logical is a logical value specifying how the function scrolls.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Insert

Inserts a blank cell or range of cells or pastes cells from the Clipboard into a sheet

static int Insert(
   short int shift_num = 0
);

Parameters

shift_num

Shift_num is a number from 1 to 4 specifying which way to shift the cells. A value of zero is treated as a missing argument.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Justify

Rearranges the text in a range so that it fills the range evenly

static int Justify( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Links

Returns the names of all workbooks referred to by external references in the workbook specified

static int Links(
   std::vector<CString>& links,
   LPCTSTR document_text = "",
   short int type_num = 1
);

Parameters

links

A vector of strings which will be populated with the list of names.
document_text

Document_text is the name of a workbook, including its path.
type_num

Type_num is a number from 1 to 6 specifying the type of linked workbooks to return.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Names

Returns the specified names defined in the specified workbook

static int Names(
   std::vector<CString>& names,
   LPCTSTR document_text = 0,
   short int type_num = 1,
   LPCTSTR match_text = 0
);

Parameters

names

A vector of strings which will be populated with the list of names.
document_text

Document_text is text that specifies the workbook whose names you want returned.
type_num

Type_num is a number from 1 to 3 that specifies whether to include hidden names in the returned array.
match_text

Match_text is text that specifies the names you want returned and can include wildcard characters.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::NewDefaultWorkbook

Creates a new workbook containing the default number of worksheets

static int NewDefaultWorkbook( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

This function calls the XLM4 function NEW(5). See the Microsoft Excel on-line Help for function NEW for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::NewSingleSheetWorkbook

Creates a new workbook containing a single worksheet

static int NewSingleSheetWorkbook( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

This function calls the XLM4 function NEW(1). See the Microsoft Excel on-line Help for function NEW for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::NewWindow

Creates a new window for the active workbook

static int NewWindow( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Note

Creates a note or replaces characters in a note

static int Note(
   LPCTSTR add_text = "",
   const CXlOper& cell_ref = CXlOper::MissingArg(),
   unsigned short start_char = 1,
   unsigned short num_chars = -1
);

Parameters

add_text

Add_text is text of up to 255 characters you want to add to a note.
cell_ref

Cell_ref is the cell to which you want to add the note text.
start_char

Start_char is the number of the character at which you want add_text to be added.
num_chars

Num_chars is the number of characters that you want to replace in the note. A value of -1 is treated as a missing argument.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Open

Opens an existing workbook

static int Open(
   LPCTSTR file_text,
   short int update_links = 0,
   bool read_only = false,
   unsigned short format = 0,
   LPCTSTR prot_pwd = 0,
   LPCTSTR write_res_pwd = 0,
   bool ignore_rorec = false,
   unsigned short file_origin = 0,
   LPCTSTR custom_delimit = 0,
   bool editable = false,
   unsigned short file_access = 0,
   bool notify_logical = false
);

Parameters

file_text

File_text is the name, as text, of the workbook you want to open.
update_links

Update_links specifies whether and how to update external and remote references.
read_only

Read_only corresponds to the Read Only check box in the Open dialog box.
format

Format specifies what character to use as a delimiter when opening text files. A value of 0 is treated as a missing argument.
prot_pwd

Prot_pwd is the password, as text, required to unprotect a protected file.
write_res_pwd

Write_res_pwd is the password, as text, required to open a read-only file with full write privileges.
ignore_rorec

Ignore_rorec is a logical value that controls whether the read-only recommended message is displayed.
file_origin

File_origin is a number specifying whether a text file originated on the Macintosh or in Windows. A zero value is treated as a missing argument.
custom_delimit

Custom_delimit is the character you want to use as a custom delimiter when opening text files.
editable

Editable is a logical valule that corresponds to opening a file (such as a template) while holding down SHIFT key.
file_access

File_access is a number specifying how the file is to be accessed. A zero value is treated as a missing argument.
notify_logical

Notify_logical is a logical value that specifies whether the user should be notified when the shared document is available to be opened across a network.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::OptionsCalculation

Controls when and how formulas in open workbooks are calculated

static int OptionsCalculation(
   short int type_num,
   bool iter = false,
   int max_num = 100,
   double max_change = 0.001,
   bool update = true,
   bool precision = false,
   bool date_1904 = false,
   bool calc_save = false,
   bool save_values = true
);

Parameters

type_num

Type_num is a number from 1 to 3 indicating the type of calculation:- 1=Automatic; 2=Automatic except tables; 3=Manual.
iter

Iter corresponds to the Iteration check box.
max_num

Max_num is the maximum number of iterations.
max_change

Max_change is the maximum change of each iteration.
update

Update corresponds to the Update Remote References check box.
precision

Precision corresponds to the Precision As Displayed check box.
date_1904

Date_1904 corresponds to the 1904 Date System check box.
calc_save

Calc_save corresponds to the Recalculate Before Save check box.
save_values

Save_values corresponds to the Save External Link Values check box.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Paste

Equivalent to choosing the Paste command from the Edit menu

static int Paste(
   const CXlOper& to_reference = CXlOper::MissingArg()
);

Parameters

to_reference

To_reference is a reference to the cell or range of cells where you want to paste what you have copied.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::PasteSpecial

Equivalent to choosing the Paste Special command from the Edit menu

static int PasteSpecial(
   unsigned short paste_num,
   unsigned short operation_num,
   bool skip_blanks,
   bool transpose
);

Parameters

paste_num

Paste_num is a number from 1 to 6 specifying what to paste.
operation_num

Operation_num is a number from 1 to 5 specifying which operation to perform when pasting.
skip_blanks

Skip_blanks is a logical value corresponding to the Skip Blanks check box in the Paste Special dialog box.
transpose

Transpose is a logical value corresponding to the Transpose check box in the Paste Special dialog box.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Patterns

Equivalent to filling in the Patterns dialog

static int Patterns(
   unsigned short apattern,
   unsigned short afore,
   unsigned short aback
);

Parameters

apattern

apattern is a number corresponding to the area patterns in the Patterns tab of the Format Cells or Format Object dialog box. If an object is selected, apattern can be from 1 to 18; if a cell is selected, apattern can be from 0 to 18. If apattern is 0 and a cell is selected, Microsoft Excel applies no pattern.

afore

afore is a number from 1 to 56 corresponding to the 56 area foreground colors in the Patterns tab of the Foramt Cells dialog box. afore is ignored if it is zero.

Note the foreground color has no effect if apattern is 1 (solid).
aback

aback is a number from 1 to 56 corresponding to the 56 area foreground colors in the Patterns tab of the Foramt Cells dialog box. Afore is ignored if it is zero.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Quit

Quits Microsoft Excel and closes any open documents

static int Quit( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::RefText

Converts a reference to an absolute reference in the form of text

static int RefText(
   CString& strreftext,
   const CXlOper& reference,
   bool a1 = false
);

Parameters

strreftext

A reference to a string that will contain the desired data if the function succeeds.
reference

Reference is the reference you want to convert.
a1

A1 is a logical value specifying A1-style or R1C1-style references.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::RelRef

Returns the reference of a cell or cells relative to the upper-left cell of rel_to_ref

static int RelRef(
   CXlOper& xloRef,
   const CXlOper& reference,
   const CXlOper& rel_to_ref
);

Parameters

xloRef

A reference to a CXlOper that will contain the desired data if the function succeeds.
reference

Reference is the cell or cells to which you want to create a relative reference.
rel_to_ref

Rel_to_ref is the cell from which you want to create the relative reference.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::RowHeight

Changes the height of the rows in a reference

static int RowHeight(
   double height_num,
   const CXlOper& reference = CXlOper::MissingArg(),
   bool standard = false,
   unsigned short type_num = 0
);

Parameters

height_num

Height_num specifies how high you want the rows to be in points.
reference

Reference specifies the rows for which you want to change the width.
standard

Standard is a logical value that sets the row height as determined by the font in each row.
type_num

Type_num is a number from 1 to 3 corresponding to the Hide, Unhide, or AutoFit Selection commands. Zero is treated as a missing argument.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Save

Saves the active document

static int Save( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::SaveAs

Equivalent to choosing the Save As command from the File menu

static int SaveAs(
   LPCTSTR document_text,
   short int type_num = 1,
   LPCTSTR prot_pwd = 0,
   short int backup = -1,
   LPCTSTR write_res_pwd = 0,
   short int read_only_rec = -1
);

Parameters

document_text

Document_text specifies the name of a workbook to save.
type_num

Type_num is a number specifying the file format in which to save the workbook.
prot_pwd

Prot_pwd is the password, as text, required to unprotect a protected file.
backup

Backup is a logical value corresponding to the Always Create Backup File check box in the Save Options dialog box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.
write_res_pwd

Write_res_pwd is the password, as text, required to open a read-only file with full write privileges.
read_only_rec

Read_only_rec is a logical value corresponding to the Read-Only Recommended check box in the Save Options dialog box. A value of -1 is treated as a missing argument, A value greater than 0 is treated as TRUE, and 0 is treated as FALSE.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::SaveCopyAs

Saves a copy of the current document using a different name but all the current document settings, such as passwords and file protection

static int SaveCopyAs(
   LPCTSTR document_text
);

Parameters

document_text

Document_text is the name you want to give the copy of the workbook.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Select

Equivalent to selecting cells or changing the active cell

static int Select(
   const CXlOper& selection,
   const CXlOper& active_cell = CXlOper::MissingArg()
);

Parameters

selection

Selection is the cell or range of cells you want to select.
active_cell

Active_cell is the cell in selection you want to make the active cell.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::SelectAll

Equivalent to selecting all the sheets in a workbook

static int SelectAll( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Selection

Returns the reference or object identifier of the selection as an external reference

static int Selection(
   CXlOper& xloRef
);

Parameters

xloRef

A reference to a CXlOper that will contain the active cell if the function succeeds.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::ShowActiveCell

Scrolls the active window so the active cell becomes visible

static int ShowActiveCell( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Split

Equivalent to choosing the Split command from the Window menu or to dragging the split bar in the active window's scroll bar.

static int Split(
   COL12 col_split,
   RW12 row_split
);

Parameters

col_split

specifies where to split the window vertically and is measured in columns from the left of the window.
row_split

specifies where to split the window horizontally and is measured in rows from the top of the window.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

If an argument is 0 and there is a split in that direction, the split is removed.

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods | CXlMacros::FreezePanes | CXlMacros::UnfreezePanes


CXlMacros::StandardWidth

Sets the default width used for all columns in a worksheet

static int StandardWidth(
   double standard_num
);

Parameters

standard_num

Standard_num specifies how wide you want the columns to be in units of one character of the font corresponding to the Normal cell style.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::SummaryInfo

Generates the summary information for the active workbook

static int SummaryInfo(
   LPCTSTR title,
   LPCTSTR subject,
   LPCTSTR author,
   LPCTSTR keywords,
   LPCTSTR comments
);

Parameters

title

Title specifies a title for the file, not necessarily a file name.
subject

Subject is information pertaining to the subject matter of the workbook
author

Author is initially the name specified in the General tab of the Options dialog box.
keywords

Keywords are keywords that can be later used in searching for the contents in the file.
comments

Comments is a comment that can be entered to help a user learn more about the contents or subject matter of the workbook.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::TextRef

Converts a reference to an absolute reference in the form of text

static int TextRef(
   CXlOper& strreftext,
   LPCTSTR  text,
   bool a1 = false
);

Parameters

strreftext

A reference to a CXlOper that will contain the desired data if the function succeeds.
text

Text is a reference in the form of text.
a1

A1 is a logical value specifying the reference type of text.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Undo

Equivalent to choosing the Undo command from the Edit menu

static int Undo( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::UnfreezePanes

Equivalent to choosing the Unfreeze Panes command from the Window menu or clicking the Unfreeze Panes button.

static int UnfreezePanes( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

Unfreezes existing panes.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods | CXlMacros::FreezePanes | CXlMacros::Split


CXlMacros::Unhide

Equivalent to choosing the Unhide command from the Window menu

static int Unhide(
   LPCTSTR window_text
);

Parameters

window_text

Window_text is the name of the window to unhide.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::VLine

Scrolls through the active window vertically by the number of rows you specify

static int VLine(
   long num_rows
);

Parameters

num_rows

Num_rows is a number that specifies how many rows to scroll.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::VPage

Vertically scrolls through the active window one window at a time

static int VPage(
   long num_windows
);

Parameters

num_windows

Num_windows specifies the number of windows to scroll through the active window vertically.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::VScroll

Vertically scrolls through the active sheet by percentage or by row number

static int VScroll(
   double position,
   bool row_logical = false
);

Parameters

position

Position specifies the row you want to scroll to.
row_logical

Row_logical is a logical value specifying how the function scrolls.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WindowMaximize

Changes the active window from its normal size to full size

static int WindowMaximize(
   LPCTSTR window_text = 0
);

Parameters

window_text

Window_text specifies which window to switch to and maximize.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WindowMinimize

Shrinks a window to an icon

static int WindowMinimize(
   LPCTSTR window_text = 0
);

Parameters

window_text

Window_text specifies which window to minimize.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WindowMove

Moves the active window so that its upper-left corner is at the specified horizontal and vertical positions

static int WindowMove(
   long x_pos,
   long y_pos,
   LPCTSTR window_text = 0
);

Parameters

x_pos

X_pos is the horizontal position to which you want to move the window.
y_pos

Y_pos is the vertical position to which you want to move the window.
window_text

Window_text specifies which window to switch to and restore.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WindowRestore

Changes the active window from maximized or minimized size to its previous size

static int WindowRestore(
   LPCTSTR window_text = 0
);

Parameters

window_text

Window_text specifies which window to switch to and restore.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Windows

Returns the names of the specified open Microsoft Excel windows

static int Windows(
   std::vector<CString>& windows,
   short int type_num = 1,
   LPCTSTR match_text = 0
);

Parameters

windows

A vector of strings which will be populated with the list of names.
type_num

Type_num is a number that specifies which types of workbooks are returned.
match_text

Match_text specifies the windows whose names you want returned and can include wildcard characters.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WindowSize

Changes the size of the active window by moving its lower-right corner so that the window has the width and height you specify

static int WindowSize(
   long x_num,
   long y_num,
   LPCTSTR window_text = 0
);

Parameters

x_num

specifies the width of the window and is measured in points.
y_num

specifies the height of the window and is measured in points.
window_text

Window_text specifies which window to switch to and restore.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookActivate

Equivalent to activating a worksheet by clicking on its tab

static int WorkbookActivate(
   const TCHAR* sheet_name
);

Parameters

sheet_name

Sheet_name is the name of the document you want to activate within the active workbook.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookActivateA

Equivalent to activating a worksheet by clicking on its tab

static int WorkbookActivateA(
   const char* sheet_name
);

Parameters

sheet_name

Sheet_name is the name of the document you want to activate within the active workbook.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookActivateW

Equivalent to activating a worksheet by clicking on its tab

static int WorkbookActivateW(
   const wchar_t* sheet_name
);

Parameters

sheet_name

Sheet_name is the name of the document you want to activate within the active workbook.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookCopy

Copies a worksheet from the current workbook to another workbook or to a new position in the current workbook

static int WorkbookCopy(
   LPCTSTR sheet_name,
   LPCTSTR dest_book,
   int position_num
);

Parameters

sheet_name

Sheet_name is the name of the sheet to copy.
dest_book

Dest_book is the name of the book to which the sheet will be copied. If it is NULL or empty, then a new book will be created. If it is the same as the active book (use CXlMacros::GetActiveWorkbookName to get the name of the active book), then the sheet will be copied to a new position within the active book.
position_num

Position_num is a number that specifies the target position for the sheet within dest_book. The first position is 1. You can use CXlMacros::WorkbookGetWorksheetCount to get the number of sheets in the current book.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookDelete

Deletes a sheet or group of sheets from the current workbook

static int WorkbookDelete(
   LPCTSTR sheet_text
);

Parameters

sheet_text

Sheet_text is the name of the sheet to delete. If omitted, the currently active sheet or sheets is deleted.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookGetWorksheetNames

Returns a list of all the sheets in a workbook

static int WorkbookGetWorksheetNames(
   std::vector<CString>& vecSheetNames,
   LPCTSTR name_text = 0,
   bool complete_names = false
);
static int WorkbookGetWorksheetNames(
   std::vector<CStringA>& vecSheetNamesA,
   LPCSTR name_text_a = 0,
   bool complete_names = false
);
static int WorkbookGetWorksheetNames(
   std::vector<CStringW>& vecSheetNamesW,
   LPCWSTR name_text_w = 0,
   bool complete_names = false
);

Parameters

vecSheetNames

A reference to a collection of strings that will be cleared and populated with sheet names if the function succeeds.
name_text

Name_text is the name of an open workbook. If omitted, the active workbook is used.
complete_names

Complete_names is a boolean value that controls whether the returned names will be in complete form (i.e. book[sheet]), or in short form (sheet). If omitted, the short form will be used.
vecSheetNamesA

A reference to a collection of ANSI strings that will be cleared and populated with sheet names if the function succeeds.
name_text_a

Name_text_a is the name of an open workbook. If omitted, the active workbook is used.
vecSheetNamesW

A reference to a collection of ANSI strings that will be cleared and populated with sheet names if the function succeeds.
name_text_w

Name_text_w is the name of an open workbook. If omitted, the active workbook is used.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

This a helper function that calls GET.WORKBOOK(2) and extracts the resulting array into a vector of strings. around See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookHide

Hides sheets in the active workbook

static int WorkbookHide(
   LPCTSTR sheet_text,
   bool very_hidden = false
);

Parameters

sheet_text

Sheet_text is the name of the sheet to hide.
very_hidden

Very_hidden specifies how the sheet is hidden.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookInsert

Inserts one or more new sheets into the current workbook

static int WorkbookInsert(
   unsigned short type_num = 0
);

Parameters

type_num

Type_num specifies the type of sheet to insert. A zero value is treated as a missing argument. 1 indicates a standard worksheet.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookMove

Moves a worksheet from the current workbook to another workbook or to a new position in the current workbook

static int WorkbookMove(
   LPCTSTR sheet_name,
   LPCTSTR dest_book,
   int position_num
);

Parameters

sheet_name

Sheet_name is the name of the sheet to move.
dest_book

Dest_book is the name of the book to which the sheet will be moved. If it is NULL or empty, then a new book will be created. If it is the same as the active book (use CXlMacros::GetActiveWorkbookName to get the name of the active book), then the sheet will be moved to a new position within the active book.
position_num

Position_num is a number that specifies the target position for the sheet within dest_book. The first position is 1. You can use CXlMacros::WorkbookGetWorksheetCount to get the number of sheets in the current book.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookName

Renames a sheet in a workbook

static int WorkbookName(
   LPCTSTR oldname_text,
   LPCTSTR newname_text
);

Parameters

oldname_text

Oldname_text is the name of the sheet that you want to rename.
newname_text

Newname_text is the new name of the sheet.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookNext

Activates the next sheet in the active workbook

static int WorkbookNext( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookPrev

Activates the previous sheet in the active workbook

static int WorkbookPrev( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookProtect

Renames a sheet in a workbook

static int WorkbookProtect(
   bool structure = false,
   bool windows = false,
   LPCTSTR password = 0
);

Parameters

structure

Structure specifies whether the structure of the workbook is protected.
windows

Windows specifes whether the windows of the workbook are protected.
password

Password specifies whether to protect the workbook with a password.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::WorkbookUnhide

Unhides sheets in the active workbook

static int WorkbookUnhide(
   LPCTSTR sheet_text = 0
);

Parameters

sheet_text

Sheet_text is the name of the sheet to unhide.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::Zoom

Enlarges or reduces a document in the active window

static int Zoom(
   double magnification
);

Parameters

magnification

Magnification can be a number from 10 to 400 specifying the percentage of enlargement or reduction.

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::ZoomMax

The current selection is enlarged or reduced to completely fill the active window

static int ZoomMax( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

This method is the equivalent of calling =ZOOM(TRUE).

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


CXlMacros::ZoomNormal

The document is restored to normal 100% magnification

static int ZoomNormal( );

Return Value

Zero if the function has been called successfully; non-zero if the function could not be called. See Error codes for a list of return values.

Remarks

This method is the equivalent of calling =ZOOM(FALSE).

Remarks

See the Microsoft Excel on-line Help for full details about this function.

Requirements

Header: xlfuncs.h

See Also

CXlMacros Class | CXlMacros Methods


xlldate.h

Overview

xlldate.h contains some global functions that access Excel's native date functionality and a class CXlDate which offers the same functionality in a more convenient form.

Classes

The table below lists the C++ object classes declared in the header file.

Class | Description
CXlDate | Static class containing date helper functions.

Functions

The table below lists the principal functions declared in the header file.

Function | Description
XlSerialToDate | Transform an Excel serial date to year, month and day.
XlDateToSerial | Transform year, month and day to an Excel serial date.
XlLSerialToDate | Transform an integer Excel serial date to year, month and day.
XlDateToLSerial | Transform year, month and day to an Excel serial date.
XlStringToDate | Transform a string to year, month and day.
XlStringToSerial | Transform a string to a serial date.
XlStringToLSerial | Transform a string to a serial date.
XlToday | Get today's date.
XlNow | Get the current time.
XlWeekday | Convert a date to a day of the week.

A full list can be found here.


CXlDate Class

Supports calls to Excel worksheet functions.

class CXlDate

Overview

The CXlDate class contains only static methods. Each of these methods calls one or more built-in Excel date functions.

Any of these functions may normally be called from worksheet functions.

Exceptions

Many methods throw an exception of type CXlApiException if the call to the Excel API fails. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when these methods are called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Methods | xlldate.h | CXlMacros object | CXllApp::Excel | CXlOper::Excel


CXlDate Methods

The methods of the CXlDate class are listed here.

Date

DateToLSerial | Transform year, month and day to an Excel serial date
DateToSerial | Transform year, month and day to an Excel serial date
LSerialToDate | Transform an integer Excel serial date to year, month and day
Now | Get the current time
SerialToDate | Transform an Excel serial date to year, month and day
StringToDate | Transform a string to year, month and day
StringToDateA | Transform a string to year, month and day
StringToDateW | Transform a string to year, month and day
StringToLSerial | Transform a string to a serial date
StringToLSerialA | Transform a string to a serial date
StringToLSerialW | Transform a string to a serial date
StringToSerial | Transform a string to a serial date
StringToSerialA | Transform a string to a serial date
StringToSerialW | Transform a string to a serial date
Today | Get today's date
XlWeekday | Convert a date to a day of the week

Construction

public method CXlDate Constructs a CXlDate object

Requirements

Header: xlldate.h

See Also

CXlDate Class | xlldate.h | CXlMacros object | CXllApp::Excel | CXlOper::Excel


CXlDate::CXlDate

Constructs a CXlDate object

CXlDate( );

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::DateToLSerial

Transform year, month and day to an Excel serial date

static long DateToLSerial(
   int yy,
   int mm,
   int dd
);

Parameters

yy

Year (eg 1996).
mm

Month (1-12).
dd

Day of month (1-31).

Return Value

An Excel integer serial date value

Remarks

This function calls Excel's DATE() function to calculate a serial date from its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::DateToSerial

Transform year, month and day to an Excel serial date

static double DateToSerial(
   int yy,
   int mm,
   int dd
);

Parameters

yy

Year (eg 1996).
mm

Month (1-12).
dd

Day of month (1-31).

Return Value

An Excel serial date value.

Remarks

This function calls Excel's DATE() function to calculate a serial date from its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::LSerialToDate

Transform an integer Excel serial date to year, month and day

static void LSerialToDate(
   long date,
   int& yy,
   int& mm,
   int& dd
);

Parameters

date

An integer serial date value.
yy

Reference to variable which will contain year (eg 1996).
mm

Reference to variable which will contain month (1-12).
dd

Reference to variable which will contain day of month (1-31).

Remarks

This function calls Excel's YEAR(), MONTH() and DAY() functions to transform a serial date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::Now

Get the current time

static double Now( );

Return Value

Excel serial date/time value.

Remarks

This function calls Excel's NOW() function.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::SerialToDate

Transform an Excel serial date to year, month and day

static void SerialToDate(
   double date,
   int& yy,
   int& mm,
   int& dd
);

Parameters

date

A serial date value as used by Excel.
yy

Reference to variable which will contain year (eg 1996).
mm

Reference to variable which will contain month (1-12).
dd

Reference to variable which will contain day of month (1-31).

Remarks

This function calls Excel's YEAR(), MONTH() and DAY() functions to transform a serial date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::StringToDate

Transform a string to year, month and day

static void StringToDate(
   const TCHAR* str,
   int& yy,
   int& mm,
   int& dd
);

Parameters

str

A string containing a date. Excel will use the date formatting rules currently in force to read the string.

yy

Reference to variable which will contain year (eg 1996).
mm

Reference to variable which will contain month (1-12).
dd

Reference to variable which will contain day of month (1-31).

Remarks

This function calls Excel's DATEVALUE(), YEAR(), MONTH() and DAY() functions to transform a string date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::StringToDateA

Transform a string to year, month and day

static void StringToDateA(
   const char* str,
   int& yy,
   int& mm,
   int& dd
);

Parameters

str

A string containing a date. Excel will use the date formatting rules currently in force to read the string.

yy

Reference to variable which will contain year (eg 1996).
mm

Reference to variable which will contain month (1-12).
dd

Reference to variable which will contain day of month (1-31).

Remarks

This function calls Excel's DATEVALUE(), YEAR(), MONTH() and DAY() functions to transform a string date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::StringToDateW

Transform a string to year, month and day

static void StringToDateW(
   const wchar_t* str,
   int& yy,
   int& mm,
   int& dd
);

Parameters

str

A string containing a date. Excel will use the date formatting rules currently in force to read the string.

yy

Reference to variable which will contain year (eg 1996).
mm

Reference to variable which will contain month (1-12).
dd

Reference to variable which will contain day of month (1-31).

Remarks

This function calls Excel's DATEVALUE(), YEAR(), MONTH() and DAY() functions to transform a string date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::StringToLSerial

Transform a string to a serial date

static long StringToLSerial(
   const TCHAR* str
);

Parameters

str

A string containing a date. Excel will use the date formatting rules currently in force to read the string.

Return Value

An Excel integer serial date value.

Remarks

This function calls Excel's DATEVALUE() function to transform a string date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::StringToLSerialA

Transform a string to a serial date

static long StringToLSerialA(
   const char* str
);

Parameters

str

A string containing a date. Excel will use the date formatting rules currently in force to read the string.

Return Value

An Excel integer serial date value.

Remarks

This function calls Excel's DATEVALUE() function to transform a string date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::StringToLSerialW

Transform a string to a serial date

static long StringToLSerialW(
   const wchar_t* str
);

Parameters

str

A string containing a date. Excel will use the date formatting rules currently in force to read the string.

Return Value

An Excel integer serial date value.

Remarks

This function calls Excel's DATEVALUE() function to transform a string date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::StringToSerial

Transform a string to a serial date

static double StringToSerial(
   const TCHAR* str
);

Parameters

str

A string containing a date. Excel will use the date formatting rules currently in force to read the string.

Return Value

An Excel serial date value.

Remarks

This function calls Excel's DATEVALUE() function to transform a string date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::StringToSerialA

Transform a string to a serial date

static double StringToSerialA(
   const char* str
);

Parameters

str

A string containing a date. Excel will use the date formatting rules currently in force to read the string.

Return Value

An Excel serial date value.

Remarks

This function calls Excel's DATEVALUE() function to transform a string date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::StringToSerialW

Transform a string to a serial date

static double StringToSerialW(
   const wchar_t* str
);

Parameters

str

A string containing a date. Excel will use the date formatting rules currently in force to read the string.

Return Value

An Excel serial date value.

Remarks

This function calls Excel's DATEVALUE() function to transform a string date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::Today

Get today's date

static long Today( );

Return Value

A serial date value (as used by Excel)

Remarks

This function calls Excel's TODAY() function.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


CXlDate::XlWeekday

Convert a date to a day of the week

static int XlWeekday(
   long date
);

Parameters

date

An integer serial date value.

Return Value

An integer between 1 (Monday) and 7 (Sunday).

Remarks

This function calls Excel's WEEKDAY() function with 2 as its second argument.

Exceptions

If a call to the Excel API fails, then an exception of type CXlApiException will be thrown. Since this exception is derived from CXlRuntimeException, it will be caught by the add-in wrapper function when this method is called from within an add-in function.

Requirements

Header: xlldate.h

See Also

CXlDate Class | CXlDate Methods


Global date functions

Global date functions are listed here.

Date

public method | XlDateToLSerial | Transform year, month and day to an Excel serial date
public method | XlDateToSerial | Transform year, month and day to an Excel serial date
public method | XlLSerialToDate | Transform an integer Excel serial date to year, month and day
public method | XlNow | Get the current time
public method | XlSerialToDate | Transform an Excel serial date to year, month and day
public method | XlStringToDate | Transform a string to year, month and day
public method | XlStringToLSerial | Transform a string to a serial date
public method | XlStringToSerial | Transform a string to a serial date
public method | XlToday | Get today's date
public method | XlWeekday | Convert a date to a day of the week

Requirements

Header: xlldate.h

See Also

xlldate.h


::XlDateToLSerial

Transform year, month and day to an Excel serial date

int XlDateToLSerial(
   long* date,
   int yy,
   int mm,
   int dd
);

Parameters

date

Pointer to a variable which will be filled with an integer serial date value.
yy

Year (eg 1996).
mm

Month (1-12).
dd

Day of month (1-31).

Return Value

1 if the function succeeds; 0 if it fails

Remarks

This function calls Excel's DATE() function to calculate a serial date from its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Requirements

Header: xlldate.h

See Also

Global date functions


::XlDateToSerial

Transform year, month and day to an Excel serial date

int XlDateToSerial(
   double* date,
   int yy,
   int mm,
   int dd
);

Parameters

date

Pointer to a variable which will be filled with a serial date value (as used by Excel).
yy

Year (eg 1996).
mm

Month (1-12).
dd

Day of month (1-31).

Return Value

1 if the function succeeds; 0 if it fails

Remarks

This function calls Excel's DATE() function to calculate a serial date from its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Requirements

Header: xlldate.h

See Also

Global date functions


::XlLSerialToDate

Transform an integer Excel serial date to year, month and day

int XlLSerialToDate(
   long date,
   int* yy,
   int* mm,
   int* dd
);

Parameters

date

An integer serial date value.
yy

Pointer to variable which will contain year (eg 1996).
mm

Pointer to variable which will contain month (1-12).
dd

Pointer to variable which will contain day of month (1-31).

Return Value

1 if the function succeeds; 0 if it fails

Remarks

This function calls Excel's YEAR(), MONTH() and DAY() functions to transform a serial date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Requirements

Header: xlldate.h

See Also

Global date functions


::XlNow

Get the current time

int XlNow(
   double* t
);

Parameters

t

Pointer to a variable which will be filled with a serial date/time value (as used by Excel).

Return Value

1 if the function succeeds; 0 if it fails

Remarks

This function calls Excel's NOW() function.

Requirements

Header: xlldate.h

See Also

Global date functions


::XlSerialToDate

Transform an Excel serial date to year, month and day

int XlSerialToDate(
   double date,
   int* yy,
   int* mm,
   int* dd
);

Parameters

date

A serial date value as used by Excel.
yy

Pointer to variable which will contain year (eg 1996).
mm

Pointer to variable which will contain month (1-12).
dd

Pointer to variable which will contain day of month (1-31).

Return Value

1 if the function succeeds; 0 if it fails

Remarks

This function calls Excel's YEAR(), MONTH() and DAY() functions to transform a serial date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Requirements

Header: xlldate.h

See Also

Global date functions


::XlStringToDate

Transform a string to year, month and day

int XlStringToDate(
   const char* str,
   int* yy,
   int* mm,
   int* dd
);
int XlStringToDate(
   const wchar_t* str,
   int* yy,
   int* mm,
   int* dd
);

Parameters

str

A string containing a date. Excel will use the date formatting rules currently in force to read the string.
yy

Pointer to variable which will contain year (eg 1996).
mm

Pointer to variable which will contain month (1-12).
dd

Pointer to variable which will contain day of month (1-31).

Return Value

1 if the function succeeds; 0 if it fails

Remarks

This function calls Excel's DATEVALUE(), YEAR(), MONTH() and DAY() functions to transform a string date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Requirements

Header: xlldate.h

See Also

Global date functions


::XlStringToLSerial

Transform a string to a serial date

int XlStringToLSerial(
   const char* str,
   long* date
);
int XlStringToLSerial(
   const wchar_t* str,
   long* date
);

Parameters

str

A string containing a date. Excel will use the date formatting rules currently in force to read the string.
date

Pointer to a variable which will be filled with a serial date value (as used by Excel).

Return Value

1 if the function succeeds; 0 if it fails

Remarks

This function calls Excel's DATEVALUE() function to transform a string date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Requirements

Header: xlldate.h

See Also

Global date functions


::XlStringToSerial

Transform a string to a serial date

int XlStringToSerial(
   const char* str,
   double* date
);
int XlStringToSerial(
   const wchar_t* str,
   double* date
);

Parameters

str

A string containing a date. Excel will use the date formatting rules currently in force to read the string.
date

Pointer to a variable which will be filled with a serial date value (as used by Excel).

Return Value

1 if the function succeeds; 0 if it fails

Remarks

This function calls Excel's DATEVALUE() function to transform a string date into its components.

Because it uses Excel for the transformation, it handles variations in the Excel base date transparently.

Requirements

Header: xlldate.h

See Also

Global date functions


::XlToday

Get today's date

int XlToday(
   long* date
);

Parameters

date

Pointer to a variable which will be filled with a serial date value (as used by Excel).

Return Value

1 if the function succeeds; 0 if it fails

Remarks

This function calls Excel's TODAY() function.

Requirements

Header: xlldate.h

See Also

Global date functions


::XlWeekday

Convert a date to a day of the week

int XlWeekday(
   long date,
   int* day
);

Parameters

date

An integer serial date value.
day

Pointer to a variable which will be filled with an integer between 1 (Monday) and 7 (Sunday).

Return Value

1 if the function succeeds; 0 if it fails

Remarks

This function calls Excel's WEEKDAY() function with 2 as its second argument.

Requirements

Header: xlldate.h

See Also

Global date functions


matrix.h

Overview

matrix.h contains a matrix<T> class for storing and manipulating two-dimensional arrays of data.

Status

This class is now deprecated, and has been replaced by the more powerful classes descended from imtx<T>.

It is included for the benefit of code written with earlier versions (4.1 and below) of XLL+.

See Also

matrix<T> class


matrix<T> Class

Container for two-dimensional arrays of type T (deprecated).

class matrix<T>

Status

This class is now deprecated, and has been replaced by the more powerful classes descended from imtx<T>.

It is included for the benefit of code written with earlier versions (4.1 and below) of XLL+.

Overview

The matrix template is a container for two-dimensional arrays of type T. You can use them to read in arrays of numbers or strings from Excel OPER and XLOPER arguments passed to your add-in functions.

As well as saving programming time, the class offers three advantages over writing your own code to read array inputs:

  • Safety
    The class has methods to check for valid inputs while reading in arrays.
  • Memory management
    The import methods automatically allocate sufficient memory to contain the input. The destructor automatically frees it, reducing the risk of memory leaks.
  • Efficiency
    The class methods and supporting functions are written close to the 'C' structures

    • The class also contains methods and operators that make it convenient to pass values to functions expecting arrays of type T. See the Tutorial for further examples of using matrix<T>.

    Alignment

    Data is always stored with columns together. The table below show the offsets of the items in a 3 row x 4 column array.

     |  | Columns
 |  | 0 | 1 | 2 | 3
Rows | 0 | Offset = 0 | Offset = 3 | Offset = 6 | Offset = 9
 | Offset = 1 | Offset = 1 | Offset = 4 | Offset = 7 | Offset = 10
 | Offset = 2 | Offset = 2 | Offset = 5 | Offset = 8 | Offset = 11

    Programming note

    You will notice that the naming conventions of matrix<T> differ from other XLL+ objects: the class is named after the conventions of the STL collection templates, and is expected to be used in conjunction with vector<T>.

    Requirements

    Header: matrix.h

    See Also

    matrix<T> Methods | matrix.h | imtx<T>


matrix<T> Methods

The methods of the matrix<T> class are listed here.

Construction

public method | matrix<T> | Constructs a new matrix
public method | operator= | Assignment operator

Operations

public method | add_col | Add a single column to the matrix and populate it
public method | add_row | Add a single row to the matrix and populate it
public method | clear | Empty the matrix
public method | resize | Resize the matrix, optionally preserving existing values
public method | transpose | Transpose the matrix along its major diagonal

Attributes

public method | cols | Returns the number of columns
public method | rows | Returns the number of rows

Access

public method | at | Returns a reference to an item in the matrix
public method | col | Returns a copy of a complete column
public method | col_ptr | Returns a pointer to the data in a column
public method | find_in_col | Searches one column for a value
public method | find_in_row | Searches one row for a value
public method | get_col_ptrs | Populates a vector of column pointers
public method | row | Returns a copy of a complete row

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix.h | imtx<T>


vector<T> and matrix<T> Flags

The flags described in the table below manage the conversion and truncation of input arrays.

Flag | Meaning
XLA_TRUNC_NONE | Do not truncate.
XLA_TRUNC_ONZERO | Truncate array just before cell if cell contains zero.
XLA_TRUNC_ONEMPTY | Truncate array just before cell if cell is empty
XLA_TRUNC_ONNONNUMERIC | Truncate array just before cell if cell is not numeric
XLA_TRUNC_ONBLANK | Truncate array just before cell if cell is blank
XLA_TRUNC_STD | Standard flags: XLA_TRUNC_ONEMPTY
XLA_TRUNC_COL_FIRST | In a matrix, truncate the column, rather than the row.
XLA_DEFAULT_NONE | Do not use default value.
XLA_DEFAULT_ZERO | Use default value if cell contains zero.
XLA_DEFAULT_EMPTY | Use default value if cell is empty.
XLA_DEFAULT_NONNUMERIC | Use default value if cell is not numeric.
XLA_DEFAULT_BLANK | Use default value if cell is blank.
XLA_DEFAULT_STD | Standard flags: 0
XLA_FLAG_TRANSPOSE | Transpose rows and columns.
XLA_FLAG_ARRAYONLY | Reject single cells.
XLA_FLAG_REJECT_NULL_ARRAY | Reject empty arrays (i.e. those with zero rows or columns.
XLA_FLAG_CONVERT_BOOLEAN | Convert Boolean values to strings or numbers as required
XLA_FLAG_CONVERT_NUMERIC | Convert numbers to strings as required
XLA_FLAG_CONVERT_ERROR | Convert errors values to strings or numbers as required
XLA_BOUND_UBOUND_INNER | Treat upper bound values as size - 1 (following Visual Basic conventions)
XLA_BOUND_UBOUND_OUTER | Treat upper bound values as size (following C/C++ conventions)
XLA_BOUND_UBOUND_AUTO | If lower bound is non-zero, then treat upper bound values as size - 1 (following Visual Basic conventions). If lower bound is zero, then treat upper bound values as size (following C/C++ conventions)

These flags are used in the following functions:

Function | Purpose
COper::ReadVector | Reads a vector from an array into a vector of numbers or strings
COper::ReadMatrix | Reads an array argument into a two-dimensional matrix of numbers or strings
COper::ColToVector | Reads a column from an array into a vector of numbers or strings
COper::RowToVector | Reads a row from an array into a vector of numbers or strings
COper::ToMatrix | Reads an array argument into a two-dimensional matrix of numbers or strings
CXlArray::ReadVector | Reads a vector from an array into a vector of numbers or strings
CXlArray::ReadMatrix | Reads an array argument into a two-dimensional matrix of numbers or strings

See Bounded input arrays for more information on the use of upper bounds.

See Also

Bounded input arrays


matrix<T>::add_col

Add a single column to the matrix and populate it

void add_col(
   const T* pt
);

Parameters

pt

Pointer to an array of type T, with at least rows() members.

Remarks

This function adds one new column to the matrix, and fills it with the values provided.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::add_row

Add a single row to the matrix and populate it

void add_row(
   const T* pt
);

Parameters

pt

Pointer to an array of type T, with at least cols() members.

Remarks

This function adds one new row to the matrix, and fills it with the values provided.

Example

matrix<T>::add_row() Example

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::at

Returns a reference to an item in the matrix

T& at(
   size_t row,
   size_t col
);

Parameters

row

Row coordinate.
col

Column coordinate.

Return Value

This function returns a reference to an item in the matrix.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::clear

Empty the matrix

void clear( );

Remarks

This function clears the contents of the matrix and sets its width and height to 0.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::col

Returns a copy of a complete column

std::vector<T> col(
   size_t col
) const;

Parameters

col

Column coordinate.

Return Value

This function copies an entire column of items from the matrix to the returned vector.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::col_ptr

Returns a pointer to the data in a column

T* col_ptr(
   size_t col
);
const T* col_ptr(
   size_t col
) const;

Parameters

col

Column coordinate.
col

Column coordinate.

Return Value

A pointer to the column is returned.

Remarks

Since columns are stored together, this function is cheap and feasible. Conversely, there is no row_ptr() method.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::cols

Returns the number of columns

size_t cols( ) const;

Return Value

This function returns the number of columns in the matrix.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::find_in_col

Searches one column for a value

size_t find_in_col(
   const T& t,
   size_t col
) const;

Parameters

t

Value to be matched.
col

Column coordinate.

Return Value

The row of the first cell in the column that contains a matching value. matrix<T>::npos is returned if no match is found.

Remarks

The specified column of the matrix is searched, top to bottom, until

at(row, col) == t
at which point row is returned.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::find_in_row

Searches one row for a value

size_t find_in_row(
   const T& t,
   size_t row
) const;

Parameters

t

Value to be matched.
row

Row coordinate.

Return Value

The column of the first cell in the row that contains a matching value. matrix<T>::npos is returned if no match is found.

Remarks

The specified row of the matrix is searched, left to right, until

at(row, col) == t
at which point col is returned.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::get_col_ptrs

Populates a vector of column pointers

void get_col_ptrs(
   std::vector<T*>& vecPtrs
);

Parameters

vecPtrs

Array of pointers, which will be filled with pointers to each column in the matrix.

Remarks

Data is stored within the matrix with columns together. This function fills vecPtrs with pointers to each column in the matrix. Any data previously in vecPtrs is discarded.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::matrix<T>

Constructs a new matrix

matrix<T>( );
matrix<T>(
   const matrix<T>& t
);
matrix<T>(
   size_t rows,
   size_t cols,
   const T& def = T()
);

Parameters

t

matrix object whose contents will be copied into this matrix.
rows

Number of rows after construction.
cols

Number of columns after construction.
def

Value of all new members.

Remarks

These are a standard constructor and a standard copy constructor.

The third constructor, allows you to set the size of the matrix. The matrix will initially be populated with the value of argument def, which defaults to 0, 0.0, false or "".

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods |


matrix<T>::operator=

Assignment operator

const COper& operator=(
   const matrix<T>& t
);

Parameters

t

matrix object whose size and contents will be copied over this matrix.

Remarks

These are a standard constructor and a standard copy constructor.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::resize

Resize the matrix, optionally preserving existing values

void resize(
   size_t rows,
   size_t cols,
   bool preserve,
   const T& def = T()
);

Parameters

rows

The new number of rows, which may be zero.
cols

The new number of columns, which may be zero.
preserve

Preserve existing values, in their current locations, if this is true. Otherwise set all values to default.
def

Default value used for new or cleared cells.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::row

Returns a copy of a complete row

std::vector<T> row(
   size_t row
) const;

Parameters

row

Row coordinate.

Return Value

This function copies an entire row of items from the matrix to the returned vector.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::rows

Returns the number of rows

size_t rows( ) const;

Return Value

This function returns the number of rows in the matrix.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


matrix<T>::transpose

Transpose the matrix along its major diagonal

void transpose( );

Remarks

This function transposes the matrix, such that:

new_array.at(i, j) = old_array.at(j, i)
Thus the number of rows and of columns will also be swapped.

Requirements

Header: matrix.h

See Also

matrix<T> Class | matrix<T> Methods


xlppush.h

Status

The classes in this file are now deprecated, and have been replaced by a mixed push/pull model implemented in VBA.

It is included for the benefit of code written with earlier versions (4.2.5 and below) of XLL+.

Overview

xlppush.h contains classes and definitions for updating Excel spreadsheets asynchronously, using a 'push' model.

For more information about the push model, see Multi-threaded add-ins in the User Guide.

Most of the functionality of the model is available via the CXllPushApp class, from which your application class should be descended.

See Also

CXllPushApp class


CXllMtMsg Class

class CXllMtMsg

Status

This class is now deprecated, and has been replaced by a mixed push/pull model implemented in VBA.

It is included for the benefit of code written with earlier versions (4.2.5 and below) of XLL+.

Overview

The CXllMtMsg class is an empty class, designed for use with the multi-threaded add-ins.

Data that is passed between threads in a push application should be contained in CXllMtMsg objects. Each implementation class should define a class descended from CXllMtMsg and enbed all the required data within it.

For more information, see Create a new class descended from CXllMtMsg in the User Guide.

Requirements

Header: xlppush.h

See Also

CXllMtMsg Methods | xlppush.h


CXllMtMsg Methods

The methods of the CXllMtMsg class are listed here.

Construction etc

public method | ~CXllMtMsg | Destroys a CXllMtMsg object
public method | CXllMtMsg | Constructs a CXllMtMsg object

Requirements

Header: xlppush.h

See Also

CXllMtMsg Class | xlppush.h


CXllMtMsg::~CXllMtMsg

Destroys a CXllMtMsg object

virtual ~CXllMtMsg( );

Remarks

Classes descended from CXllMtMsg should have a virtual destructor. This allows the framework to clean up any messages that are left on the queue when the application is closed.

Requirements

Header: xlppush.h

See Also

CXllMtMsg Class | CXllMtMsg Methods


CXllMtMsg::CXllMtMsg

Constructs a CXllMtMsg object

CXllMtMsg( );

Requirements

Header: xlppush.h

See Also

CXllMtMsg Class | CXllMtMsg Methods


CXllPushApp Class

class CXllPushApp

Status

This class is now deprecated, and has been replaced by a mixed push/pull model implemented in VBA.

It is included for the benefit of code written with earlier versions (4.2.5 and below) of XLL+.

Overview

The CXllPushApp class is a specialised sub-class of CXllApp. It provides all of the infrastructure for a multi-threaded add-in which can asynchronously update formula cells. Typical uses of this functionality are:

  • Data feed
  • Very slow calculations performed in a background thread
  • Monitoring a background task

A class that is descended from CXllPushApp must implement the virtual function ProcessAsyncMessage().

CXllPushApp messages and threads

Data that is passed between threads in a push application should be contained in CXllMtMsg objects. Each implementation class should define a class descended from CXllMtMsg and enbed all the required data within it.

For more information, see Create a new class descended from CXllMtMsg in the User Guide.

Implementing CXllPushApp

A class descended from CXllPushApp() must implement at least the following:

  1. A data cache, for all external data used by asynchronous add-in functions.
  2. The virtual function ProcessAsyncMessage().
  3. The virtual function OnXllOpenEx().

For more information, see Steps to create an asynchronous add-in in the User Guide.

Requirements

Header: xlppush.h

See Also

CXllPushApp Methods | xlppush.h


CXllPushApp Methods

The methods of the CXllPushApp class are listed here.

Construction

public method CXllPushApp Constructs a CXllPushApp object

Operations

public method | AddConnection | Register a connection between a cell range and the data it uses
public method | AddFunction | Add a name to the list of asynchronous functions which can be pushed by this cache
public method | UpdateCells | Update all cells connected to the topic

Properties

public method | GetFormatChangedCells | Returns whether formatting behaviour for changed cells is switched on
public method | GetRefreshPeriod | Returns the time in milliseconds between calls to RefreshFromApplication()
public method | GetTickPeriod | Returns the time in milliseconds between ticks for idle tasks
public method | SetFormatChangedCells | Sets whether formatting behaviour for changed cells is switched on
public method | SetRefreshPeriod | Sets the time in milliseconds between calls to RefreshFromApplication()
public method | SetTickPeriod | Sets the time between ticks for idle tasks

Methods available from any thread

public method PostMessage Posts a message to the main thread's message queue

Overridables

public method | OnCellUpdate | Called in main thread whenever a connected cell range is updated
public method | OnTopicAdd | Called in main thread whenever a new topic is added to the list of connections
public method | OnTopicRemove | Called in main thread whenever the last connection to a topic is removed from the list of connections
public method | OnXllClose | Called during application termination
public method | OnXllOpenEx | Called during application initialization
public method | ProcessAsyncMessage | Called in main thread whenever a message is received from another thread

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | xlppush.h


CXllPushApp::AddConnection

Register a connection between a cell range and the data it uses

int AddConnection(
   LPCSTR pszTopic
);

Parameters

pszTopic

The topic string. Whenever this topic string is passed to the method UpdateCells this cell will be updated (as will any other cell connected to the topic).

Return Value

The function returns a member of the enumeration CXllPush::AddConnectionReturnValues. A negative value indicates an error.

Remarks

This function may only be called from the main thread. It is generally only called from add-in functions.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::AddFunction() | Steps to create an asynchronous add-in


CXllPushApp::AddFunction

Add a name to the list of asynchronous functions which can be pushed by this cache

void AddFunction(
   LPCSTR pszFnName
);

Parameters

pszFnName

The registered name of the function to be pushed, as it will appear in Excel.

Remarks

This function may only be called from the main thread. It is generally only called during OnXllOpenEx().

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::AddConnection() | Steps to create an asynchronous add-in


CXllPushApp::CXllPushApp

Constructs a CXllPushApp object

CXllPushApp(
   const char* lpszAppName = NULL
);

Parameters

lpszAppName

A null-terminated string that contains the application name that Windows uses. If this argument is not supplied or is NULL, CWinApp uses the resource string AFX_IDS_APP_TITLE or the filename of the executable file.

Remarks

Constructs a CXllPushApp object and passes lpszAppName to be stored as the application name. You should construct one global object of your CXllApp-derived class. You can have only one CXllPushApp object in your application. The constructor stores a pointer to the CXllApp object so that WinMain can call the object's member functions to initialize and run the application.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods


CXllPushApp::GetFormatChangedCells

Returns whether formatting behaviour for changed cells is switched on

BOOL GetFormatChangedCells( );

Return Value

The function returns the value of the switch that determines whether updated cells are formatted by the push engine.

Remarks

This function may only be called from the main thread.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::SetFormatChangedCells() | CXllPushApp::OnCellUpdate()


CXllPushApp::GetRefreshPeriod

Returns the time in milliseconds between calls to RefreshFromApplication()

long GetRefreshPeriod( );

Return Value

The function returns the time in milliseconds between calls to RefreshFromApplication(). See CXllPushApp::SetRefreshPeriod() for more details.

Remarks

This function may only be called from the main thread.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::SetRefreshPeriod() | CXllPushApp::SetTickPeriod() | CXllPushApp::GetTickPeriod()


CXllPushApp::GetTickPeriod

Returns the time in milliseconds between ticks for idle tasks

long GetTickPeriod( );

Return Value

The function returns the time in milliseconds between ticks for idle tasks. See CXllPushApp::SetTickPeriod() for more details.

Remarks

This function may only be called from the main thread.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::SetTickPeriod() | CXllPushApp::SetRefreshPeriod() | CXllPushApp::GetRefreshPeriod()


CXllPushApp::OnCellUpdate

Called in main thread whenever a connected cell range is updated

virtual void OnCellUpdate(
   PCXPPRANGEDATA data,
   PXPPCELLFORMAT format
);

Parameters

data

Read-only structure containing information about the cell, including its previous and current values.
format

Writeable structure containing formatting instructions for the cell. The flMask member should be set to indicate which of the structure's members have been populated.

Remarks

This event is raised in the main thread just after a range has been recalculated and just before it is reformatted.

The implementation may populate various members of *format. The default implementation sets cells whose numeric value has increased to blue text, and cells whose value has decreased to red. If GetFormatChangedCells() returns FALSE, then the default implementation does nothing.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::OnTopicRemove


CXllPushApp::OnTopicAdd

Called in main thread whenever a new topic is added to the list of connections

virtual void OnTopicAdd(
   LPCSTR pszTopic
);

Parameters

pszTopic

The topic string.

Remarks

This method is called whenever a new topic is added to the list of connections. It will not be called for the second or third such connection, only the first. The default implementation does nothing.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::OnTopicRemove


CXllPushApp::OnTopicRemove

Called in main thread whenever the last connection to a topic is removed from the list of connections

virtual void OnTopicRemove(
   LPCSTR pszTopic
);

Parameters

pszTopic

The topic string.

Remarks

This method is called whenever the a topic is removed from the list of connections. It will only be called when the last connection to the topic is removed. The default implementation does nothing.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::OnTopicRemove


CXllPushApp::OnXllClose

Called during application termination

virtual void OnXllClose( );

Remarks

This virtual function should be implemented by any class descended from CXllPushApp. The method is called only once in the lifetime of an addin, just before it is closed.

It should always call the parent class implementation (CXllPushApp::OnXllClose()).

It should clean up any resources used by the application, such as database connections and data feeds.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::OnXllOpenEx() | CXllApp::OnXllClose() | Steps to create an asynchronous add-in


CXllPushApp::OnXllOpenEx

Called during application initialization

virtual BOOL OnXllOpenEx( );

Return Value

The method should return TRUE if initialization succeeded, FALSE if it failed.

Remarks

This virtual function should be implemented by any class descended from CXllPushApp. The method is called only once in the lifetime of an addin, when it is first opened.

It should always call the parent class implementation (CXllPushApp::OnXllOpenEx()) first, and return FALSE if it fails.

It should open any resources required by the application, such as database connections and data feeds. If any errors occur during such initialization, it should show an error message and then return FALSE to indicate failure.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllApp::OnXllOpenEx() | CXllPushApp::OnXllClose() | Steps to create an asynchronous add-in


CXllPushApp::PostMessage

Posts a message to the main thread's message queue

BOOL PostMessage(
   CXllMtMsg* msg
);

Parameters

msg

A message of a class descended from CXllMtMsg. The message will no longer be owned by the posting thread; it will be the responsibility of the main thread from here on.

Return Value

Returns TRUE if the function succeeded, FALSE if it failed. If it failed, then the caller is reposible for deleting the message.

Remarks

This function may only be called from any thread, including the main thread.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::ProcessAsyncMessage() | CXllMtMsg


CXllPushApp::ProcessAsyncMessage

Called in main thread whenever a message is received from another thread

virtual void ProcessAsyncMessage(
   CXllMtMsg* msg = NULL
);

Parameters

msg

A message class descended from CXllMtMsg. This is the value passed as an argument to PostMessage()

Remarks

This virtual function must be implemented by any class descended from CXllPushApp.

ProcessAsyncMessage() is called whenever a messsage is received from another thread, at a time when it is safe for the add-in to process the message. The implementation should process or store the message, and pass a notification of any changes to the push engine, using CXllPush::UpdateCells().

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | Steps to create an asynchronous add-in


CXllPushApp::SetFormatChangedCells

Sets whether formatting behaviour for changed cells is switched on

BOOL SetFormatChangedCells(
   BOOL bFormat
);

Parameters

bFormat

The new value of the switch. If the value is TRUE, then cells which are updtaed by the push engine will be reformatted according to the current settings, whenever they are changed. If FALSE, no formatting will take place.

Return Value

The function returns TRUE if the function succeeds, FALSE for failure.

Remarks

This function may only be called from the main thread.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::GetFormatChangedCells() | CXllPushApp::OnCellUpdate()


CXllPushApp::SetRefreshPeriod

Sets the time in milliseconds between calls to RefreshFromApplication()

BOOL SetRefreshPeriod(
   long lMillisecs
);

Parameters

lMillisecs

The new value of the period in milliseconds. See remarks below.

Return Value

The function returns TRUE if the function succeeds, FALSE for failure.

Remarks

In order to keep track of connected cells that may have been moved by the user, the push engine periodically checks for changes to connected cells, by calling RefreshFromApplication(). This method controls the time in milliseconds between these checks.

This function may only be called from the main thread.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::GetRefreshPeriod() | CXllPushApp::SetTickPeriod() | CXllPushApp::GetTickPeriod()


CXllPushApp::SetTickPeriod

Sets the time between ticks for idle tasks

BOOL SetTickPeriod(
   long lMillisecs
);

Parameters

lMillisecs

The new value of the period in milliseconds. See remarks below.

Return Value

The function returns TRUE if the function succeeds, FALSE for failure.

Remarks

Sometimes updates cannot be sent immediately to Excel, because the application is busy, or the user interface is in use. The push engine will try again within TickPeriod milliseconds.

This function may only be called from the main thread.

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::GetTickPeriod() | CXllPushApp::SetRefreshPeriod() | CXllPushApp::GetRefreshPeriod()


CXllPushApp::UpdateCells

Update all cells connected to the topic

void UpdateCells(
   LPCSTR pszTopic,
   BOOL bUpdateNow = FALSE
);

Parameters

pszTopic

The topic string.
bUpdateNow

This should always be FALSE.

Remarks

This function may only be called from the main thread. It is generally only called from ProcessAsyncMessage().

Requirements

Header: xlppush.h

See Also

CXllPushApp Class | CXllPushApp Methods | CXllPushApp::AddConnection() | CXllPushApp::ProcessAsyncMessage() | Steps to create an asynchronous add-in


cpplog/TraceAppender.h

Overview

TraceAppender.h contains a log appender class which writes output to the TRACE macro.

The main logging header file cpplog.h must be included before TraceAppender.h.

For an introduction to the design and use of the logging framework, see Logging in the User Guide.

Classes

The table below lists the C++ object classes declared in the header file.

Class | Description
TraceAppender | An appender class which writes to the TRACE macro.


nonrtdhandles.h

Overview

nonrtdhandles.h contains common classes and functions used by the non-RTD implementations of object handles, including StringHandles, StringPtrHandles and NumericHandles.

Classes

The table below lists the principal C++ object classes declared in the header file.

Class | Description
HandleCacheInstanceImportManager | Manages the sharing of object handles between XLLs.

See Also

Other handle implementations


HandleCacheInstanceImportManager Class

Manages the sharing of object handles between XLLs.

class psl::HandleCacheInstanceImportManager

Overview

The HandleCacheInstanceImportManager class is a helper class that supports the sharing of object handles between different XLLs. In particular, it allows a one XLL - the handle consumer XLL - to redirect the search for certain classes of object handle to another specific XLL - the handle provider XLL.

Use pattern

The use of the class is very straightforward. In the consumer XLL, during the event handler CXllApp::OnXllOpenEx(), the object types to be found elsewhere shouyld be listed by calling HandleCacheInstanceImportManager::RegisterType(), e.g.:

CopyC++
BOOL CHandleConsumerApp::OnXllOpenEx()
{
    // Inform the controller that handles for the following object types will
    // be sourced from "HandleProvider.xll"
    psl::HandleCacheInstanceImportManager::RegisterType(L"Thing", _T("HandleProvider.xll"));
    psl::HandleCacheInstanceImportManager::RegisterType(L"test::Thing2", _T("HandleProvider.xll"));
    psl::HandleCacheInstanceImportManager::RegisterType(L"std::map<std::string,std::string>", _T("HandleProvider.xll"));
    return TRUE;
}

The class name argument must be a wide (Unicode) string and must exactly match the form of the class name used in add-in functions. If a namespace is used in the add-in function's definition then the namespace must be used in the RegisterType() call.

Similarly, if template arguments are used, they must be in exactly the same form as in the add-in function, including white-space.

Note that the XLL name is in standard text form (either ASCII or Unicode depending on the project settings) and that it:

  1. includes the extension ".xll";
  2. does not include the directory of the XLL.

It is also essential that, in the provider XLL, the macro NONRTDHANDLES_IMPLEMENT_EXPORT is inserted before the inclusion of any handle header file, e.g.:

CopyC++
#define NONRTDHANDLES_IMPLEMENT_EXPORT
#include "extensions\StringHandles.h"

See the SharedHandles sample project for an example of the class in use.

Requirements

Header: nonrtdhandles.h
Namespace: psl

See Also

HandleCacheInstanceImportManager Methods | nonrtdhandles.h | Sharing object handles between XLLs (User Guide) | SharedHandles Sample


HandleCacheInstanceImportManager Methods

The methods of the HandleCacheInstanceImportManager class are listed here.

Locking

RegisterType Registers a handle type as being provided by another XLL

Construction

public method HandleCacheInstanceImportManager Constructs a HandleCacheInstanceImportManager object

Requirements

Header: nonrtdhandles.h
Namespace: psl

See Also

HandleCacheInstanceImportManager Class | nonrtdhandles.h | Sharing object handles between XLLs (User Guide) | SharedHandles Sample


HandleCacheInstanceImportManager::HandleCacheInstanceImportManager

Constructs a HandleCacheInstanceImportManager object

HandleCacheInstanceImportManager( );

Requirements

Header: nonrtdhandles.h

See Also

HandleCacheInstanceImportManager Class | HandleCacheInstanceImportManager Methods


HandleCacheInstanceImportManager::RegisterType

Registers a handle type as being provided by another XLL

static void RegisterType(
   const wchar_t* wpszTypeName,
   const TCHAR* pszXllFile
);

Parameters

wpszTypeName

The type of an object represented by a handle.

The class name argument must be a wide (Unicode) string and must exactly match the form of the class name used in add-in functions. If a namespace is used in the add-in function's definition then the namespace must also be used here.

Similarly, if template arguments are used, they must be in exactly the same form as in the add-in function, including white-space.
pszXllFile

The name of the XLL which will provide the handles of the specified class.

Note that the XLL name is in standard text form (either ASCII or Unicode depending on the project settings) and that it:

  1. includes the extension ".xll";
  2. does not include the directory of the XLL.

Remarks

For examples of use, see the SharedHandles sample project.

Requirements

Header: nonrtdhandles.h

See Also

HandleCacheInstanceImportManager Class | HandleCacheInstanceImportManager Methods | Sharing object handles between XLLs (User Guide) | SharedHandles Sample


plemtx.h

Overview

plemtx.h contains classes and functions for populating and manipulating two-dimensional matrices of data.

All the matrix handling operations within the XLL+ core library expect matrix data in a shape conforming to the interface defined by imtx<T>. If you already have matrix class, and you wish to continue using it in your add-in code, then you can easily build an adapter class to make it work with the XLL+ core functions. See Adapter classes for imtx<T> for instructions on building an adapter class.

Classes

The following classes are contained in plemtx.h:

Class | Purpose
imtx<T> | Abstract interface; defines all methods required by matrix objects.
imtx_impl<T> | Default implementation class; returns false to all optional operations.
mtx_ptrs<T> | Implementation class; stores data in an array of pointers.
mtx_flat<T> | Implementation class; stores data in a single continuous array.
mtx_ptrreader<M> | Translation class; reads data from any matrix into an array of pointers.
mtx_ptrwriter<M> | Translation class; writes data to any matrix from an array of pointers.
mtx_flatreader<M> | Translation class; reads data from any matrix into a continous array of items.
mtx_flatwriter<M> | Translation class; writes data to any matrix from a continous array of items.

Global functions

The following global functions make use of imtx<T> and its associated classes:

Function | Purpose
ptrreader<M> | Constructor function, which creates a mtx_ptrreader object for a given matrix.
ptrwriter<M> | Constructor function, which creates a mtx_ptrwriter object for a given matrix.
flatreader<M> | Constructor function, which creates a mtx_flatreader object for a given matrix.
flatwriter<M> | Constructor function, which creates a mtx_flatwriter object for a given matrix.
copy_offset<M, N> | Generic copy function, for transferring data between matrices, including matrices of different sizes and/or storage strategies.
mtx_copy<M, N> | Generic copy function, for transferring data between equal-sized matrices, including matrices with different storage strategies.
mtx_flatten<M, V> | Generic copy function, for transferring data between a matrix and a std::vector<T>.
mtx_copy_transpose<M, N> | Generic copy function, for transposing data between equivalent-sized matrices, including matrices with different storage strategies.
mtx_transpose<M> | Generic transformation function, for transposing data between rows and columns in a single matrix.

See Also

imtx<T> interface | Adapter classes for imtx<T>


imtx_impl<T> Class

Default implementation class for the imtx<T> interface.

class imtx_impl<T> : public imtx

Overview

The imtx_impl<T> template is a default implementation class for the imtx<T> interface.

Any class that is descended from imtx_impl can make use of the matrix methods contained in COper, CXlOper and CXlArray, which support conversion of array data to and from Excel formats.

If your code already uses a matrix class, you can easily define an adaptor class desecended form imtx_impl<T> that will allow your existing class to be used as well.

The class also contains methods and operators that make it convenient to pass values to functions expecting arrays of type T.

The standard template classes mtx_ptrs<T> and mtx_flat<T> are descended from imtx_impl<T>.

Requirements

Header: plemtx.h

See Also

imtx_impl<T> Methods | plemtx.h | imtx<T> class | mtx_ptrs<T> class | mtx_flat<T> class


imtx_impl<T> Methods

The methods of the imtx_impl<T> class are listed here.

Conversion operations

public method | get_flat | Gets a pointer to a flattened, continuous array containing all the members of the matrix
public method | get_ptrs | Gets an array of pointers to the rows or columns of a matrix

Construction

public method imtx_impl Constructs a imtx_impl object

Methods of imtx<T>

Requirements

Header: plemtx.h

See Also

imtx_impl<T> Class | plemtx.h | imtx<T> class | mtx_ptrs<T> class | mtx_flat<T> class


imtx_impl<T>::get_flat

Gets a pointer to a flattened, continuous array containing all the members of the matrix

virtual bool get_flat(
   const T*& data
) const;
virtual bool get_flat(
   T*& data
);

Parameters

data

Buffer for a pointer to an array of items.
data

Buffer for a pointer to an array of items.

Return Value

Returns true if the operation is supported, false if it is not.

Remarks

This method should set data to the start of an array of T containing all the members of the matrix. The number of vectors should be the same as the value returned by size(0) * size(1), i.e. the total size of the matrix.

The data should be arranged with the inner dimension continuous, i.e. a 2 x 2 matrix would arranged as: at(0,0), at(0,1), at(1,0), at(1,1).

If the storage method used by the implementation class does not support this form of operation without rearrangement of data, then the method should return false.

The default implementation returns false, to signify that the operation is not supported.

Requirements

Header: plemtx.h

See Also

imtx_impl<T> Class | imtx_impl<T> Methods


imtx_impl<T>::get_ptrs

Gets an array of pointers to the rows or columns of a matrix

virtual bool get_ptrs(
   const T**& ptrs
) const;
virtual bool get_ptrs(
   T**& ptrs
);

Parameters

ptrs

Buffer for a pointer to an array of pointers.
ptrs

Buffer for a pointer to an array of pointers.

Return Value

Returns true if the operation is supported, false if it is not.

Remarks

This method should set ptrs to the start of an array of pointers to each of the vectors contained in the natrix. The number of vectors should be the same as the value returned by size(0), i.e. the size of the inner dimension of the matrix.

If the storage method used by the implementation class does not support this form of operation without rearrangement of data, then the method should return false.

The default implementation returns false, to signify that the operation is not supported.

Requirements

Header: plemtx.h

See Also

imtx_impl<T> Class | imtx_impl<T> Methods


imtx_impl<T>::imtx_impl

Constructs a imtx_impl object

imtx_impl( );

Requirements

Header: plemtx.h

See Also

imtx_impl<T> Class | imtx_impl<T> Methods


imtx<T> Class

A pure interface definition for a container of two-dimensional arrays of type T.

class imtx<T>

Overview

The imtx<T> template is a pure interface definition for a container of two-dimensional arrays of type T.

Any class that is descended from imtx (or which implements all of the methods defined in the interface) can make use of the matrix methods contained in COper, CXlOper and CXlArray, which support conversion of array data to and from Excel formats.

If your code already uses a matrix class, you can easily define an adapter class that will allow your existing class to be used as well.

The class also contains methods and operators that make it convenient to pass values to functions expecting arrays of type T. See the Tutorial for further examples of using imtx<T>.

Associated classes

The following classes are descended from or associated with imtx<T>:

Class | Purpose
imtx_impl<T> | Default implementation class; returns false to all optional operations.
mtx_ptrs<T> | Implementation class; stores data in an array of pointers.
mtx_flat<T> | Implementation class; stores data in a single continuous array.
mtx_ptrreader<M> | Translation class; reads data from any matrix into an array of pointers.
mtx_ptrwriter<M> | Translation class; writes data to any matrix from an array of pointers.
mtx_flatreader<M> | Translation class; reads data from any matrix into a continous array of items.
mtx_flatwriter<M> | Translation class; writes data to any matrix from a continous array of items.

Global functions

The following global functions make use of imtx<T> and its associated classes:

Function | Purpose
ptrreader<M> | Constructor function, which creates a mtx_ptrreader object for a given matrix.
ptrwriter<M> | Constructor function, which creates a mtx_ptrwriter object for a given matrix.
flatreader<M> | Constructor function, which creates a mtx_flatreader object for a given matrix.
flatwriter<M> | Constructor function, which creates a mtx_flatwriter object for a given matrix.
copy_offset<M, N> | Generic copy function, for transferring data between matrices, including matrices of different sizes and/or storage strategies.
mtx_copy<M, N> | Generic copy function, for transferring data between equal-sized matrices, including matrices with different storage strategies.
mtx_flatten<M, V> | Generic copy function, for transferring data between a matrix and a std::vector<T>.
mtx_copy_transpose<M, N> | Generic copy function, for transposing data between equivalent-sized matrices, including matrices with different storage strategies.
mtx_transpose<M> | Generic transformation function, for transposing data between rows and columns in a single matrix.

Requirements

Header: plemtx.h

See Also

imtx<T> Methods | plemtx.h | imtx_impl<T> class | mtx_ptrs<T> class | mtx_flat<T> class | Adapter classes for imtx<T>


imtx<T> Methods

The methods of the imtx<T> class are listed here.

Matrix operations

public method | at | Get a reference to a member of the matrix
public method | resize | Resize a matrix
public method | size | Get the size of a dimension of the matrix

Conversion operations

public method | get_flat | Gets a pointer to a flattened, continuous array containing all the members of the matrix
public method | get_ptrs | Gets an array of pointers to the rows or columns of a matrix

Construction

public method imtx Constructs a imtx object

Requirements

Header: plemtx.h

See Also

imtx<T> Class | plemtx.h | imtx_impl<T> class | mtx_ptrs<T> class | mtx_flat<T> class | Adapter classes for imtx<T>


imtx<T>::at

Get a reference to a member of the matrix

virtual const T& at(
   size_t i0,
   size_t i1
) const;
virtual T& at(
   size_t i0,
   size_t i1
);

Parameters

i0

Coordinate in dimension 0. In Excel this corresponds to the zero-based row index.
i1

Coordinate in dimension 1. In Excel this corresponds to the zero-based column index.

Return Value

Returns a reference to a member of the matrix. The reference returned by form 2 may be used for assignment.

Remarks

This method returns a reference to a specified member of the matrix.

Requirements

Header: plemtx.h

See Also

imtx<T> Class | imtx<T> Methods


imtx<T>::get_flat

Gets a pointer to a flattened, continuous array containing all the members of the matrix

virtual bool get_flat(
   const T*& data
) const;
virtual bool get_flat(
   T*& data
);

Parameters

data

Buffer for a pointer to an array of items.
data

Buffer for a pointer to an array of items.

Return Value

Returns true if the operation is supported, false if it is not.

Remarks

This method should set data to the start of an array of T containing all the members of the matrix. The number of items should be the same as the value returned by size(0) * size(1), i.e. the total size of the matrix.

The data should be arranged with the inner dimension continuous, i.e. a 2 x 2 matrix would be arranged as: at(0,0), at(0,1), at(1,0), at(1,1).

If the storage method used by the implementation class does not support this form of operation without rearrangement of data, then the method should return false.

Requirements

Header: plemtx.h

See Also

imtx<T> Class | imtx<T> Methods


imtx<T>::get_ptrs

Gets an array of pointers to the rows or columns of a matrix

virtual bool get_ptrs(
   const T**& ptrs
) const;
virtual bool get_ptrs(
   T**& ptrs
);

Parameters

ptrs

Buffer for a pointer to an array of pointers.
ptrs

Buffer for a pointer to an array of pointers.

Return Value

Returns true if the operation is supported, false if it is not.

Remarks

This method should set ptrs to the start of an array of pointers to each of the vectors contained in the natrix. The number of vectors should be the same as the value returned by size(0), i.e. the size of the inner dimension of the matrix.

If the storage method used by the implementation class does not support this form of operation without rearrangement of data, then the method should return false.

Requirements

Header: plemtx.h

See Also

imtx<T> Class | imtx<T> Methods


imtx<T>::imtx

Constructs a imtx object

imtx( );

Requirements

Header: plemtx.h

See Also

imtx<T> Class | imtx<T> Methods


imtx<T>::resize

Resize a matrix

virtual void resize(
   bool preserve,
   size_t dim0,
   size_t dim1
);

Parameters

preserve

If true, then the current contents of the matrix will be preserved. If false, then the contents will be set to arbitrary values.
dim0

The new size of dimension 0. In Excel this corresponds to the number of rows.
dim1

The new size of dimension 1. In Excel this corresponds to the number of columns.

Remarks

This method resizes a matrix.

Requirements

Header: plemtx.h

See Also

imtx<T> Class | imtx<T> Methods


imtx<T>::size

Get the size of a dimension of the matrix

virtual size_t size(
   int dim
) const;

Parameters

dim

Dimension number. In Excel, 0 corresponds to the number of rows, and 1 corresponds to the number of columns.

Remarks

This method the size of a specified dimension of the matrix.

Requirements

Header: plemtx.h

See Also

imtx<T> Class | imtx<T> Methods


mtx_flat<T> Class

Implementation of the imtx<T> interface using continuous storage.

class mtx_flat<T> : public imtx_impl

Overview

The mtx_flat<T> template is an implementation of the imtx<T> interface, and acts as a container of two-dimensional arrays of type T.

Because it is descended from imtx, it can make use of the matrix methods contained in COper, CXlOper and CXlArray, which support conversion of array data to and from Excel formats.

The class implements a storage method which maintains a continous array of type T. It is thus efficient as a data holder for existing functions which expect an array of "flattened" data (i.e. T*).

See the Tutorial for further examples of using mtx_flat<T>.

Requirements

Header: plemtx.h

See Also

mtx_flat<T> Methods | plemtx.h | imtx<T> class | imtx_impl<T> class | mtx_ptrs<T> class


mtx_flat<T> Methods

The methods of the mtx_flat<T> class are listed here.

Construction

public method mtx_flat Constructs a mtx_flat<T> object

Operators

public method | operator [] | Returns a reference to an item in the matrix
public method | operator [] const | Returns the value of an item in the matrix, indexed by its position
public method | operator = | Performs a deep copy

Matrix operations

public method | at | Get a reference to a member of the matrix
public method | resize | Resize a matrix
public method | size | Get the size of a dimension of the matrix

Conversion operations

public method | get_flat | Gets a pointer to a flattened, continuous array containing all the members of the matrix
public method | get_ptrs | Gets an array of pointers to the rows or columns of a matrix

Access operations

public method | begin | Returns a read-only or writeable pointer to the constituent data of a matrix
public method | end | Returns a read-only or writeable pointer to the address just after the last data of a matrix

Methods of imtx_impl<T>

Requirements

Header: plemtx.h

See Also

mtx_flat<T> Class | plemtx.h | imtx<T> class | imtx_impl<T> class | mtx_ptrs<T> class


mtx_flat<T>::at

Get a reference to a member of the matrix

virtual const T& at(
   size_t i0,
   size_t i1
) const;
virtual T& at(
   size_t i0,
   size_t i1
);

Parameters

i0

Coordinate in dimension 0. In Excel this corresponds to the zero-based row index.
i1

Coordinate in dimension 1. In Excel this corresponds to the zero-based column index.

Return Value

Returns a reference to a member of the matrix. The reference returned by form 2 may be used for assignment.

Remarks

This method returns a reference to a specified member of the matrix.

Requirements

Header: plemtx.h

See Also

mtx_flat<T> Class | mtx_flat<T> Methods


mtx_flat<T>::begin

Returns a read-only or writeable pointer to the constituent data of a matrix

T* begin( );
const T* begin( ) const;

Return Value

Returns a pointer to the constituent data of a matrix.

Requirements

Header: plemtx.h

See Also

mtx_flat<T> Class | mtx_flat<T> Methods


mtx_flat<T>::end

Returns a read-only or writeable pointer to the address just after the last data of a matrix

T* end( );
const T* end( ) const;

Return Value

Returns a pointer to the end of the array containing the data of a matrix.

Requirements

Header: plemtx.h

See Also

mtx_flat<T> Class | mtx_flat<T> Methods


mtx_flat<T>::get_flat

Gets a pointer to a flattened, continuous array containing all the members of the matrix

virtual bool get_flat(
   const T*& data
) const;
virtual bool get_flat(
   T*& data
);

Parameters

data

Buffer for a pointer to an array of items.
data

Buffer for a pointer to an array of items.

Return Value

Returns true if the operation is supported, false if it is not.

Remarks

This method sets data to the start of an array of T containing all the members of the matrix. The number of items is the same as the value returned by size(0) * size(1), i.e. the total size of the matrix.

The data is arranged with the inner dimension continuous, i.e. a 2 x 2 matrix is arranged as: at(0,0), at(0,1), at(1,0), at(1,1).

The method always returns true, to indicate that the operation is supported.

Requirements

Header: plemtx.h

See Also

mtx_flat<T> Class | mtx_flat<T> Methods


mtx_flat<T>::get_ptrs

Gets an array of pointers to the rows or columns of a matrix

virtual bool get_ptrs(
   const T**& ptrs
) const;
virtual bool get_ptrs(
   T**& ptrs
);

Parameters

ptrs

Buffer for a pointer to an array of pointers.
ptrs

Buffer for a pointer to an array of pointers.

Return Value

Always returns false.

Remarks

This method always returns false, to indicate that it is not supported by its storage method.

Requirements

Header: plemtx.h

See Also

mtx_flat<T> Class | mtx_flat<T> Methods


mtx_flat<T>::mtx_flat

Constructs a mtx_flat<T> object

mtx_flat( );
mtx_flat(
   size_t dim0,
   size_t dim1
);
mtx_flat(
   const mtx_flat<T>& mat
);

Parameters

dim0

The initial size of dimension 0
dim1

The initial size of dimension 1
mat

A reference to a mtx_flat<T> object.

Remarks

The third version of the contructor copies the contents of its argument into the new matrix object.

Requirements

Header: plemtx.h

See Also

mtx_flat<T> Class | mtx_flat<T> Methods


mtx_flat<T>::operator []

Returns a reference to an item in the matrix

T& operator [](
   size_t i
);

Parameters

i

Index into flat array

Remarks

This overloaded operator returns the value of an item in the matrix, indexed by its position in the flat array.

It is mostly useful as a way of passing data to a function which expect pointers to flat data. For example:

    ple::mtx_flat<double> m;
    ...
    rc = call_function(&m[0], ...);

Requirements

Header: plemtx.h

See Also

mtx_flat<T> Class | mtx_flat<T> Methods | operator [] const | Walkthrough: Adding a matrix argument


mtx_flat<T>::operator [] const

Returns the value of an item in the matrix, indexed by its position

T operator [] const(
   size_t i
) const;

Parameters

i

Index into flat array

Remarks

This overloaded operator returns the value of an item in the matrix, indexed by its position in the flat array.

Requirements

Header: plemtx.h

See Also

mtx_flat<T> Class | mtx_flat<T> Methods | operator []


mtx_flat<T>::operator =

Performs a deep copy

const COper& operator =(
   const mtx_flat<T>& mat
);

Parameters

mat

A reference to a mtx_flat<T> object.

Remarks

This operator assigns the size and contents of the argument to the mtx_flat<T> object. If the mtx_flat<T> already contains data, then it will be cleared before the assignment.

Requirements

Header: plemtx.h

See Also

mtx_flat<T> Class | mtx_flat<T> Methods


mtx_flat<T>::resize

Resize a matrix

virtual void resize(
   bool preserve,
   size_t dim0,
   size_t dim1
);

Parameters

preserve

If true, then the current contents of the matrix will be preserved. If false, then the contents will be set to arbitrary values.
dim0

The new size of dimension 0. In Excel this corresponds to the number of rows.
dim1

The new size of dimension 1. In Excel this corresponds to the number of columns.

Remarks

This method resizes a matrix.

Requirements

Header: plemtx.h

See Also

mtx_flat<T> Class | mtx_flat<T> Methods


mtx_flat<T>::size

Get the size of a dimension of the matrix

virtual const T& size(
   int dim
) const;

Parameters

dim

Dimension number. In Excel, 0 corresponds to the number of rows, and 1 corresponds to the number of columns.

Remarks

This method the size of a specified dimension of the matrix.

Requirements

Header: plemtx.h

See Also

mtx_flat<T> Class | mtx_flat<T> Methods


mtx_flatreader<M> Class

Supports read-only access to any class that supports the imtx<T> interface.

class mtx_flatreader<M>

Overview

The mtx_flatreader<M> template supports read-only access to any class M that supports the imtx<T> interface. Through its get_flat() method, it provides a continuous "flattened" array of T.

The class can be applied to a matrix of any type, but is more efficient when applied to a matrix whose storage strategy uses a "flat" storage method.

See the Tutorial for an example of using mtx_flatreader<M>.

Requirements

Header: plemtx.h

See Also

mtx_flatreader<M> Methods | plemtx.h | mtx_flatwriter<M> class | imtx<T> class | imtx_impl<T> class


mtx_flatreader<M> Methods

The methods of the mtx_flatreader<M> class are listed here.

Construction

public method mtx_flatreader Constructs and initialises a mtx_flatreader<M> object

Operations

public method get_flat Get a continuous flattened array of items

Operators

public method | operator const M::mtx_item_type* | Get a pointer to the members of the matrix
public method | operator M::mtx_item_type* | Get a pointer to the members of the matrix

Requirements

Header: plemtx.h

See Also

mtx_flatreader<M> Class | plemtx.h | mtx_flatwriter<M> class | imtx<T> class | imtx_impl<T> class


mtx_flatreader<M>::get_flat

Get a continuous flattened array of items

const M::mtx_item_type* get_flat( ) const;

Remarks

This method returns a contigous "flattened" array containing all the items in the matrix.

Requirements

Header: plemtx.h

See Also

mtx_flatreader<M> Class | mtx_flatreader<M> Methods


mtx_flatreader<M>::mtx_flatreader

Constructs and initialises a mtx_flatreader<M> object

mtx_flatreader(
   const M& m
);

Parameters

m

A reference to an object of type M that supports the imtx<T> interface.

Remarks

The creates a reader object and attaches it to the supplied matrix.

Requirements

Header: plemtx.h

See Also

mtx_flatreader<M> Class | mtx_flatreader<M> Methods


mtx_flatreader<M>::operator const M::mtx_item_type*

Get a pointer to the members of the matrix

const M::mtx_item_type* operator const M::mtx_item_type*( ) const;

Remarks

This overloaded operator returns a read-only pointer to the contents of the matrix.

Requirements

Header: plemtx.h

See Also

mtx_flatreader<M> Class | mtx_flatreader<M> Methods


mtx_flatreader<M>::operator M::mtx_item_type*

Get a pointer to the members of the matrix

M::mtx_item_type* operator M::mtx_item_type*( );

Remarks

This method returns a contigous "flattened" array containing all the items in the matrix.

Because the pointers are not const, the mtx_flatreader<M> makes a copy of the data contained in the attached matrix, and returns a pointer to the copied data.

Thus the data in the original matrix is never affected by write operations to the passed array.

Requirements

Header: plemtx.h

See Also

mtx_flatreader<M> Class | mtx_flatreader<M> Methods


mtx_flatwriter<M> Class

Supports read-write access to any class that supports the imtx<T> interface.

class mtx_flatwriter<M>

Overview

The mtx_flatwriter<M> template supports read-write access to any class M that supports the imtx<T> interface. Through its get_flat() method, it provides a continuous "flattened" array of T.

The class can be applied to a matrix of any type, but is more efficient when applied to a matrix whose storage strategy uses a "flat" storage method.

See the Tutorial for an example of using mtx_flatwriter<M>.

Requirements

Header: plemtx.h

See Also

mtx_flatwriter<M> Methods | plemtx.h | mtx_flatreader<M> class | imtx<T> class | imtx_impl<T> class


mtx_flatwriter<M> Methods

The methods of the mtx_flatwriter<M> class are listed here.

Construction

public method mtx_flatwriter Constructs and initialises a mtx_flatwriter<M> object

Operations

public method get_flat Get a continuous flattened array of items

Operators

public method operator M::mtx_item_type* Get an pointer to the members of the matrix

Requirements

Header: plemtx.h

See Also

mtx_flatwriter<M> Class | plemtx.h | mtx_flatreader<M> class | imtx<T> class | imtx_impl<T> class


mtx_flatwriter<M>::get_flat

Get a continuous flattened array of items

M::mtx_item_type* get_flat( );

Remarks

This method returns a contigous "flattened" array containing all the items in the matrix.

Requirements

Header: plemtx.h

See Also

mtx_flatwriter<M> Class | mtx_flatwriter<M> Methods


mtx_flatwriter<M>::mtx_flatwriter

Constructs and initialises a mtx_flatwriter<M> object

mtx_flatwriter(
   M& m
);

Parameters

m

A reference to an object of type M that supports the imtx<T> interface.

Remarks

The creates a writer object and attaches it to the supplied matrix.

Requirements

Header: plemtx.h

See Also

mtx_flatwriter<M> Class | mtx_flatwriter<M> Methods


mtx_flatwriter<M>::operator M::mtx_item_type*

Get an pointer to the members of the matrix

M::mtx_item_type* operator M::mtx_item_type*( );

Remarks

This overloaded operator returns a read-write pointer to the contents of the matrix.

Requirements

Header: plemtx.h

See Also

mtx_flatwriter<M> Class | mtx_flatwriter<M> Methods


mtx_ptrreader<M> Class

Supports read-only access to any class that supports the imtx<T> interface.

class mtx_ptrreader<M>

Overview

The mtx_ptrreader<M> template supports read-only access to any class M that supports the imtx<T> interface. Through its get_ptrs() method, it provides an array of pointers to arrays of T.

The class can be applied to a matrix of any type, but is more efficient when applied to a matrix whose storage strategy uses an array of pointers.

See the Tutorial for an example of using mtx_ptrreader<M>.

Requirements

Header: plemtx.h

See Also

mtx_ptrreader<M> Methods | plemtx.h | mtx_ptrwriter<M> class | imtx<T> class | imtx_impl<T> class


mtx_ptrreader<M> Methods

The methods of the mtx_ptrreader<M> class are listed here.

Construction

public method mtx_ptrreader Constructs and initialises a mtx_ptrreader<M> object

Operations

public method get_ptrs Get an array of pointers to arrays

Operators

public method | operator const M::mtx_item_type** | Get an array of pointers to arrays
public method | operator M::mtx_item_type** | Get an array of pointers to arrays

Requirements

Header: plemtx.h

See Also

mtx_ptrreader<M> Class | plemtx.h | mtx_ptrwriter<M> class | imtx<T> class | imtx_impl<T> class


mtx_ptrreader<M>::get_ptrs

Get an array of pointers to arrays

const M::mtx_item_type** get_ptrs( ) const;

Remarks

This method returns an array of pointers to the rows or columns of the matrix.

Requirements

Header: plemtx.h

See Also

mtx_ptrreader<M> Class | mtx_ptrreader<M> Methods


mtx_ptrreader<M>::mtx_ptrreader

Constructs and initialises a mtx_ptrreader<M> object

mtx_ptrreader(
   const M& m
);

Parameters

m

A reference to an object of type M that supports the imtx<T> interface.

Remarks

The creates a reader object and attaches it to the supplied matrix.

Requirements

Header: plemtx.h

See Also

mtx_ptrreader<M> Class | mtx_ptrreader<M> Methods


mtx_ptrreader<M>::operator const M::mtx_item_type**

Get an array of pointers to arrays

const M::mtx_item_type** operator const M::mtx_item_type**( ) const;

Remarks

This overloaded operator returns an array of read-only pointers to the rows or columns of the matrix.

Requirements

Header: plemtx.h

See Also

mtx_ptrreader<M> Class | mtx_ptrreader<M> Methods


mtx_ptrreader<M>::operator M::mtx_item_type**

Get an array of pointers to arrays

M::mtx_item_type** operator M::mtx_item_type**( );

Remarks

This overloaded operator returns an array of pointers to the rows or columns of the matrix.

Because the pointers are not const, the mtx_ptrreader<M> makes a copy of the data contained in the attached matrix, and returns pointers to the copied data.

Thus the data in the original matrix is never affected by write operations to the passed arrays.

Requirements

Header: plemtx.h

See Also

mtx_ptrreader<M> Class | mtx_ptrreader<M> Methods


mtx_ptrs<T> Class

Implementation of the imtx<T> interface using arrays of arrays.

class mtx_ptrs<T> : public imtx_impl

Overview

The mtx_ptrs<T> template is an implementation of the imtx<T> interface, and acts as a container of two-dimensional arrays of type T.

Because it is descended from imtx, it can make use of the matrix methods contained in COper, CXlOper and CXlArray, which support conversion of array data to and from Excel formats.

The class implements a storage method which maintains an array of pointers to homogenous arrays of type T. It is thus efficient as a data holder for existing functions which expect an array of pointers (i.e. T**).

Example

mtx_ptrs<T> Example

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Methods | plemtx.h | imtx<T> class | imtx_impl<T> class | mtx_flat<T> class | Walkthrough: Adding a matrix argument


mtx_ptrs<T> Methods

The methods of the mtx_ptrs<T> class are listed here.

Construction

public method mtx_ptrs Constructs a mtx_ptrs<T> object

Operators

public method | operator [] | Returns a pointer to one sub-array
public method | operator [] const | Returns a read-only pointer to one sub-array
public method | operator = | Performs a deep copy

Matrix operations

public method | at | Get a reference to a member of the matrix
public method | erase | Erases a range of rows or columns
public method | resize | Resize a matrix
public method | size | Get the size of a dimension of the matrix

Conversion operations

public method | get_flat | Gets a pointer to a flattened, continuous array containing all the members of the matrix
public method | get_ptrs | Gets an array of pointers to the rows or columns of a matrix

Access operations

public method | begin | Returns a read-only or writeable array of pointers to the constituent vectors of a matrix
public method | end | Returns a read-only or writeable array of pointers to the address just after the last constituent vector of a matrix

Methods of imtx_impl<T>

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Class | plemtx.h | imtx<T> class | imtx_impl<T> class | mtx_flat<T> class | Walkthrough: Adding a matrix argument


mtx_ptrs<T>::at

Get a reference to a member of the matrix

virtual const T& at(
   size_t i0,
   size_t i1
) const;
virtual T& at(
   size_t i0,
   size_t i1
);

Parameters

i0

Coordinate in dimension 0. In Excel this corresponds to the zero-based row index.
i1

Coordinate in dimension 1. In Excel this corresponds to the zero-based column index.

Return Value

Returns a reference to a member of the matrix. The reference returned by form 2 may be used for assignment.

Remarks

This method returns a reference to a specified member of the matrix.

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Class | mtx_ptrs<T> Methods


mtx_ptrs<T>::begin

Returns a read-only or writeable array of pointers to the constituent vectors of a matrix

T** begin( );
const T** begin( ) const;

Return Value

Returns a pointer to the constituent vectors of a matrix.

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Class | mtx_ptrs<T> Methods


mtx_ptrs<T>::end

Returns a read-only or writeable array of pointers to the address just after the last constituent vector of a matrix

T** end( );
const T** end( ) const;

Return Value

Returns a pointer to the end of the array containing the constituent vectors of a matrix.

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Class | mtx_ptrs<T> Methods


mtx_ptrs<T>::erase

Erases a range of rows or columns

void erase(
   int dim,
   size_t b,
   size_t e
);

Parameters

dim

Dimension number. Specifies in which dimension the selected range will be erased. In Excel, 0 corresponds to the number of rows, and 1 corresponds to the number of columns.
b

Index of the first row or column to be erased.
e

Index of the first row or column beyond the range to be erased. The number of rows or columns erased will be (e - b).

Remarks

This method the size of a specified dimension of the matrix.

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Class | mtx_ptrs<T> Methods


mtx_ptrs<T>::get_flat

Gets a pointer to a flattened, continuous array containing all the members of the matrix

virtual bool get_flat(
   const T*& data
) const;
virtual bool get_flat(
   T*& data
);

Parameters

data

Buffer for a pointer to an array of items.
data

Buffer for a pointer to an array of items.

Return Value

Returns true if the operation is supported, false if it is not.

Remarks

This method always returns false, to indicate that it is not supported by its storage method.

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Class | mtx_ptrs<T> Methods


mtx_ptrs<T>::get_ptrs

Gets an array of pointers to the rows or columns of a matrix

virtual bool get_ptrs(
   const T**& ptrs
) const;
virtual bool get_ptrs(
   T**& ptrs
);

Parameters

ptrs

Buffer for a pointer to an array of pointers.
ptrs

Buffer for a pointer to an array of pointers.

Return Value

Always returns true.

Remarks

This method sets ptrs to the start of an array of pointers to each of the vectors contained in the natrix. The number of vectors is the same as the value returned by size(0), i.e. the size of the inner dimension of the matrix.

The method always returns true, to indicate that the operation is supported.

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Class | mtx_ptrs<T> Methods


mtx_ptrs<T>::mtx_ptrs

Constructs a mtx_ptrs<T> object

mtx_ptrs( );
mtx_ptrs(
   size_t dim0,
   size_t dim1
);
mtx_ptrs(
   const mtx_ptrs<T>& mat
);

Parameters

dim0

The initial size of dimension 0
dim1

The initial size of dimension 1
mat

A reference to a mtx_ptrs<T> object.

Remarks

The third version of the contructor copies the contents of its argument into the new matrix object.

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Class | mtx_ptrs<T> Methods


mtx_ptrs<T>::operator []

Returns a pointer to one sub-array

T*& operator [](
   size_t i
);

Parameters

i

Index in dimension 0

Remarks

This overloaded operator returns a writeable pointer to one of the constituent vectors of the matrix.

This behaviour allows you to treat the matrix object like an array. For example:

    ple::mtx_ptrs<double> m;
    ...
    m[i][j] = a_value;

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Class | mtx_ptrs<T> Methods | operator [] const | Walkthrough: Adding a matrix argument


mtx_ptrs<T>::operator [] const

Returns a read-only pointer to one sub-array

const T* operator [] const(
   size_t i
) const;

Parameters

i

Index in dimension 0

Remarks

This overloaded operator returns a read-only pointer to one of the constituent vectors of the matrix.

This behaviour allows you to treat the matrix object like an array. For example:

    ple::mtx_ptrs<double> m;
    ...
    a_value = m[i][j];

Example

mtx_ptrs<T> Example

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Class | mtx_ptrs<T> Methods | operator [] | Walkthrough: Adding a matrix argument


mtx_ptrs<T>::operator =

Performs a deep copy

const COper& operator =(
   const mtx_ptrs<T>& mat
);

Parameters

mat

A reference to a mtx_ptrs<T> object.

Remarks

This operator assigns the size and contents of the argument to the mtx_ptrs<T> object. If the mtx_ptrs<T> already contains data, then it will be cleared before the assignment.

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Class | mtx_ptrs<T> Methods


mtx_ptrs<T>::resize

Resize a matrix

virtual void resize(
   bool preserve,
   size_t dim0,
   size_t dim1
);

Parameters

preserve

If true, then the current contents of the matrix will be preserved. If false, then the contents will be set to arbitrary values.
dim0

The new size of dimension 0. In Excel this corresponds to the number of rows.
dim1

The new size of dimension 1. In Excel this corresponds to the number of columns.

Remarks

This method resizes a matrix.

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Class | mtx_ptrs<T> Methods


mtx_ptrs<T>::size

Get the size of a dimension of the matrix

virtual const T& size(
   int dim
) const;

Parameters

dim

Dimension number. In Excel, 0 corresponds to the number of rows, and 1 corresponds to the number of columns.

Remarks

This method the size of a specified dimension of the matrix.

Example

mtx_ptrs<T> Example

Requirements

Header: plemtx.h

See Also

mtx_ptrs<T> Class | mtx_ptrs<T> Methods | Walkthrough: Adding a matrix argument


mtx_ptrwriter<M> Class

Supports read-write access to any class that supports the imtx<T> interface.

class mtx_ptrwriter<M>

Overview

The mtx_ptrwriter<M> template supports read-write access to any class M that supports the imtx<T> interface. Through its get_ptrs() method, it provides an array of pointers to arrays of T.

The class can be applied to a matrix of any type, but is more efficient when applied to a matrix whose storage strategy uses an array of pointers.

See the Tutorial for an example of using mtx_ptrwriter<M>.

Requirements

Header: plemtx.h

See Also

mtx_ptrwriter<M> Methods | plemtx.h | mtx_ptrreader<M> class | imtx<T> class | imtx_impl<T> class


mtx_ptrwriter<M> Methods

The methods of the mtx_ptrwriter<M> class are listed here.

Construction

public method mtx_ptrwriter Constructs and initialises a mtx_ptrwriter<M> object

Operations

public method get_ptrs Get an array of pointers to arrays

Operators

public method operator M::mtx_item_type** Get an array of pointers to arrays

Requirements

Header: plemtx.h

See Also

mtx_ptrwriter<M> Class | plemtx.h | mtx_ptrreader<M> class | imtx<T> class | imtx_impl<T> class


mtx_ptrwriter<M>::get_ptrs

Get an array of pointers to arrays

M::mtx_item_type** get_ptrs( );

Remarks

This method returns an array of pointers to the rows or columns of the matrix.

Requirements

Header: plemtx.h

See Also

mtx_ptrwriter<M> Class | mtx_ptrwriter<M> Methods


mtx_ptrwriter<M>::mtx_ptrwriter

Constructs and initialises a mtx_ptrwriter<M> object

mtx_ptrwriter(
   M& m
);

Parameters

m

A reference to an object of type M that supports the imtx<T> interface.

Remarks

The creates a writer object and attaches it to the supplied matrix.

Requirements

Header: plemtx.h

See Also

mtx_ptrwriter<M> Class | mtx_ptrwriter<M> Methods


mtx_ptrwriter<M>::operator M::mtx_item_type**

Get an array of pointers to arrays

const M::mtx_item_type** operator M::mtx_item_type**( );

Remarks

This overloaded operator returns an array of read-write pointers to the rows or columns of the matrix.

Requirements

Header: plemtx.h

See Also

mtx_ptrwriter<M> Class | mtx_ptrwriter<M> Methods


Matrix template functions

Matrix template functions are listed here.

Matrix adapters

public method | mtx_adapter<T> | Create an instance of an matrix adapter
public method | mtx_const_adapter<T> | Create an instance of a read-only matrix adapter

Matrix readers

public method | flatreader<M> | Create an instance of mtx_flatreader
public method | ptrreader<M> | Create an instance of mtx_ptrreader

Matrix writers

public method | flatwriter<M> | Create an instance of mtx_flatwriter
public method | ptrwriter<M> | Create an instance of mtx_ptrwriter

Copy operations

public method | copy_offset<M, N> | Copy one matrix to another, with offsets, truncating if required
public method | mtx_copy_transpose<M, N> | Copy one matrix to another, with the contents transposed
public method | mtx_copy<M, N> | Copy one matrix to another, resizing if required
public method | mtx_flatten<M, V> | Copy the members of a matrix to a flattened vector
public method | mtx_transpose<M> | Transpose the rows and columns of a matrix

Requirements

Header: plemtx.h

See Also

plemtx.h | imtx<T> class


::copy_offset<M, N>

Copy one matrix to another, with offsets, truncating if required

void copy_offset<M, N>(
   M& m,
   const N& n,
   int offset0,
   int offset1
);

Parameters

m

A reference to a target object of type M that supports the imtx<T> interface.
n

A reference to a source object of type N that supports the imtx<T> interface.
offset0

An offset in dimension 0. If it is negative it indicates that the first -offset0 rows/columns of the source matrix should be ignored. If positive, it indicates the start location within the target matrix.

offset1

An offset in dimension 1. If it is negative it indicates that the first -offset1 rows/columns of the source matrix should be ignored. If positive, it indicates the start location within the target matrix.

Remarks

This template function copies data from one matrix to another, with offsets, truncating if required.

Both matrices must support the imtx<T> interface. The matrixes do not need to be of the same type, but they should each have the same item type T.

Note that the function does not resize the target matrix.

Requirements

Header: plemtx.h

See Also

Matrix template functions


::flatreader<M>

Create an instance of mtx_flatreader

mtx_flatreader<M> flatreader<M>(
   const M& m
);

Parameters

m

A reference to an object of type M that supports the imtx<T> interface.

Return Value

An instance of mtx_flatreader<M> for a matrix of type M.

Remarks

This template function creates an instance of mtx_flatreader<M> to read the specified matrix.

Requirements

Header: plemtx.h

See Also

Matrix template functions


::flatwriter<M>

Create an instance of mtx_flatwriter

mtx_flatwriter<M> flatwriter<M>(
   M& m
);

Parameters

m

A reference to an object of type M that supports the imtx<T> interface.

Return Value

An instance of mtx_flatwriter<M> for a matrix of type M.

Remarks

This template function creates an instance of mtx_flatwriter<M> to read and write to the specified matrix.

Requirements

Header: plemtx.h

See Also

Matrix template functions


::mtx_adapter<T>

Create an instance of an matrix adapter

imtx<T> mtx_adapter<T>(
   C& src
);

Parameters

src

A reference to an object of type C which is a two-dimensional container for T, and does not support the imtx<T> interface.

Return Value

An instance of an adapter class that supports the imtx<T> interface.

Remarks

This template function creates an instance of a adapter derived from imtx<T> to read the specified matrix of type C.

The template function must be implemented for each matrix adapter class; it is called by the XLL+ code generated for reading matrix arguments.

Requirements

Header: plemtx.h

See Also

Matrix template functions


::mtx_const_adapter<T>

Create an instance of a read-only matrix adapter

imtx<T> mtx_const_adapter<T>(
   const C& src
);

Parameters

src

A reference to an object of type C which is a two-dimensional container for T, and does not support the imtx<T> interface.

Return Value

An instance of an adapter class that supports the imtx<T> interface.

Remarks

This template function creates an instance of a adapter derived from imtx<T> to read the specified matrix of type C.

The template function may be implemented for each matrix adapter class. It is not called by the XLL+ code generated for reading matrix arguments.

Requirements

Header: plemtx.h

See Also

Matrix template functions


::mtx_copy_transpose<M, N>

Copy one matrix to another, with the contents transposed

void mtx_copy_transpose<M, N>(
   M& m,
   const N& n
);

Parameters

m

A reference to a target object of type M that supports the imtx<T> interface.
n

A reference to a source object of type N that supports the imtx<T> interface.

Remarks

This template function copies one matrix to another, resizing the target matrix if required.

The items in the source matrix are transposed in the target matrix, such that n.at(i, j) = m.at(j, i).

Both matrices must support the imtx<T> interface. The matrixes do not need to be of the same type, but they should each have the same item type T.

Requirements

Header: plemtx.h

See Also

Matrix template functions


::mtx_copy<M, N>

Copy one matrix to another, resizing if required

void mtx_copy<M, N>(
   M& m,
   const N& n
);

Parameters

m

A reference to a target object of type M that supports the imtx<T> interface.
n

A reference to a source object of type N that supports the imtx<T> interface.

Remarks

This template function copies one matrix to another, resizing the target matrix if required.

Both matrices must support the imtx<T> interface. The matrixes do not need to be of the same type, but they should each have the same item type T.

Requirements

Header: plemtx.h

See Also

Matrix template functions


::mtx_flatten<M, V>

Copy the members of a matrix to a flattened vector

void mtx_flatten<M, V>(
   V& v,
   const M& n,
   int outer_dim
);

Parameters

v

A reference to a target vector containing items of type M::mtx_item_type.
n

A reference to a source object of type M that supports the imtx<T> interface.
outer_dim

The index of the dimension to be treated as the outer dimension in the target array. The only legal values are 0 and 1.

Remarks

This template function a matrix to a flattened array of items, contained in an std::vector<T> container.

The source matrix must support the imtx<T> interface.

Requirements

Header: plemtx.h

See Also

Matrix template functions


::mtx_transpose<M>

Transpose the rows and columns of a matrix

void mtx_transpose<M>(
   M& m
);

Parameters

m

A reference to an object of type M that supports the imtx<T> interface.

Remarks

This template function transposes the rows and columns of a matrix.

The items in the matrix are transposed, such that m.at(i, j) in the transposed matrix = m.at(j, i) in the original matrix.

Requirements

Header: plemtx.h

See Also

Matrix template functions


::ptrreader<M>

Create an instance of mtx_ptrreader

mtx_ptrreader<M> ptrreader<M>(
   const M& m
);

Parameters

m

A reference to an object of type M that supports the imtx<T> interface.

Return Value

An instance of mtx_ptrreader<M> for a matrix of type M.

Remarks

This template function creates an instance of mtx_ptrreader<M> to read the specified matrix.

Requirements

Header: plemtx.h

See Also

Matrix template functions


::ptrwriter<M>

Create an instance of mtx_ptrwriter

mtx_ptrwriter<M> ptrwriter<M>(
   M& m
);

Parameters

m

A reference to an object of type M that supports the imtx<T> interface.

Return Value

An instance of mtx_ptrwriter<M> for a matrix of type M.

Remarks

This template function creates an instance of mtx_ptrwriter<M> to read and write to the specified matrix.

Requirements

Header: plemtx.h

See Also

Matrix template functions


rtdhandles.h

Overview

rtdhandles.h contains classes and functions that support the use of object handles in Excel add-in functions.

Classes

The table below lists the principal C++ object classes declared in the header file.

Class | Description
HandleCache<T> | Manages object handles in Excel.
PersistentHandleCache<T> | Manages object handles in Excel, and allows the objects to be serialized to a persistent cache.
CHandleFormatter<T> | The class which converts handles to and from their display text. Classes can be derived from CHandleFormatter in order to implement the developer's own custom formats.

Functions

The table below lists the principal global functions declared in the header file.

Function | Description
CreateHandleInCache | Puts an object into the handle cache, creates a handle for it, and returns the new handle.
CopyHandleInCache | Increment the reference count of a handle already in the object cache.

A full list can be found here.

See Also

Object Handles


CHandleFormatter<T> Class

Converts an object handle to and from text.

class psl::rtd::CHandleFormatter<T>

Overview

Object handles, as implemented in RtdHandles.h, consist of a set of parts, separated by colons (or other separators), which combine to form a handle. The parts include:

  • A unique key, in the form of a GUID, e.g. {A6CBD52A-040D-4990-89EF-41A6721BADC6}.
  • State number, a long integer, e.g. 1280298484.

Using the default handle format, a handle looks like this:

{A6CBD52A-040D-4990-89EF-41A6721BADC6}:1280298484

Custom handle format

The developer can implement their own handle formatting class, and thereby take control of the appearance of the handle, by deriving a class from CHandleFormatter<T>.

For example, you can include the type, name and other details of the object being represented:

CustomThing:The name of the thing:{A6CBD52A-040D-4990-89EF-41A6721BADC6}:1280298484
YieldCurve:USD:Govt:{A6CBD52A-040D-4990-89EF-41A6721BADC6}:1280298484

This makes for much more user-friendly handles; it becomes much easier to understand the structure of a spreadsheet that uses handles, and to track down problems.

If you do not specify a separator, then a colon is used. If you have handles that need to include colons, you can specify a different separator by passing it to the constructor of the base class, e.g.:

YieldCurve~USD:Govt~{A6CBD52A-040D-4990-89EF-41A6721BADC6}~1280298484
YieldCurve/USD:Govt:Short/{A6CBD52A-040D-4990-89EF-41A6721BADC6}/1280298484

Derived classes

A class derived from CHandleFormatter<T> must implement the two conversion functions: MakeHandle and SplitHandle. If the class has a destructor, it must be declared as virtual.

Example

The example code below can be found in the RtdHandleDemo sample. Here is the simple object which will be used with a custom handle formatter:

CopyC++
class CustomThing {
public:
    CustomThing(const TCHAR* name_, int value_, double created_)
      : name(name_), value(value_), created(created_)
    {
    }
    std::tstring name;
    int value;
    double created;
};

We can define a custom handle formatter class, which create handles that include the target object's type and name, e.g.:

CustomThing/Gregory/{A6CBD52A-040D-4990-89EF-41A6721BADC6}/1280298484

The class implements the two required virtual methods, SplitHandle() and MakeHandle(). The code is based on the implementations in the base class, which can be found in include\XlRtdHandles\HandleFormatter.h.

In addition, the constructor passes a forward slash to the base class constructor, to be used as a separator character.

CopyC++
class CustomThingHandleFormatter : public psl::rtd::CHandleFormatter<CustomThing>
{
public:
    // The constructor specifies a forward slash as the separator character
    CustomThingHandleFormatter()
      : psl::rtd::CHandleFormatter<CustomThing>(_T('/'))
    {
    }
    virtual bool SplitHandle(const TCHAR* pszHandle, std::tstring& strKey, long& lState)
    {
        // Extract the required parts: the guid key and the state
        // which are at positions 2 & 3 respectively.
        // The base class method ExtractKeyAndState() method does all the work.

        return ExtractKeyAndState(pszHandle, strKey, lState, 2, 3);
    }
    virtual std::tstring MakeHandle(const CustomThing* t, const TCHAR* pszKey, long lState)
    {
        // Create a handle: [Class]/[Name]/[GUID]/[State]

        // This code is based on that in the parent class,
        // with an additional 2 key parts inserted at the start
        // of the handle.

        std::vector<std::tstring> parts;

        // 1st, the class
        parts.push_back(_T("CustomThing"));

        // 2nd, the name. Note that the base class
        // method Escape() is used to remove any separator characters.
        parts.push_back(Escape(t->name));

        // 3rd and fourth, the GUID and the state.
        // These two parts are required, but can be in any position.
        // We put them at the end of the handle, because they are not
        // interesting to the user, and we therefore do not care much
        // if they are not visible.
        parts.push_back(pszKey);
        parts.push_back(WriteState(lState));

        // Join the parts together and return the concatenated string.
        return Join(parts);
    }
};

Finally, in the OnXllOpen() event handler, we register the custom formatter with the single instance of HandleCache<CustomThing>:

CopyC++
BOOL CRtdHandleDemoApp::OnXllOpenEx()
{
    // Install the custom handle formatter, for CustomThings.
    psl::HandleCache<CustomThing>::GetOrCreateInstance()->SetFormatter(
        new CustomThingHandleFormatter());

    return TRUE;
}

Requirements

Header: rtdhandles.h
Namespace: psl::rtd

See Also

CHandleFormatter<T> Methods | rtdhandles.h | Custom handle formats (User Guide)


CHandleFormatter<T> Methods

The methods of the CHandleFormatter<T> class are listed here.

Construction

public method CHandleFormatter<T> Constructs a CHandleFormatter object

Conversion functions

public method | MakeHandle | Creates a handle for an object.
public method | SplitHandle | Parses a handle and returns the guid and state.

Helper methods

public method | Escape | Replaces any separator characters in a string with escapes.
public method | ExtractKeyAndState | Parses a handle composed of separated parts and extracts the key and state.
public method | Join | Joins a set of strings, using a specified character (by default, a colon) as separator.
public method | ReadState | Reads a state number from text.
public method | Split | Splits a handle into parts.
public method | WriteState | Writes a state number as text.

Requirements

Header: rtdhandles.h
Namespace: psl::rtd

See Also

CHandleFormatter<T> Class | rtdhandles.h | Custom handle formats (User Guide)


CHandleFormatter<T>::CHandleFormatter<T>

Constructs a CHandleFormatter object

CHandleFormatter<T>(
   TCHAR chSep = ':',
   TCHAR chEscape = '_'
);

Parameters

chSep

A character that will be used to separate the parts of a handle.
chEscape

A character that will be used to replace any occurrences of the separator character within the parts of a handle.

Requirements

Header: rtdhandles.h

See Also

CHandleFormatter<T> Class | CHandleFormatter<T> Methods


CHandleFormatter<T>::Escape

Replaces any separator characters in a string with escapes.

std::tstring Escape(
   const std::tstring& raw
);

Parameters

raw

A string, which may contain separator characters.

Return Value

Returns the input string, with each separator(by default, colon ':') replaced by an escape character (by default, an underscore '_').

Requirements

Header: rtdhandles.h

See Also

CHandleFormatter<T> Class | CHandleFormatter<T> Methods


CHandleFormatter<T>::ExtractKeyAndState

Parses a handle composed of separated parts and extracts the key and state.

bool ExtractKeyAndState(
   const TCHAR* pszHandle,
   std::tstring& strKey,
   long& lState,
   size_t nKeyPartIndex,
   size_t nStatePartIndex
);

Parameters

pszHandle

A handle, as displayed in an Excel cell. This should be composed of several parts, separated by colons (or another separator character if specified in the constructor). Two of the parts - the key and the state number - are compulsory, and their positions should be indicated by nKeyPartIndex and nStatePartIndex.

strKey

The key that is extracted from the handle is placed into strKey. The key is always in the form of a GUID, e.g.: {A6CBD52A-040D-4990-89EF-41A6721BADC6}.

The key is expected to be in the part indexed by nKeyPartIndex.
lState

The state number that is extracted from the handle is placed into lState. The state number is expected to be in the part indexed by nStatePartIndex.
nKeyPartIndex

The position of the key in the list of separated parts.
nStatePartIndex

The position of the state number in the list of separated parts.

Return Value

Returns true if the conversion succeeded, or false if the handle could not be successfully parsed.

Remarks

This helper method is used by the standard implementation of SplitHandle, and is recommended to be used by all derived classes as well.

The handle is split into parts, separated by the character specified in the constructor. Then the parts in the positions specified by nKeyPartIndex and nStatePartIndex are extracted, and the state number is parsed. If either part is missing, or the state number cannot be parsed, the function fails and returns false.

Requirements

Header: rtdhandles.h

See Also

CHandleFormatter<T> Class | CHandleFormatter<T> Methods


CHandleFormatter<T>::Join

Joins a set of strings, using a specified character (by default, a colon) as separator.

std::tstring Join(
   const std::vector<std::tstring>& parts
);

Parameters

parts

A vector of strings. Each of these will be concatenated, separated by the separator character specified to the constructor (by default, a colon). None of the part strings should contain the separator character.

Return Value

Returns a single string containing the concatenated parts, separated by the separator character specified in the constructor.

Requirements

Header: rtdhandles.h

See Also

CHandleFormatter<T> Class | CHandleFormatter<T> Methods | CHandleFormatter_Split


CHandleFormatter<T>::MakeHandle

Creates a handle for an object.

virtual std::tstring MakeHandle(
   const T* pObject,
   const TCHAR* pszKey,
   long lState
);

Parameters

pObject

The object whose handle is being created.

pszKey

The key that uniquely identifies the object. The key is always in the form of a GUID, e.g.: {A6CBD52A-040D-4990-89EF-41A6721BADC6}.

lState

The state number that specifies the stored state of the object.

Return Value

The function returns the handle as a text string. The handle must contain the key and the state, such that they can be extracted by SplitHandle.

Remarks

This method is called by the HandleCache<T> object when it converts creates a handle for a newly created object. The handle created must be of a form which can be parsed by SplitHandle, so that the key and the state can be extracted.

The default implementation returns the key and the state, joined by a colon. Implementations in derived classes can insert useful information into the handle, such as the type and the name.

Requirements

Header: rtdhandles.h

See Also

CHandleFormatter<T> Class | CHandleFormatter<T> Methods


CHandleFormatter<T>::ReadState

Reads a state number from text.

bool ReadState(
   const std::tstring& strState,
   long& lState
);

Parameters

strState

A string, which should contain a state number in decimal integer text format.

lState

The state number will be placed in lState if the conversion is successful.

Return Value

Returns true if the conversion succeeded, or false if the state string could not be successfully parsed.

Requirements

Header: rtdhandles.h

See Also

CHandleFormatter<T> Class | CHandleFormatter<T> Methods | CHandleFormatter_WriteState


CHandleFormatter<T>::Split

Splits a handle into parts.

int Split(
   const TCHAR* pszHandle,
   std::vector<std::tstring>& parts
);

Parameters

pszHandle

A string composed of several parts, separated by a specified character (by default, a colon).

parts

This should be reference to an empty vector of strings. The parts of the of the handle will be returned in this vector.

Return Value

Returns the number of parts that were extracted.

Requirements

Header: rtdhandles.h

See Also

CHandleFormatter<T> Class | CHandleFormatter<T> Methods | CHandleFormatter_Join


CHandleFormatter<T>::SplitHandle

Parses a handle and returns the guid and state.

virtual bool SplitHandle(
   const TCHAR* pszHandle,
   std::tstring& strKey,
   long& lState
);

Parameters

pszHandle

A handle, as displayed in an Excel cell.

strKey

The key that is extracted from the handle is placed into strKey. The key is always in the form of a GUID, e.g.: {A6CBD52A-040D-4990-89EF-41A6721BADC6}.

lState

The state number that is extracted from the handle is placed into lState.

Return Value

Returns true if the conversion succeeded, or false if the handle could not be successfully parsed.

Remarks

This method is called by the HandleCache<T> object when it converts a handle argument into a pointer to an object of type T.

Requirements

Header: rtdhandles.h

See Also

CHandleFormatter<T> Class | CHandleFormatter<T> Methods


CHandleFormatter<T>::WriteState

Writes a state number as text.

std::tstring WriteState(
   long lState
);

Parameters

lState

A state number, generated by the framework.

Return Value

Returns the state number as a decimal integer string.

Requirements

Header: rtdhandles.h

See Also

CHandleFormatter<T> Class | CHandleFormatter<T> Methods | CHandleFormatter_ReadState


HandleCache<T> Class

Manages object handles in Excel.

class psl::HandleCache<T>

Overview

The HandleCache<T> class holds a set of objects in memory and allows them to be represented in Excel as "handles". It actively manages the lifetime of the cached objects.

Instantiation

If a handle cache of the appropriate type for an object is not found at run-time, then it will be created when required, using the static method HandleCache<T>::GetOrCreateInstance.

However, if you choose to construct a HandleCache<T> object yourself, either as a global object or as a member of your application class, then that instance will be used, and no additional instances will be created.

Handle Format

RTD handles consist of a set of keys, combined to form a handle. The keys include:

  • Unique ID (GUID), e.g. {A6CBD52A-040D-4990-89EF-41A6721BADC6}.
  • State number, a long integer, e.g. 1280298484.

Using the default handle format, a handle looks like this:

{A6CBD52A-040D-4990-89EF-41A6721BADC6}:1280298484

The developer can implement their own handle formatting class, and thereby take control of the appearance of the handle, by deriving a class from CHandleFormatter<T>. See CHandleFormatter<T> for more details and an example of a custom formatter.

Requirements

Header: rtdhandles.h
Namespace: psl

See Also

HandleCache<T> Methods | rtdhandles.h


HandleCache<T> Methods

The methods of the HandleCache<T> class are listed here.

Construction

public method HandleCache<T> Constructs a HandleCache object

Singleton

GetInstance | Returns the single instance of this cache type.
GetOrCreateInstance | Returns the single instance of this cache type, creating one if none exists.

Handle functions

public method | CreateHandleInCache | Creates a new handle for the supplied pointer, and adds the pointer to the object cache.
public method | HandleToPtr | Converts a handle to a pointer to T.

Properties

public method SetFormatter Sets the specified formatter object to be the formatter for all handles in this cache.

Requirements

Header: rtdhandles.h
Namespace: psl

See Also

HandleCache<T> Class | rtdhandles.h


HandleCache<T>::CreateHandleInCache

Creates a new handle for the supplied pointer, and adds the pointer to the object cache.

std::tstring CreateHandleInCache(
   T* ptr
);
std::tstring CreateHandleInCache(
   RTDHANDLES_PTR_CLASS<T>& sptr
);

Parameters

ptr

A pointer to T. Once a pointer has been passed to CreateHandleInCache, the object pointed to is owned by the HandleCache, and will be deleted when it is no longer in use.

sptr

A smart pointer to T. Once a smart pointer has been passed to CreateHandleInCache, the object pointed to is partially owned by the HandleCache, and will be kept alive until it is no longer in use either by the object cache, or by the library which created the object.

Return Value

Returns the handle for the object, which should immediately be returned to Excel as the result of a handle creator function.

Requirements

Header: rtdhandles.h

See Also

HandleCache<T> Class | HandleCache<T> Methods


HandleCache<T>::GetInstance

Returns the single instance of this cache type.

static HandleCache<T> GetInstance( );

Return Value

The function returns a pointer to the single instance of the cache for type T. If no instance exists, then an exception of type CXlRuntimeException is thrown.

Requirements

Header: rtdhandles.h

See Also

HandleCache<T> Class | HandleCache<T> Methods


HandleCache<T>::GetOrCreateInstance

Returns the single instance of this cache type, creating one if none exists.

static HandleCache<T> GetOrCreateInstance( );

Return Value

The function returns a pointer to the single instance of the cache for type T. If no instance yet exists, then a cache of type HandleCache<T> is created.

Requirements

Header: rtdhandles.h

See Also

HandleCache<T> Class | HandleCache<T> Methods


HandleCache<T>::HandleCache<T>

Constructs a HandleCache object

HandleCache<T>(
   CHandleFormatter<T>* formatter = 0
);

Parameters

formatter

A pointer to an object derived from CHandleFormatter<T>. If set to 0, then a default formatter will be created.

Remarks

Once the object has been passed to the constructor, the object is owned by the HandleCache, and will be deleted by it at the appropriate time. The developer should not delete instances of formatters that have been passed to the constructor. The developer should not create instances of formatters on the stack; they must be created on the heap, using new.

Requirements

Header: rtdhandles.h

See Also

HandleCache<T> Class | HandleCache<T> Methods


HandleCache<T>::HandleToPtr

Converts a handle to a pointer to T.

bool HandleToPtr(
   const CString& handle,
   T*& ptr
);

Parameters

handle

A handle, as displayed in an Excel cell.

ptr

If the conversion succeeds, and the handle refers to a valid object, then ptr will be set to point to the object.

Return Value

Returns true if the conversion succeeded, or false if the handle could not be successfully parsed, or referred to an invalid object.

Requirements

Header: rtdhandles.h

See Also

HandleCache<T> Class | HandleCache<T> Methods


HandleCache<T>::SetFormatter

Sets the specified formatter object to be the formatter for all handles in this cache.

int SetFormatter(
   CHandleFormatter<T>* formatter
);

Parameters

formatter

A pointer to an object derived from CHandleFormatter<T>*.

Remarks

Once the object has been passed to SetFormatter(), the object is owned by the HandleCache, and will be deleted by it at the appropriate time. The developer should not delete instances of formatters that have been passed to SetFormatter(). The developer should not create instances of formatters on the stack; they must be created on the heap, using new.

Requirements

Header: rtdhandles.h

See Also

HandleCache<T> Class | HandleCache<T> Methods


PersistentHandleCache<T> Class

Manages object handles in Excel, and allows the objects to be serialized to a persistent cache.

class psl::PersistentHandleCache<T> : public HandleCache

Overview

The PersistentHandleCache<T> class is derived from HandleCache<T>, and adds the capbility to save the objects and their handles to persistent disk storage.

For a disussion of the use of PersistentHandleCache<T>, see Persistent object handles in the User Guide.

Instantiation

Only a single instance of a cache derived from HandleCache<T> is allowed to exist. So, if an instance of PersistentHandleCache<T> is instantiated, no further caches will be created at run-time.

Requirements

Header: rtdhandles.h
Namespace: psl

See Also

PersistentHandleCache<T> Methods | rtdhandles.h


PersistentHandleCache<T> Methods

The methods of the PersistentHandleCache<T> class are listed here.

Construction

public method PersistentHandleCache<T> Constructs a PersistentHandleCache object

Operations

public method | Restore | Restores the object cache from persistent storage.
public method | Save | Saves the object cache to persistent storage.

Properties

public method | GetAutoSave | Returns the value of the AutoSave property.
public method | GetDataFile | Returns the value of the DataFile property.
public method | GetMaxSavedItemAge | Returns the value of the MaxSavedItemAge property.
public method | GetMaxSavedItemCount | Returns the value of the MaxSavedItemCount property.
public method | SetAutoSave | Sets the value of the AutoSave property.
public method | SetDataFile | Sets the value of the DataFile property.
public method | SetMaxSavedItemAge | Sets the value of the MaxSavedItemAge property.
public method | SetMaxSavedItemAgeDays | Sets the value of the MaxSavedItemAge property.
public method | SetMaxSavedItemCount | Sets the value of the MaxSavedItemCount property.

Services

public method ExpandDataFile Returns the expanded path to the persistent storage.

Methods of HandleCache<T>

Requirements

Header: rtdhandles.h
Namespace: psl

See Also

PersistentHandleCache<T> Class | rtdhandles.h


PersistentHandleCache<T>::ExpandDataFile

Returns the expanded path to the persistent storage.

bool ExpandDataFile(
   std::tstring& strDataFile
) const;

Parameters

strDataFile

strDataFile will be filled with the full path to the file to be used for persistent storage. If the DataFile property includes environmment variables such as %TMP%, these will be expanded.

Return Value

Returns true if the expansion succeeds, false if it fails. It will always fail if the DataFile property is empty.

Requirements

Header: rtdhandles.h

See Also

PersistentHandleCache<T> Class | PersistentHandleCache<T> Methods | GetDataFile


PersistentHandleCache<T>::GetAutoSave

Returns the value of the AutoSave property.

bool GetAutoSave( ) const;

Requirements

Header: rtdhandles.h

See Also

PersistentHandleCache<T> Class | PersistentHandleCache<T> Methods | SetAutoSave


PersistentHandleCache<T>::GetDataFile

Returns the value of the DataFile property.

std::tstring GetDataFile( ) const;

Return Value

The full path to the file to be used for persistent storage. The path may include environmment variables such as %TMP%, which will be expanded when the file is opened.

Requirements

Header: rtdhandles.h

See Also

PersistentHandleCache<T> Class | PersistentHandleCache<T> Methods | SetDataFile | ExpandDataFile


PersistentHandleCache<T>::GetMaxSavedItemAge

Returns the value of the MaxSavedItemAge property.

long GetMaxSavedItemAge( ) const;

Return Value

The maximum age of an object in seconds. Any objects which have been unused for this time or longer will be purged from the cache when it is saved. If the value is 0 or negative, then objects will not be limited with regard to age.

Requirements

Header: rtdhandles.h

See Also

PersistentHandleCache<T> Class | PersistentHandleCache<T> Methods | SetMaxSavedItemAge


PersistentHandleCache<T>::GetMaxSavedItemCount

Returns the value of the MaxSavedItemCount property.

long GetMaxSavedItemCount( ) const;

Return Value

The maximum number of objects that will ever be saved to the persistent storage. If the value is 0 or negative, then the file will be of unlimited size.

Requirements

Header: rtdhandles.h

See Also

PersistentHandleCache<T> Class | PersistentHandleCache<T> Methods | SetMaxSavedItemCount


PersistentHandleCache<T>::PersistentHandleCache<T>

Constructs a PersistentHandleCache object

PersistentHandleCache<T>(
   CHandleFormatter<T>* formatter = 0,
   const TCHAR* pszDataFile,
   long lMaxSavedItemCount,
   long lMaxSavedItemAge,
   bool bAutoSave = true,
   long lVersion = 1
);

Parameters

formatter

A pointer to an object derived from CHandleFormatter<T>. If set to 0, then a default formatter will be created.

Once the object has been passed to the constructor, the object is owned by the HandleCache, and will be deleted by it at the appropriate time. The developer should not delete instances of formatters that have been passed to the constructor. The developer should not create instances of formatters on the stack; they must be created on the heap, using new.

pszDataFile

The full path to the file to be used for persistent storage. The path may include environmment variables such as %TMP%, which will be expanded when the file is opened.

lMaxSavedItemCount

The maximum number of objects that will ever be saved to the persistent storage. If the value is 0 or negative, then the file will be of unlimited size.

lMaxSavedItemAge

The maximum age of an object in seconds. Any objects which have been unused for this time or longer will be purged from the cache when it is saved. If the value is 0 or negative, then objects will not be limited with regard to age.

bAutoSave

If true, then the cache will automatically be restored when the XLL is opened, and saved when the XLL is closed. if false, then the developer is responsible for restoring and saving the cache, by calling the Save and Restore methods.

lVersion

If a cache file exists, and the saved version number does not match the value provided, then the cache file will be ignored, and will not be restored. When the cache is next saved, the contents of the existing file will be discarded.

You should increment this number whenever you change the serialization code for stored objects. This will safely invalidate existing caches in the old format, removing the need to individually delete them.

Requirements

Header: rtdhandles.h

See Also

PersistentHandleCache<T> Class | PersistentHandleCache<T> Methods


PersistentHandleCache<T>::Restore

Restores the object cache from persistent storage.

void Restore( );

Requirements

Header: rtdhandles.h

See Also

PersistentHandleCache<T> Class | PersistentHandleCache<T> Methods


PersistentHandleCache<T>::Save

Saves the object cache to persistent storage.

void Save( );

Requirements

Header: rtdhandles.h

See Also

PersistentHandleCache<T> Class | PersistentHandleCache<T> Methods


PersistentHandleCache<T>::SetAutoSave

Sets the value of the AutoSave property.

void SetAutoSave(
   bool bAutoSave
);

Parameters

bAutoSave

If true, then the cache will automatically be restored when the XLL is opened, and saved when the XLL is closed. if false, then the developer is responsible for restoring and saving the cache, by calling the Save and Restore methods.

Requirements

Header: rtdhandles.h

See Also

PersistentHandleCache<T> Class | PersistentHandleCache<T> Methods | GetAutoSave


PersistentHandleCache<T>::SetDataFile

Sets the value of the DataFile property.

void SetDataFile(
   const std::tstring& strDataFile
);

Parameters

strDataFile

The full path to the file to be used for persistent storage. The path may include environmment variables such as %TMP%, which will be expanded when the file is opened.

Requirements

Header: rtdhandles.h

See Also

PersistentHandleCache<T> Class | PersistentHandleCache<T> Methods | GetDataFile | ExpandDataFile


PersistentHandleCache<T>::SetMaxSavedItemAge

Sets the value of the MaxSavedItemAge property.

void SetMaxSavedItemAge(
   long lSeconds
);

Parameters

lSeconds

The maximum age of an object in seconds. Any objects which have been unused for this time or longer will be purged from the cache when it is saved. If the value is 0 or negative, then objects will not be limited with regard to age.

Requirements

Header: rtdhandles.h

See Also

PersistentHandleCache<T> Class | PersistentHandleCache<T> Methods | SetMaxSavedItemAgeDays | GetMaxSavedItemAge


PersistentHandleCache<T>::SetMaxSavedItemAgeDays

Sets the value of the MaxSavedItemAge property.

void SetMaxSavedItemAgeDays(
   long lDays
);

Parameters

lDays

The maximum age of an object in days. Any objects which have been unused for this time or longer will be purged from the cache when it is saved. If the value is 0 or negative, then objects will not be limited with regard to age.

Requirements

Header: rtdhandles.h

See Also

PersistentHandleCache<T> Class | PersistentHandleCache<T> Methods | SetMaxSavedItemAge | GetMaxSavedItemAge


PersistentHandleCache<T>::SetMaxSavedItemCount

Sets the value of the MaxSavedItemCount property.

void SetMaxSavedItemCount(
   long lMaxSavedItemCount
);

Parameters

lMaxSavedItemCount

The maximum number of objects that will ever be saved to the persistent storage. If the value is 0 or negative, then the file will be of unlimited size.

Requirements

Header: rtdhandles.h

See Also

PersistentHandleCache<T> Class | PersistentHandleCache<T> Methods | GetMaxSavedItemCount


Global Handle Functions

Global Handle Functions are listed here.

Handle functions

public method | AddHandleDeleteActionToCache | Add an action to be executed when the spoecified object handle is deleted.
public method | CopyHandleInCache | Increment the reference count of a handle already in the object cache.
public method | CreateHandleInCache | Create a handle, add it to the object cache, and return the handle

Requirements

Header: rtdhandles.h
Namespace: psl

See Also

rtdhandles.h


psl::AddHandleDeleteActionToCache

Add an action to be executed when the spoecified object handle is deleted.

template< class T >
void AddHandleDeleteActionToCache(
   const CXlOper& xloHandle,
   IXlRtdCacheDeleteAction* action
);

Parameters

xloHandle

A CXlOper value containing a valid string handle.

action

A pointer to an object derived from IXlRtdCacheDeleteAction.

Remarks

The add-in function that contains the call should be marked as a Handle Creator function. This method is used by code generated by the XLL+ Function Wizard; it should not normally be used directly by developers.

Implementation

HandleCache<T> AddHandleDeleteActionToCache

Requirements

Header: rtdhandles.h

See Also

Global Handle Functions | Object Handles (User Guide)


psl::CopyHandleInCache

Increment the reference count of a handle already in the object cache.

template< class T >
void CopyHandleInCache(
   const CXlOper& xloHandle
);

Parameters

xloHandle

A CXlOper value containing a valid string handle.

Remarks

The add-in function that contains the call should be marked as a Handle Creator function. This method is used by code generated by the XLL+ Function Wizard; it should not normally be used directly by developers.

Implementation

HandleCache<T> CopyHandleInCache

Requirements

Header: rtdhandles.h

See Also

Global Handle Functions | Object Handles (User Guide)


psl::CreateHandleInCache

Create a handle, add it to the object cache, and return the handle

template< class T >
std::tstring CreateHandleInCache(
   T* ptr
);
template< class T >
std::tstring CreateHandleInCache(
   RTDHANDLES_PTR_CLASS<T>& sptr
);

Parameters

ptr

A pointer to an instance of type T.

sptr

A smart pointer to T. Once a smart pointer has been passed to CreateHandleInCache, the object pointed to is partially owned by the HandleCache, and will be kept alive until it is no longer in use either by the object cache, or by the library which created the object.

Return Value

Returns a string handle, which can be displayed in Excel as a value, and which can be passed to functions which accept object handles of type T.

Remarks

The add-in function that contains the call should be marked as a Handle Creator function. The value returned by this method should usually be returned immediately to Excel, e.g.:

CopyC++
Thing* thing = new Thing(Name, Value, CXlDate::Now());
xloResult = psl::CreateHandleInCache(thing);
return xloResult.Ret();

Implementation

HandleCache<T> CreateHandleInCache

Requirements

Header: rtdhandles.h

See Also

Global Handle Functions | Object Handles (User Guide)


rtdhandleslock.h

Overview

rtdhandleslock.h contains specialized classes that allow RTD handles to be explicitly locked in order to extend and control their lifetime.

Classes

The table below lists the principal C++ object classes declared in the header file.

Class | Description
LockableHandleCache<T> | Manages object handles in Excel.

See Also

Object Handles


LockableHandleCache<T> Class

Manages object handles in Excel and allows explicit extension of handle lifetimes.

class psl::LockableHandleCache<T>

Overview

The LockableHandleCache<T> class is a specialized handle cache which can be used in place of HandleCache<T>. Like HandleCache<T>, it actively manages the lifetime of the cached objects, but it also allows the developer to lock handles into memory, so that they are only deleted when they are explicitly unlocked by code.

This form of cache allows developers to create and control object handles from VBA code (or other automation code).

Use pattern

  1. To use this cache, the developer should instantiate it explicitly in global scope. Otherwise a cache of the base type HandleCache<T> will be created at run-time.

    CopyC++
    LockableHandleCache<Thing> theLockableThingCache;

  2. In order to allow automation code to lock a handle, create an XLL add-in function that takes a string handle as its only argument. In this function, create a lock token using the cache's LockHandle method, and return the token as the result of the function.

    CopyC++
    CXlOper* LockThingHandle_Impl(CXlOper& xloResult, const CXlStringArg& t_op)
{
    // Input buffers
    const Thing* t;
    // Validate and translate inputs
    XlReadScalarEx(t_op, t, psl::HandleConverter<Thing >(), CScalarConvertParams
        <const Thing*>(L"t", 0, 0, -1).SetStringParam(0, L"Thing"));
    // End of generated code
//}}XLP_SRC

    xloResult = theLockableThingCache.LockHandle(t_op);
    return xloResult.Ret();
}

  3. When calling add-in functions that expect an RTD handle from automation, pass the token in place of the handle.

  4. Author another XLL add-in function that uses the cache's UnlockHandle method.

    CopyC++
    CXlOper* UnlockThingHandle_Impl(CXlOper& xloResult, const CXlStringArg& token)
{
    // End of generated code
//}}XLP_SRC
    theLockableThingCache.UnlockHandle(token);
    return xloResult.Ret();
}

    When the lock is no longer required, call this add-in function from the automation code, passing the token.

    The object referred to by the handle is available for destruction when the last token is unlocked, and Excel has stopped using the handle.

See the LockableHandles sample project for an example of the class in use.

Requirements

Header: rtdhandleslock.h
Namespace: psl

See Also

LockableHandleCache<T> Methods | rtdhandleslock.h | LockableHandles Sample


LockableHandleCache<T> Methods

The methods of the LockableHandleCache<T> class are listed here.

Construction

public method LockableHandleCache<T> Constructs a LockableHandleCache object

Locking

public method | LockHandle | Returns a lock token for a handle
public method | UnlockHandle | Unlocks a handle previously locked using LockHandle

Requirements

Header: rtdhandleslock.h
Namespace: psl

See Also

LockableHandleCache<T> Class | rtdhandleslock.h | LockableHandles Sample


LockableHandleCache<T>::LockableHandleCache<T>

Constructs a LockableHandleCache object

LockableHandleCache<T>(
   CHandleFormatter<T>* formatter = 0,
   TCHAR sep = ':'
);

Parameters

formatter

A pointer to an object derived from CHandleFormatter<T>. If set to 0, then a default formatter will be created.

sep

The separator which will be used to separate the handle and the extra data added from the lock token. This should be the same as the separator used for the handle formatter. Set it to ':' to imitate the default handle formatter.

Remarks

Once the formatter object has been passed to the constructor, the object is owned by the HandleCache, and will be deleted by it at the appropriate time. The developer should not delete instances of formatters that have been passed to the constructor. The developer should not create instances of formatters on the stack; they must be created on the heap, using new.

Requirements

Header: rtdhandleslock.h

See Also

LockableHandleCache<T> Class | LockableHandleCache<T> Methods


LockableHandleCache<T>::LockHandle

Returns a lock token for a handle

CString LockHandle(
   const TCHAR* pszHandle
);

Parameters

pszHandle

A handle, as displayed in an Excel cell.

Return Value

A string lock token, which can be used in place of the handle itself when instantiating objects from handles.

Remarks

Locks a handle, returning a token. The object referred to by the handle will stay in scope at least until the token is released with UnlockHandle().

Requirements

Header: rtdhandleslock.h

See Also

LockableHandleCache<T> Class | LockableHandleCache<T> Methods


LockableHandleCache<T>::UnlockHandle

Unlocks a handle previously locked using LockHandle

bool UnlockHandle(
   const TCHAR* pszToken
);

Parameters

pszToken

A token previously returned by LockHandle.

Return Value

The function returns true if the operation succeeded; false if it failed. Failure can occur if the token is invalid.

Remarks

The object referred to by the handle is available for destruction when the last token is unlocked, and Excel has stopped using the handle.

Requirements

Header: rtdhandleslock.h

See Also

LockableHandleCache<T> Class | LockableHandleCache<T> Methods


rtdlink.h

Overview

rtdlink.h contains classes and functions that implement the XLL+ asynchronous function mechanism.

For more information, see Asynchronous functions in the User Guide.

Classes

The table below lists the public C++ object classes declared in the header file.

Class | Description
CRtdAsyncManager | Provides access to the asynchronous function API, allowing the developer to control the background threads.
CRtdLink | Supports implementations of asynchronous functions developed under older versions of XLL+.


CRtdAsyncManager Class

Provides access to the asynchronous function API, allowing the developer to control the background threads.

class CRtdAsyncManager

Overview

The CRtdAsyncManager class manages the execution of asynchronous worksheet functions. These functions return #WAIT! when they are initially calculated, and start a task in a background (worker) thread. When the task is complete, the Excel RTD mechanism is used to inform Excel that the cell should be recalculated; the final result is then returned to Excel.

Usage

The object should not be created directly. A single instance of the class is created on demand by the method CXllApp::GetRtdAsyncManager().

Once you have retrieved a pointer to the CRtdAsyncManager instance, you can set the maximum number of threads used by the asynchronous function mechanism with the SetMaxThreads() method. During operation, you can use Stop() and Start() to control the worker threads.

Requirements

Header: rtdlink.h

See Also

CRtdAsyncManager Methods | rtdlink.h | CRtdLink object


CRtdAsyncManager Methods

The methods of the CRtdAsyncManager class are listed here.

Operations

public method | Start | Allocates the background threads and starts any queued tasks.
public method | Stop | Kills any running threads and queues tasks until Start is called.

Properties

public method | GetMaxThreads | Gets the maximum number of background threads that will be used to run asynchronous functions.
public method | GetWaitMessage | Gets the message returned by incomplete asynchronous functions.
public method | SetMaxThreads | Sets the maximum number of background threads that will be used to run asynchronous functions.
public method | SetWaitMessage | Sets the message returned by incomplete asynchronous functions.

Construction

public method CRtdAsyncManager Constructs a CRtdAsyncManager object

Requirements

Header: rtdlink.h

See Also

CRtdAsyncManager Class | rtdlink.h | CRtdLink object


CRtdAsyncManager::CRtdAsyncManager

Constructs a CRtdAsyncManager object

CRtdAsyncManager( );

Requirements

Header: rtdlink.h

See Also

CRtdAsyncManager Class | CRtdAsyncManager Methods


CRtdAsyncManager::GetMaxThreads

Gets the maximum number of background threads that will be used to run asynchronous functions.

size_t GetMaxThreads( );

Return Value

Returns the maximum number of threads.

Requirements

Header: rtdlink.h

See Also

CRtdAsyncManager Class | CRtdAsyncManager Methods


CRtdAsyncManager::GetWaitMessage

Gets the message returned by incomplete asynchronous functions.

LPCTSTR GetWaitMessage( );

Return Value

Returns a pointer to the string that will be returned by all incomplete asynchronous functions.

Requirements

Header: rtdlink.h

See Also

CRtdAsyncManager Class | CRtdAsyncManager Methods


CRtdAsyncManager::SetMaxThreads

Sets the maximum number of background threads that will be used to run asynchronous functions.

void SetMaxThreads(
   size_t maxThreads
);

Parameters

maxThreads

The maximum number of threads that will be used by for asynchronous functions.

If the value is 0 then an exception of type CXlOutOfRangeException will be thrown.

Remarks

If Start has already been called, then SetMaxThreads will fail and an exception of type CXlRuntimeException will be thrown.

Requirements

Header: rtdlink.h

See Also

CRtdAsyncManager Class | CRtdAsyncManager Methods


CRtdAsyncManager::SetWaitMessage

Sets the message returned by incomplete asynchronous functions.

void SetWaitMessage(
   const TCHAR* waitMessage
);

Parameters

waitMessage

The string that will be returned by all incomplete asynchronous functions.

If the value is blank then a default value will be used. This is "#WAIT!" in English and a similar value in other supported run-time languages.

Requirements

Header: rtdlink.h

See Also

CRtdAsyncManager Class | CRtdAsyncManager Methods


CRtdAsyncManager::Start

Allocates the background threads and starts any queued tasks.

void Start( );

Requirements

Header: rtdlink.h

See Also

CRtdAsyncManager Class | CRtdAsyncManager Methods


CRtdAsyncManager::Stop

Kills any running threads and queues tasks until Start is called.

void Stop( );

Requirements

Header: rtdlink.h

See Also

CRtdAsyncManager Class | CRtdAsyncManager Methods


CRtdLink Class

Proxy class that supports the asynchronous function implementation of older XLL+ versions.

class CRtdLink

Overview

The CRtdLink class was used by XLL+ version 6 and below. An instance of the class was inserted into the project's application class. As of XLL+ version 7, the CRtdAsyncManager is used instead. An instance of this class is created, on demand, inside the application class base class, CXllApp.

This deprecated class merely acts as a proxy for the instance of CRtdAsyncManager contained by the base class.

Requirements

Header: rtdlink.h

See Also

CRtdLink Methods | rtdlink.h | CRtdAsyncManager object


CRtdLink Methods

The methods of the CRtdLink class are listed here.

Construction

public method CRtdLink Constructs a CRtdLink object

Operations

public method | Start | Allocates the background threads and starts any queued tasks.
public method | Stop | Kills any running threads and queues tasks until Start is called.

Properties

public method GetWaitMessage Gets the message returned by incomplete asynchronous functions.

Requirements

Header: rtdlink.h

See Also

CRtdLink Class | rtdlink.h | CRtdAsyncManager object


CRtdLink::CRtdLink

Constructs a CRtdLink object

CRtdLink(
   size_t maxThreads = 4,
   const TCHAR* waitMessage = _T("")
);

Parameters

maxThreads

The maximum number of threads that will be used by for asynchronous functions.

If the value is 0 then an exception of type CXlOutOfRangeException will be thrown.

waitMessage

The string that will be returned by all incomplete asynchronous functions.

If the value is blank then a default value will be used. This is "#WAIT!" in English and a similar value in other supported run-time languages.

Remarks

The parameter values passed to this constructor will be applied to the CRtdAsyncManager object owned by the base class.

Requirements

Header: rtdlink.h

See Also

CRtdLink Class | CRtdLink Methods


CRtdLink::GetWaitMessage

Gets the message returned by incomplete asynchronous functions.

LPCTSTR GetWaitMessage( );

Return Value

Returns a pointer to the string that will be returned by all incomplete asynchronous functions.

Requirements

Header: rtdlink.h

See Also

CRtdLink Class | CRtdLink Methods


CRtdLink::Start

Allocates the background threads and starts any queued tasks.

void Start( );

Requirements

Header: rtdlink.h

See Also

CRtdLink Class | CRtdLink Methods


CRtdLink::Stop

Kills any running threads and queues tasks until Start is called.

void Stop( );

Requirements

Header: rtdlink.h

See Also

CRtdLink Class | CRtdLink Methods


xldialog.h

Overview

xldialog.h contains classes that support native Excel dialogs.

The API is modelled as far is as possible on the MFC CDialog class, but with some substantial differences that reflect the more limited functionality of native Excel dialogs.

Classes

The main classes in xldialog.h are as follows:

Class | Purpose
CXlDialog | Dialog object. The developer may choose to inherit their own class from CXlDialog, and override the event handler methods.
CXlControl | Push-button. Default action is to dismiss the dialog with a result code of TRUE, but the event can be trapped by overriding the OnOK() virtual method.

Controls

Each control on a dialog is of a class descended from CXlControl. The following control types are supported:

Class | Purpose
CXlControlOK | Push-button. Default action is to dismiss the dialog with a result code of TRUE, but the event can be trapped by overriding the OnOK() virtual method.
CXlControlCancel | Push-button. Action is always to dismiss the dialog, with a result code of FALSE.
CXlControlStatic | Static text field.
CXlControlTextEdit | Text edit field. May contain any text.
CXlControlIntegerEdit | Integer edit field. An error message is displayed if the user enters anything but an integer.
CXlControlNumberEdit | Number edit field. An error message is displayed if the user enters anything but an number (integer or floating-point).
CXlControlFormulaEdit | Formula edit field. The user can enter formula by typing or by selecting cells, as in the Excel formula bar.
CXlControlRefEdit | Reference edit field. The user can enter an address by typing, or by selecting cells.
CXlControlOption | Option button. Only one button in a group may be selected at any time. Selecting an option causes the overrideable event handler OnOption() to be called.
CXlControlOptionGroup | Option button group. This invisible control is used to group together a sequence of option buttons.
CXlControlCheckBox | Check-box. The user may click on the button to toggle its state between checked and unchecked. Checking a box causes the overrideable event handler OnCheckBox() to be called.
CXlControlGroupBox | Static group box.
CXlControlListBox | List box. The control is a single-selection list-box, and its API is modelled on that of the MFC class CListBox. Changing the selection causes the overrideable event handler OnListBox() to be called.
CXlControlIcon | Icon image. The image may only be one of the three standard message box icons.

See Also

CXlDialog object | CXlControl object


CXlControl Class

Base class for all the controls supported by CXlDialog.

class CXlControl

Overview

The CXlControl class is the base class for all the controls supported by CXlDialog.

The following classes are descended from CXlControl:

  • CXlControlOK
  • CXlControlCancel
  • CXlControlStatic
  • CXlControlTextEdit
  • CXlControlIntegerEdit
  • CXlControlNumberEdit
  • CXlControlFormulaEdit
  • CXlControlRefEdit
  • CXlControlOption
  • CXlControlOptionGroup
  • CXlControlCheckBox
  • CXlControlGroupBox
  • CXlControlListBox
  • CXlControlIcon

Requirements

Header: xldialog.h

See Also

CXlControl Methods | xldialog.h | CXlDialog object


CXlControl Methods

The methods of the CXlControl class are listed here.

Construction

public method CXlControl Constructs a CXlControl object, without displaying it

Common data functions

public method | GetID | Returns the ID of the control
public method | GetText | Returns the text of the control
public method | GetValue | Returns the text value of the control
public method | SetID | Sets the ID of the control
public method | SetText | Sets the text of the control
public method | SetValue | Sets the string value of the control

State functions

public method | GetEnabled | Returns the enabled state of the control
public method | GetTrigger | Returns the trigger state of the control
public method | GetVisible | Returns the visible state of the control
public method | SetEnabled | Sets the enabled state of the control
public method | SetTrigger | Sets the trigger state of the control
public method | SetVisible | Sets the visible state of the control

Position functions

public method | GetHeight | Returns the height of the control
public method | GetLeft | Returns the horizontal position of the control
public method | GetTop | Returns the vertical position of the control
public method | GetWidth | Returns the width of the control
public method | SetPos | Sets the position and optinally the size of the control
public method | SetSize | Sets the size of the control

Requirements

Header: xldialog.h

See Also

CXlControl Class | xldialog.h | CXlDialog object


CXlControl::CXlControl

Constructs a CXlControl object, without displaying it

CXlControl(
   UINT id,
   USHORT nType,
   const char* pszText,
   USHORT x,
   USHORT y,
   USHORT cx,
   USHORT cy
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
nType

Control type.
pszText

Control text, if any.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

The constructor is protected. Only classes descended from CXlControl may be instantiated.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::GetEnabled

Returns the enabled state of the control

bool GetEnabled( ) const;

Remarks

Returns the enabled state of the control. If true, the control will be black and, if appropriate, may be edited. If false, then the control will be greyed out and read-only.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::GetHeight

Returns the height of the control

USHORT GetHeight( ) const;

Remarks

Returns the height of the control.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::GetID

Returns the ID of the control

UINT GetID( ) const;

Remarks

Returns the identifier of the control.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::GetLeft

Returns the horizontal position of the control

USHORT GetLeft( ) const;

Remarks

Returns the horizontal position of the control.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::GetText

Returns the text of the control

CString GetText( ) const;

Remarks

Returns the text of the control. For some controls, including all edit fields, the text is always blank.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::GetTop

Returns the vertical position of the control

USHORT GetTop( ) const;

Remarks

Returns the vertical position of the control.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::GetTrigger

Returns the trigger state of the control

bool GetTrigger( ) const;

Remarks

Returns the trigger state of the control. If true, then changes to the control will cause the appropriate event-handler to be invoked. If false, then changes will not invoke an event-handler.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::GetValue

Returns the text value of the control

CString GetValue( ) const;

Remarks

Returns the value of the control. For some controls, including static fields, the value is always blank.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::GetVisible

Returns the visible state of the control

bool GetVisible( ) const;

Remarks

Returns the visible state of the control. If true, then the control will be visible. If false, the control will be hidden from the user.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::GetWidth

Returns the width of the control

USHORT GetWidth( ) const;

Remarks

Returns the width of the control.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::SetEnabled

Sets the enabled state of the control

void SetEnabled(
   bool bEnabled
);

Parameters

bEnabled

true to enable the control; false to disable it.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::SetID

Sets the ID of the control

void SetID(
   UINT id
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.

Remarks

Sets the identifier of the control. The ID does not need to be unique, but if it is not unique then CXlDialog::ControlFromID() cannot be used to retrieve the address of the control.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::SetPos

Sets the position and optinally the size of the control

void SetPos(
   USHORT x,
   USHORT y,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

x

Coordinate of left side of control.
y

Coordinate of top of control.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

Sets the position and optionally the size of the control. Note that zero values for x, y, cx and cy will result in the default position and/or size being applied.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::SetSize

Sets the size of the control

void SetSize(
   USHORT cx,
   USHORT cy
);

Parameters

cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

Sets the size of the control. Note that zero values for cx and cy will result in the default size being applied.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::SetText

Sets the text of the control

void SetText(
   const char* pszText
);

Parameters

pszText

Text of the control.

Remarks

Sets the text of the control. For some controls, including all edit fields, the text is ignored.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::SetTrigger

Sets the trigger state of the control

void SetTrigger(
   bool bTrigger
);

Parameters

bTrigger

If bTrigger is true, then any changes to the control will cause an event-handler to be called. If it is false, then changes will not invoke an event-handler.

Remarks

Sets the trigger state of the control. If true, then changes to the control will cause the appropriate event-handler to be invoked. If false, then changes will not invoke an event-handler.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::SetValue

Sets the string value of the control

void SetValue(
   const char* pszText
);

Parameters

pszText

Value of the control as a string.

Remarks

Sets the value of the control. For some controls, including static fields, the value is ignored.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControl::SetVisible

Sets the visible state of the control

void SetVisible(
   bool bVisible
);

Parameters

bVisible

true to show the control; false to hide it.

Remarks

Sets the visible state of the control. If true, then the control will be visible. If false, the control will be hidden from the user.

Requirements

Header: xldialog.h

See Also

CXlControl Class | CXlControl Methods


CXlControlCancel Class

Push-button class supported by CXlDialog.

class CXlControlCancel : public CXlControl

Overview

The CXlControlCancel class instantiates a push-button. If it is pushed during CDialog::Show() then the dialog will be closed and Show() will return FALSE.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlCancel Methods | xldialog.h | CXlDialog object | CXlControl object


CXlControlCancel Methods

The methods of the CXlControlCancel class are listed here.

Construction

public method CXlControlCancel Constructs a CXlControlCancel object, without displaying it

Property functions

public method | GetDefault | Returns whether the button is triggered by the Escape key
public method | SetDefault | Sets whether the button is triggered by the Escape key

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlCancel Class | xldialog.h | CXlDialog object | CXlControl object


CXlControlCancel::CXlControlCancel

Constructs a CXlControlCancel object, without displaying it

CXlControlCancel(
   UINT id = -1,
   const char* pszText = 0,
   USHORT x = 0,
   USHORT y = 0,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
pszText

Button text. If 0, then "Cancel" will be used.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

This constructor creates a push-button. When the user presses it the dialog will be closed and Show() will return FALSE.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlCancel Class | CXlControlCancel Methods


CXlControlCancel::GetDefault

Returns whether the button is triggered by the Escape key

bool GetDefault( ) const;

Remarks

Returns the default state of the control. If true, then the button will be deemed to have been pressed whenever the user presses the Escape key.

Requirements

Header: xldialog.h

See Also

CXlControlCancel Class | CXlControlCancel Methods


CXlControlCancel::SetDefault

Sets whether the button is triggered by the Escape key

void SetDefault(
   bool bDefault
);

Parameters

bDefault

If bDefault is true, then the button will be deemed to have been pressed whenever the user presses the Escape key.

Remarks

Sets the default state of the control. If true, then the button will be deemed to have been pressed whenever the user presses the Escape key.

Requirements

Header: xldialog.h

See Also

CXlControlCancel Class | CXlControlCancel Methods


CXlControlCheckBox Class

Check-box class supported by CXlDialog.

class CXlControlCheckBox : public CXlControl

Overview

The CXlControlCheckBox class instantiates an check-box field. The text associated with the control can be read and set by calling GetText() and SetText().

The checked state of the field is read and set by calling GetChecked and SetChecked methods.

If the CXlControlCheckBox is set to be a trigger (with the SetTrigger method), then the OnCheckBox() event handler will be called whever the checked state is changed.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlCheckBox Methods | xldialog.h | CXlDialog object | CXlControl object


CXlControlCheckBox Methods

The methods of the CXlControlCheckBox class are listed here.

Construction

public method CXlControlCheckBox Constructs a CXlControlCheckBox object, without displaying it

Data functions

public method | GetChecked | Returns the checked state of the control
public method | SetChecked | Sets the checked state of the control

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlCheckBox Class | xldialog.h | CXlDialog object | CXlControl object


CXlControlCheckBox::CXlControlCheckBox

Constructs a CXlControlCheckBox object, without displaying it

CXlControlCheckBox(
   UINT id = -1,
   const char* pszText = 0,
   USHORT x = 0,
   USHORT y = 0,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
pszText

Pointer to null-terminated string containing the text displayed with the control.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

This constructor creates a check-box control.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlCheckBox Class | CXlControlCheckBox Methods


CXlControlCheckBox::GetChecked

Returns the checked state of the control

BOOL GetChecked( ) const;

Remarks

Returns the checked state of the control. This will be TRUE if the check-box is checked, FALSE if it is not.

Requirements

Header: xldialog.h

See Also

CXlControlCheckBox Class | CXlControlCheckBox Methods


CXlControlCheckBox::SetChecked

Sets the checked state of the control

void SetChecked(
   BOOL bChecked
);

Parameters

bChecked

TRUE to check the box. FALSE to set it as unchecked.

Remarks

Sets the checked state of the control.

Requirements

Header: xldialog.h

See Also

CXlControlCheckBox Class | CXlControlCheckBox Methods


CXlControlFormulaEdit Class

Formula edit control supported by CXlDialog.

class CXlControlFormulaEdit : public CXlControl

Overview

The CXlControlFormulaEdit class instantiates a formula edit field. The raw string value of the field can be read and set by calling GetValue() and SetValue(). Note that this value will contain references in R1C1 form.

The formula value of the field can be read and set by calling GetFormula() and SetFormula().

The user can populate the field by typing and selecting cell ranges in an Excel workbook, just like in the Excel Formula Bar.

Methods of parent class

Reference formats

The references contained in formulae may be formatted in either A1 or R1C1 format.

They will be displayed in the formula bar according to the format currently set for the instance of Excel. You can find this in the Excel Tools - Options dialog on the "General" tab. You can also set it programatically using the "OPTIONS.GENERAL" macro, and read it with the "GET.WORKSPACE" macro.

Requirements

Header: xldialog.h

See Also

CXlControlFormulaEdit Methods | xldialog.h | CXlDialog object | CXlControl object


CXlControlFormulaEdit Methods

The methods of the CXlControlFormulaEdit class are listed here.

Construction

public method CXlControlFormulaEdit Constructs a CXlControlFormulaEdit object, without displaying it

Data functions

public method | GetFormula | Returns a string containing a version of the formula displayed in the field
public method | SetFormula | Sets the control's value to the supplied formula

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlFormulaEdit Class | xldialog.h | CXlDialog object | CXlControl object


CXlControlFormulaEdit::CXlControlFormulaEdit

Constructs a CXlControlFormulaEdit object, without displaying it

CXlControlFormulaEdit(
   UINT id = -1,
   const char* pszFormula = 0,
   BOOL bA1 = TRUE,
   USHORT x = 0,
   USHORT y = 0,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
pszFormula

Pointer to a null-terminated string containing a formula, which will be used as the initial value of the field. If the pointer is 0, then the field will initially be blank.
bA1

Flag denoting whether the formula is in A1-style or R1C1 style. TRUE indicates that all references are in A1 form; FALSE that they are in R1C1 form.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

This constructor creates a formula edit field.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlFormulaEdit Class | CXlControlFormulaEdit Methods


CXlControlFormulaEdit::GetFormula

Returns a string containing a version of the formula displayed in the field

BOOL GetFormula(
   CString& strFormula,
   BOOL bA1 = TRUE
) const;

Parameters

strFormula

String buffer.
bA1

Flag denoting whether the formula is in A1-style or R1C1 style. TRUE indicates that all references are in A1 form; FALSE that they are in R1C1 form.

Return Value

Returns TRUE if the field contains a valid formula. Returns FALSE if the field contains an invalid formula.

Remarks

Populates a string containing a version of the formula displayed in the field. The formula may contain references in A1 or in R1C1 form, depending on the value of bA1.

Requirements

Header: xldialog.h

See Also

CXlControlFormulaEdit Class | CXlControlFormulaEdit Methods


CXlControlFormulaEdit::SetFormula

Sets the control's value to the supplied formula

BOOL SetFormula(
   const char* pszFormula,
   BOOL bA1 = TRUE
);

Parameters

pszFormula

A pointer to a null-terminated string containing a formula.
bA1

Flag denoting whether the formula is in A1-style or R1C1 style. TRUE indicates that all references are in A1 form; FALSE that they are in R1C1 form.

Return Value

Returns TRUE if the call is successful; FALSE if the call fails. The call may fail if the formula is invalid.

Remarks

Sets the value displayed in the control.

Requirements

Header: xldialog.h

See Also

CXlControlFormulaEdit Class | CXlControlFormulaEdit Methods


CXlControlGroupBox Class

Group-box control supported by CXlDialog.

class CXlControlGroupBox : public CXlControl

Overview

The CXlControlGroupBox class instantiates a group box. The text of the group box can be set by calling SetText().

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlGroupBox Methods | xldialog.h | CXlDialog object | CXlControl object


CXlControlGroupBox Methods

The methods of the CXlControlGroupBox class are listed here.

Construction

public method CXlControlGroupBox Constructs a CXlControlGroupBox object, without displaying it

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlGroupBox Class | xldialog.h | CXlDialog object | CXlControl object


CXlControlGroupBox::CXlControlGroupBox

Constructs a CXlControlGroupBox object, without displaying it

CXlControlGroupBox(
   UINT id = -1,
   const char* pszText = 0,
   USHORT x = 0,
   USHORT y = 0,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
pszText

Group box text.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

This constructor creates a group box.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlGroupBox Class | CXlControlGroupBox Methods


CXlControlIcon Class

Icon picture control supported by CXlDialog.

class CXlControlIcon : public CXlControl

Overview

The CXlControlIcon class instantiates an icon field. The value of the field can be read and set by calling GetIcon() and SetIcon().

The only icons available are the three standard Excel message box icons.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlIcon Methods | xldialog.h | CXlDialog object | CXlControl object


CXlControlIcon Methods

The methods of the CXlControlIcon class are listed here.

Construction

public method CXlControlIcon Constructs a CXlControlIcon object, without displaying it

Data functions

public method | GetIcon | Returns the index of the icon displayed in the control
public method | SetIcon | Sets the index of the icon displayed in the control

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlIcon Class | xldialog.h | CXlDialog object | CXlControl object


CXlControlIcon::CXlControlIcon

Constructs a CXlControlIcon object, without displaying it

CXlControlIcon(
   UINT id = -1,
   USHORT nIcon = 1,
   USHORT x = 0,
   USHORT y = 0,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
nIcon

Value representing an icon. See GetIcon() for a list of icon values.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

This constructor creates an icon control.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlIcon Class | CXlControlIcon Methods


CXlControlIcon::GetIcon

Returns the index of the icon displayed in the control

int GetIcon( ) const;

Remarks

Returns the index of the icon displayed in the control. The index may be one of the following values:

iconQuestion (1) | Question mark
iconInformation (2) | Information icon
iconStop (3) | Exclamation mark

Requirements

Header: xldialog.h

See Also

CXlControlIcon Class | CXlControlIcon Methods


CXlControlIcon::SetIcon

Sets the index of the icon displayed in the control

void SetIcon(
   int nIcon
);

Parameters

nIcon

Index of the icon to be displayed. See GetIcon() for a list of icon values.

Remarks

Sets the index of the icon displayed in the control.

Requirements

Header: xldialog.h

See Also

CXlControlIcon Class | CXlControlIcon Methods


CXlControlIntegerEdit Class

Integer edit text-box control supported by CXlDialog.

class CXlControlIntegerEdit : public CXlControl

Overview

The CXlControlIntegerEdit class instantiates an integer edit field. The value of the field can be read and set by calling GetIntValue() and SetIntValue().

If the user attempts to enter anything other than an integer, an error message will be displayed.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlIntegerEdit Methods | xldialog.h | CXlDialog object | CXlControl object


CXlControlIntegerEdit Methods

The methods of the CXlControlIntegerEdit class are listed here.

Construction

public method CXlControlIntegerEdit Constructs a CXlControlIntegerEdit object, without displaying it

Data functions

public method | GetIntValue | Returns the value displayed in the control
public method | SetIntValue | Sets the integer value of the control

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlIntegerEdit Class | xldialog.h | CXlDialog object | CXlControl object


CXlControlIntegerEdit::CXlControlIntegerEdit

Constructs a CXlControlIntegerEdit object, without displaying it

CXlControlIntegerEdit(
   UINT id = -1,
   int nValue = 0,
   USHORT x = 0,
   USHORT y = 0,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
nValue

Initial value displayed in field.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

This constructor creates a integer edit field.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlIntegerEdit Class | CXlControlIntegerEdit Methods


CXlControlIntegerEdit::GetIntValue

Returns the value displayed in the control

int GetIntValue( ) const;

Remarks

Returns the value of the control.

Requirements

Header: xldialog.h

See Also

CXlControlIntegerEdit Class | CXlControlIntegerEdit Methods


CXlControlIntegerEdit::SetIntValue

Sets the integer value of the control

void SetIntValue(
   int nValue
);

Parameters

nValue

Value of the control.

Remarks

Sets the value displayed in the control.

Requirements

Header: xldialog.h

See Also

CXlControlIntegerEdit Class | CXlControlIntegerEdit Methods


CXlControlListBox Class

List-box control supported by CXlDialog.

class CXlControlListBox : public CXlControl

Overview

The CXlControlListBox class instantiates a list-box. The selected item of the field can be read and set by calling GetCurSel() and SetCurSel().

Items can be added to the list-box using AddString(). Most other methods of single-selection list-boxes familiar from the MFC CListBox class are also supported.

If the control's trigger state is set with SetTrigger() then the CDialog::OnListBox() event handler will be inkoked whenever the user changes the selection.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlListBox Methods | xldialog.h | CXlDialog object | CXlControl object


CXlControlListBox Methods

The methods of the CXlControlListBox class are listed here.

Construction

public method CXlControlListBox Constructs a CXlControlListBox object, without displaying it

Behavior operations

public method | GetStyle | Returns the style of the list-box
public method | SetStyle | Sets the style of the list-box

General operations

public method | GetCount | Returns the number of strings in a list box
public method | GetItemData | Retrieves the application-supplied doubleword value associated with the specified list-box item
public method | GetItemDataPtr | Returns a pointer to a list-box item
public method | GetSel | Returns the selection state of a list-box item
public method | GetText | Retrieves the application-supplied doubleword value associated with the specified list-box item
public method | GetTextLen | Gets the length of a string in a list-box item
public method | SetItemData | Sets a 32-bit value associated with the specified item in a list box
public method | SetItemDataPtr | Sets a pointer to the list-box item

Selection operations

public method | GetCurSel | Returns the zero-based index of the currently selected string in a list box
public method | SetCurSel | Selects a list-box string

String operations

public method | AddString | Adds a string to a list box
public method | DeleteString | Deletes a string from a list box
public method | FindString | Searches for a string in a list box
public method | FindStringExact | Finds the first list-box string that matches a specified string
public method | InsertString | Inserts a string at a specific location in a list box
public method | ResetContent | Removes all items from a list box
public method | SelectString | Searches for and selects a string in a single-selection list box

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | xldialog.h | CXlDialog object | CXlControl object


CXlControlListBox::AddString

Adds a string to a list box

int AddString(
   const char* pszItem
);

Parameters

pszItem

Points to the null-terminated string that is to be added.

Return Value

The zero-based index to the string in the list box. The return value is -1 if an error occurs.

Remarks

Call this member function to add a string to a list box. The string is added to the end of the list.

Use InsertString to insert a string into a specific location within the list box.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::CXlControlListBox

Constructs a CXlControlListBox object, without displaying it

CXlControlListBox(
   UINT id = -1,
   int nSel = -1,
   USHORT x = 0,
   USHORT y = 0,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
nSel

Initial index of selected item. -1 for no selection.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

This constructor creates a number edit field.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::DeleteString

Deletes a string from a list box

int DeleteString(
   int nIndex
);

Parameters

nIndex

Specifies the zero-based index of the string to be deleted.

Return Value

A count of the strings remaining in the list. The return value is -1 if nIndex specifies an index greater than the number of items in the list.

Remarks

Deletes an item in a list box.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::FindString

Searches for a string in a list box

int FindString(
   int nStartAfter,
   const char* pszFind
) const;

Parameters

nStartAfter

Contains the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by nStartAfter. If nStartAfter is -1, the entire list box is searched from the beginning.
pszFind

Points to the null-terminated string that contains the prefix to search for. The search is case independent, so this string may contain any combination of uppercase and lowercase letters.

Return Value

The zero-based index of the matching item, or -1 if the search was unsuccessful.

Remarks

Finds the first string in a list box that contains the specified prefix without changing the list-box selection. Use the SelectString member function to both find and select a string.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::FindStringExact

Finds the first list-box string that matches a specified string

int FindStringExact(
   int nStartAfter,
   const char* pszFind
) const;

Parameters

nStartAfter

Contains the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by nStartAfter. If nStartAfter is -1, the entire list box is searched from the beginning.
pszFind

Points to the null-terminated string to search for. This string can contain a complete filename, including the extension. The search is not case sensitive, so the string can contain any combination of uppercase and lowercase letters.

Return Value

The zero-based index of the matching item, or -1 if the search was unsuccessful.

Remarks

An application calls the FindStringExact member function to find the first list-box string that matches the string specified in pszFind.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::GetCount

Returns the number of strings in a list box

int GetCount( ) const;

Return Value

The number of items in the list box, or -1 if an error occurs.

Remarks

Retrieves the number of items in a list box.

The returned count is one greater than the index value of the last item (the index is zero-based).

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::GetCurSel

Returns the zero-based index of the currently selected string in a list box

int GetCurSel( ) const;

Return Value

The zero-based index of the currently selected item. It is -1 if no item is currently selected.

Remarks

Retrieves the zero-based index of the currently selected item, if any, in a single-selection list box.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::GetItemData

Retrieves the application-supplied doubleword value associated with the specified list-box item

DWORD GetItemData(
   int nIndex
) const;

Parameters

nIndex

Specifies the zero-based index of the item in the list box.

Return Value

The 32-bit value associated with the item, or -1 if an error occurs.

Remarks

Retrieves the application-supplied doubleword value associated with the specified list-box item.

The doubleword value was the dwItemData parameter of a SetItemData call.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::GetItemDataPtr

Returns a pointer to a list-box item

void* GetItemDataPtr(
   int nIndex
) const;

Parameters

nIndex

Specifies the zero-based index of the item in the list box.

Return Value

Retrieves a pointer, or -1 if an error occurs.

Remarks

Retrieves the application-supplied 32-bit value associated with the specified list-box item as a pointer (void*).

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::GetSel

Returns the selection state of a list-box item

int GetSel(
   int nIndex
) const;

Parameters

nIndex

Specifies the zero-based index of the item in the list box.

Return Value

A positive number if the specified item is selected; otherwise, it is 0. The return value is -1 if an error occurs.

Remarks

Retrieves the selection state of an item.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::GetStyle

Returns the style of the list-box

int GetStyle( );

Remarks

Returns the style of the control. The style may be one of the following types:

styleStandard | A standard list-box.
styleLinked | The list-box is linked to the preceding control, which must be an object of class CXlControlTextEdit. Whenever the selection of the list-box is changed, the contents of the edit field will be changed to reflect the selected item of the list-box.
styleDropList | A drop-down list in a combo-box.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::GetText

Retrieves the application-supplied doubleword value associated with the specified list-box item

int GetText(
   int nIndex,
   const char* pszBuffer
) const;
void GetText(
   int nIndex,
   CString& rString
) const;

Parameters

nIndex

Specifies the zero-based index of the item in the list box.
pszBuffer

Points to the buffer that receives the string. The buffer must have sufficient space for the string and a terminating null character. The size of the string can be determined ahead of time by calling the GetTextLen member function.
nIndex

Specifies the zero-based index of the item in the list box.
rString

A reference to a CString object

Return Value

The length (in bytes) of the string, excluding the terminating null character. If nIndex does not specify a valid index, the return value is -1.

Remarks

Gets a string from a list box. The second form of this member function fills a CString object with the string text.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::GetTextLen

Gets the length of a string in a list-box item

int GetTextLen(
   int nIndex
) const;

Parameters

nIndex

Specifies the zero-based index of the item in the list box.

Return Value

The length (in bytes) of the string, excluding the terminating null character. If nIndex does not specify a valid index, the return value is -1.

Remarks

Gets the length of a string in a list-box item.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::InsertString

Inserts a string at a specific location in a list box

int InsertString(
   int nIndex,
   const char* pszItem
);

Parameters

nIndex

Specifies the zero-based index of the position to insert the string. If this parameter is -1, the string is added to the end of the list.
pszItem

Points to the null-terminated string that is to be inserted.

Return Value

The zero-based index to the string in the list box. The return value is -1 if an error occurs.

Remarks

Inserts a string into the list box.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::ResetContent

Removes all items from a list box

void ResetContent( );

Remarks

Removes all items from a list box.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::SelectString

Searches for and selects a string in a single-selection list box

int SelectString(
   int nStartAfter,
   const char* pszFind
);

Parameters

nStartAfter

Contains the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by nStartAfter. If nStartAfter is –1, the entire list box is searched from the beginning.
pszFind

Points to the null-terminated string that contains the prefix to search for. The search is case independent, so this string may contain any combination of uppercase and lowercase letters.

Return Value

The index of the selected item if the search was successful. If the search was unsuccessful, the return value is -1 and the current selection is not changed.

Remarks

Searches for a list-box item that matches the specified string, and if a matching item is found, it selects the item.

The list box is scrolled, if necessary, to bring the selected item into view.

An item is selected only if its initial characters (from the starting point) match the characters in the string specified by pszItem.

Use the FindString member function to find a string without selecting an item.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::SetCurSel

Selects a list-box string

int SetCurSel(
   int nIndex
);

Parameters

nIndex

Specifies the zero-based index of the item in the list box.

Return Value

-1 if an error occurs.

Remarks

Selects a string and scrolls it into view, if necessary. When the new string is selected, the list box removes the highlight from the previously selected string.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::SetItemData

Sets a 32-bit value associated with the specified item in a list box

int SetItemData(
   int nIndex,
   DWORD dwItemData
);

Parameters

nIndex

Specifies the zero-based index of the item in the list box.
dwItemData

Specifies the value to be associated with the item.

Return Value

-1 if an error occurs.

Remarks

Sets a 32-bit value associated with the specified item in a list box.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::SetItemDataPtr

Sets a pointer to the list-box item

int SetItemDataPtr(
   int nIndex,
   void* dwItemData
);

Parameters

nIndex

Specifies the zero-based index of the item in the list box.
dwItemData

Specifies the pointer to be associated with the item.

Return Value

-1 if an error occurs.

Remarks

Sets the 32-bit value associated with the specified item in a list box to be the specified pointer (void*). This pointer remains valid for the life of the list box, even though the item's relative position within the list box might change as items are added or removed. Hence, the item's index within the box can change, but the pointer remains reliable.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlListBox::SetStyle

Sets the style of the list-box

void SetStyle(
   int nStyle
);

Parameters

nStyle

Style of the control. See GetStyle() for a list of style types.

Remarks

Sets the style of the list-box.

Requirements

Header: xldialog.h

See Also

CXlControlListBox Class | CXlControlListBox Methods


CXlControlNumberEdit Class

Numeric edit text-box control supported by CXlDialog.

class CXlControlNumberEdit : public CXlControl

Overview

The CXlControlNumberEdit class instantiates an numeric edit field. The value of the field can be read and set by calling GetNumberValue() and SetNumberValue().

If the user attempts to enter anything other than a number, an error message will be displayed.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlNumberEdit Methods | xldialog.h | CXlDialog object | CXlControl object


CXlControlNumberEdit Methods

The methods of the CXlControlNumberEdit class are listed here.

Construction

public method CXlControlNumberEdit Constructs a CXlControlNumberEdit object, without displaying it

Data functions

public method | GetNumberValue | Returns the value displayed in the control
public method | SetNumberValue | Sets the integer value of the control

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlNumberEdit Class | xldialog.h | CXlDialog object | CXlControl object


CXlControlNumberEdit::CXlControlNumberEdit

Constructs a CXlControlNumberEdit object, without displaying it

CXlControlNumberEdit(
   UINT id = -1,
   double dValue = 0,
   USHORT x = 0,
   USHORT y = 0,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
dValue

Initial value displayed in field.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

This constructor creates a number edit field.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlNumberEdit Class | CXlControlNumberEdit Methods


CXlControlNumberEdit::GetNumberValue

Returns the value displayed in the control

double GetNumberValue( ) const;

Remarks

Returns the value of the control.

Requirements

Header: xldialog.h

See Also

CXlControlNumberEdit Class | CXlControlNumberEdit Methods


CXlControlNumberEdit::SetNumberValue

Sets the integer value of the control

void SetNumberValue(
   double dValue
);

Parameters

dValue

Value of the control.

Remarks

Sets the value displayed in the control.

Requirements

Header: xldialog.h

See Also

CXlControlNumberEdit Class | CXlControlNumberEdit Methods


CXlControlOK Class

Push-button control supported by CXlDialog.

class CXlControlOK : public CXlControl

Overview

The CXlControlOK class instantiates a push-button. If it is pushed during CDialog::Show() then the OnOK() event handler will be called.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlOK Methods | xldialog.h | CXlDialog object | CXlControl object


CXlControlOK Methods

The methods of the CXlControlOK class are listed here.

Construction

public method CXlControlOK Constructs a CXlControlOK object, without displaying it

Property functions

public method | GetDefault | Returns whether the button is triggered by the Enter key
public method | SetDefault | Sets whether the button is triggered by the Enter key

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlOK Class | xldialog.h | CXlDialog object | CXlControl object


CXlControlOK::CXlControlOK

Constructs a CXlControlOK object, without displaying it

CXlControlOK(
   UINT id = -1,
   const char* pszText = 0,
   USHORT x = 0,
   USHORT y = 0,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
pszText

Button text. If 0, then "OK" will be used.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

This constructor creates a push-button. When the user presses it the OnOK() event handler will be invoked. By default, this method dismisses the dialog with result TRUE. It can be overriden in classes descended from CDialog.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlOK Class | CXlControlOK Methods


CXlControlOK::GetDefault

Returns whether the button is triggered by the Enter key

bool GetDefault( ) const;

Remarks

Returns the default state of the control. If true, then the button will be deemed to have been pressed whenever the user presses the Enter key or double-clicks on a list-box, check-box or option button.

Requirements

Header: xldialog.h

See Also

CXlControlOK Class | CXlControlOK Methods


CXlControlOK::SetDefault

Sets whether the button is triggered by the Enter key

void SetDefault(
   bool bDefault
);

Parameters

bDefault

If bDefault is true, then the button will be deemed to have been pressed whenever the user presses the Enter key or double-clicks on a list-box, check-box or option button.

Remarks

Sets the default state of the control. If true, then the button will be deemed to have been pressed whenever the user presses the Enter key or double-clicks on a list-box, check-box or option button.

Requirements

Header: xldialog.h

See Also

CXlControlOK Class | CXlControlOK Methods


CXlControlOption Class

Option control supported by CXlDialog.

class CXlControlOption : public CXlControl

Overview

The CXlControlOption class instantiates an option field. The text associated with the option can be read and set by calling GetText() and SetText().

A group of options should be added to the dialog in a sequential group, and the group must be preceded by a CXlControlOptionGroup control.

The checked state of the field is read and set by calling GetSel and SetSel methods of the associated CXlControlOptionGroup control.

If the CXlControlOptionGroup is set to be a trigger (with the SetTrigger method), then the OnOption() event handler will be called whever the selection is changed.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlOption Methods | xldialog.h | CXlDialog object | CXlControl object | CXlControlOptionGroup object


CXlControlOption Methods

The methods of the CXlControlOption class are listed here.

Construction

public method CXlControlOption Constructs a CXlControlOption object, without displaying it

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlOption Class | xldialog.h | CXlDialog object | CXlControl object | CXlControlOptionGroup object


CXlControlOption::CXlControlOption

Constructs a CXlControlOption object, without displaying it

CXlControlOption(
   UINT id = -1,
   const char* pszText = 0,
   USHORT x = 0,
   USHORT y = 0,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
pszText

Pointer to null-terminated string containing the text displayed with the control.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

This constructor creates an option field.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlOption Class | CXlControlOption Methods


CXlControlOptionGroup Class

Option group control supported by CXlDialog.

class CXlControlOptionGroup : public CXlControl

Overview

The CXlControlOptionGroup class groups together a set of option fields, each represented by a CXlControlOption object.

A group of options should be added to the dialog in a sequential group, and the group must be preceded by a CXlControlOptionGroup control.

The CXlControlOptionGroup object is never displayed, but its position can be used to set the position of the first member option.

Which of the options is selected can be read and set by calling GetSel and SetSel methods.

If the CXlControlOptionGroup is set to be a trigger (with the SetTrigger method), then the OnOption() event handler will be called whever the selection is changed.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlOptionGroup Methods | xldialog.h | CXlDialog object | CXlControl object | CXlControlOption object


CXlControlOptionGroup Methods

The methods of the CXlControlOptionGroup class are listed here.

Construction

public method CXlControlOptionGroup Constructs a CXlControlOptionGroup object

Data functions

public method | GetSel | Returns the index of the currently selected option
public method | SetSel | Sets the index of the currently selected option

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlOptionGroup Class | xldialog.h | CXlDialog object | CXlControl object | CXlControlOption object


CXlControlOptionGroup::CXlControlOptionGroup

Constructs a CXlControlOptionGroup object

CXlControlOptionGroup(
   UINT id = -1,
   int nSel = -1,
   USHORT x = 0,
   USHORT y = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
nSel

Zero-based index of the initially selected option.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.

Remarks

This constructor creates a option group.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlOptionGroup Class | CXlControlOptionGroup Methods


CXlControlOptionGroup::GetSel

Returns the index of the currently selected option

int GetSel( ) const;

Remarks

Returns the zero-based index of the currently selected option. Note that the index will reflect the order in which CXlDialog::Add() was called for each option.

Requirements

Header: xldialog.h

See Also

CXlControlOptionGroup Class | CXlControlOptionGroup Methods


CXlControlOptionGroup::SetSel

Sets the index of the currently selected option

void SetSel(
   int nSel
);

Parameters

nSel

Zero-based index of the option to be selected. Note that the index will reflect the order in which CXlDialog::Add() was called for each option.

Remarks

Sets the zero-based index of the currently selected option.

Requirements

Header: xldialog.h

See Also

CXlControlOptionGroup Class | CXlControlOptionGroup Methods


CXlControlRefEdit Class

Reference edit text-box control supported by CXlDialog.

class CXlControlRefEdit : public CXlControl

Overview

The CXlControlRefEdit class instantiates a reference edit field. The string value of the field can be read and set by calling GetValue() and SetValue().

The reference value of the field can be read and set by calling GetRef() and SetRef().

The user can populate the field by selecting a cell range in an Excel workbook.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlRefEdit Methods | xldialog.h | CXlDialog object | CXlControl object


CXlControlRefEdit Methods

The methods of the CXlControlRefEdit class are listed here.

Construction

public method CXlControlRefEdit Constructs a CXlControlRefEdit object, without displaying it

Data functions

public method | GetRef | Returns a CXlOper containing a reference to the address displayed in the field
public method | SetRef | Sets the control's value to the address of the supplied reference

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlRefEdit Class | xldialog.h | CXlDialog object | CXlControl object


CXlControlRefEdit::CXlControlRefEdit

Constructs a CXlControlRefEdit object, without displaying it

CXlControlRefEdit(
   UINT id = -1,
   const CXlOper* pxloRef = 0,
   USHORT x = 0,
   USHORT y = 0,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
pxloRef

Pointer to CXlOper containing a reference, whose address will be used as the initial value of the field. If the pointer is 0, then the field will initially be blank.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

This constructor creates a reference edit field.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlRefEdit Class | CXlControlRefEdit Methods


CXlControlRefEdit::GetRef

Returns a CXlOper containing a reference to the address displayed in the field

BOOL GetRef(
   CXlOper& xloRef
) const;

Parameters

xloRef

Reference to a CXlOper which will contain a reference if the call is successful.

Return Value

Returns TRUE if the field contains a valid reference. Returns FALSE if the field contains an invalid reference or is empty.

Remarks

Populates a CXlOper with a reference to the address displayed in the field.

Requirements

Header: xldialog.h

See Also

CXlControlRefEdit Class | CXlControlRefEdit Methods


CXlControlRefEdit::SetRef

Sets the control's value to the address of the supplied reference

void SetRef(
   const CXlOper& xloRef
);

Parameters

xloRef

A CXlOper containing a reference.

Remarks

Sets the value displayed in the control.

Requirements

Header: xldialog.h

See Also

CXlControlRefEdit Class | CXlControlRefEdit Methods


CXlControlStatic Class

Static text control supported by CXlDialog.

class CXlControlStatic : public CXlControl

Overview

The CXlControlStatic class instantiates a static text field. The text of the field can be set by calling SetText().

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlStatic Methods | xldialog.h | CXlDialog object | CXlControl object


CXlControlStatic Methods

The methods of the CXlControlStatic class are listed here.

Construction

public method CXlControlStatic Constructs a CXlControlStatic object, without displaying it

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlStatic Class | xldialog.h | CXlDialog object | CXlControl object


CXlControlStatic::CXlControlStatic

Constructs a CXlControlStatic object, without displaying it

CXlControlStatic(
   UINT id = -1,
   const char* pszText = 0,
   USHORT x = 0,
   USHORT y = 0,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
pszText

Field text.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

This constructor creates a static text field.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlStatic Class | CXlControlStatic Methods


CXlControlTextEdit Class

Text-box control supported by CXlDialog.

class CXlControlTextEdit : public CXlControl

Overview

The CXlControlTextEdit class instantiates a text edit field. The text of the field can be read and set by calling GetValue() and SetValue().

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlTextEdit Methods | xldialog.h | CXlDialog object | CXlControl object


CXlControlTextEdit Methods

The methods of the CXlControlTextEdit class are listed here.

Construction

public method CXlControlTextEdit Constructs a CXlControlTextEdit object, without displaying it

Methods of CXlControl

Requirements

Header: xldialog.h

See Also

CXlControlTextEdit Class | xldialog.h | CXlDialog object | CXlControl object


CXlControlTextEdit::CXlControlTextEdit

Constructs a CXlControlTextEdit object, without displaying it

CXlControlTextEdit(
   UINT id = -1,
   const char* pszText = 0,
   USHORT x = 0,
   USHORT y = 0,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

id

Numeric identifier of the control, which can be used to refer to it in event handlers. The ID does not need to be unique.
pszText

Initial value of text.
x

Coordinate of left side of control. Ignored if 0.
y

Coordinate of top of control. Ignored if 0.
cx

Width of control. Ignored if 0.
cy

Height of control. Ignored if 0.

Remarks

This constructor creates a text edit field.

Methods of parent class

Requirements

Header: xldialog.h

See Also

CXlControlTextEdit Class | CXlControlTextEdit Methods


CXlDialog Class

Controls the display and interaction of native Excel dialogs.

class CXlDialog

Overview

The CXlDialog class controls the display and interaction of native Excel dialogs.

The Show() method is used to display the dialog.

During Show(), overrideable event handlers will be called if the user clicks buttons or selects items in list boxes. The developer can create a class descended from CXlDialog and override these event handlers.

Controls

Each control on a dialog is of a class descended from CXlControl. See the help for CXlControl for a list of control types.

Each control must be added to the dialog using the CXlDialog::Add() method.

Requirements

Header: xldialog.h

See Also

CXlDialog Methods | xldialog.h | CXlControl object


CXlDialog Methods

The methods of the CXlDialog class are listed here.

Construction

public method CXlDialog Constructs a CXlDialog object without displaying it

Title functions

public method | GetTitle | Returns the title of the dialog
public method | SetTitle | Sets the title of the dialog

Position functions

public method | GetHeight | Returns the height of the dialog
public method | GetLeft | Returns the horizontal position of the dialog
public method | GetTop | Returns the vertical position of the dialog
public method | GetWidth | Returns the width of the dialog
public method | SetPos | Sets the position and optinally the size of the dialog
public method | SetSize | Sets the size of the dialog

Control functions

public method | Add | Adds a control to the dialog
public method | ControlFromID | Gets a control from its ID

Display functions

public method Show Displays the dialog

Overrideable functions

public method | OnCheckBox | Event handler for check-boxes
public method | OnListBox | Event handler for list-boxes
public method | OnOK | Event handler for OK buttons
public method | OnOption | Event handler for option buttons
public method | OnTrigger | Event handler for all triggered events

Dialog state functions

public method | EndDialog | Closes the dialog
public method | GetFocus | Gets the control which currently has the focus
public method | SetFocus | Sets the focus to a particular control

Requirements

Header: xldialog.h

See Also

CXlDialog Class | xldialog.h | CXlControl object


CXlDialog::Add

Adds a control to the dialog

void Add(
   CXlControl& ctl
);
void Add(
   int cCtls,
    ...
);

Parameters

ctl

Reference to an object of a class descended from CXlControl.
cCtls

Count of the number of arguments following.
...

The remaining cCtls argauments should each be a pointer to an object descended from CXlControl. Each of these will be added to the dialog.

Remarks

This function can be used to add one or more controls to the dialog. Note that the call does not establish "ownership" of the control - the control must be deleted by the user; it will not be automatically cleaned up by the CXlDialog's destructor.

Unless a control is added to the dialog using Add(), it will not be visible.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::ControlFromID

Gets a control from its ID

CXlControl* ControlFromID(
   UINT id
) const;

Parameters

id

ID of the control to be found.

Remarks

It returns a pointer to the first control with a matching ID. The function returns 0 if no such control could not be found.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::CXlDialog

Constructs a CXlDialog object without displaying it

CXlDialog( );
CXlDialog(
   const char* pszTitle,
   USHORT cx,
   USHORT cy,
   USHORT x = 0,
   USHORT y = 0
);

Parameters

pszTitle

Title of the dialog, which will appear in the dialog's title bar.
cx

Width of dialog in pixels.
cy

Height of dialog in pixels.
x

Coordinate of left side of dialog. Ignored if 0.
y

Coordinate of top of dialog. Ignored if 0.

Remarks

Any parameters passed into the constructor may be changed before the dialog is displayed.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::EndDialog

Closes the dialog

void EndDialog(
   BOOL bResult
);

Parameters

bResult

The result code which will be returned by Show().

Remarks

This function can be called from event handlers in order to close the dialog.

If called from any other place, it has no effect.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::GetFocus

Gets the control which currently has the focus

CXlControl* GetFocus( ) const;

Remarks

This function can be called from event handlers in order to get the control that has the focus. If called from any other place, it has no effect.

The function returns NULL if no focus could be found.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::GetHeight

Returns the height of the dialog

USHORT GetHeight( ) const;

Remarks

Returns the height of the dialog.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::GetLeft

Returns the horizontal position of the dialog

USHORT GetLeft( ) const;

Remarks

Returns the horizontal position of the dialog.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::GetTitle

Returns the title of the dialog

CString GetTitle( ) const;

Remarks

Returns the title of the dialog.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::GetTop

Returns the vertical position of the dialog

USHORT GetTop( ) const;

Remarks

Returns the vertical position of the dialog.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::GetWidth

Returns the width of the dialog

USHORT GetWidth( ) const;

Remarks

Returns the width of the dialog.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::OnCheckBox

Event handler for check-boxes

virtual void OnCheckBox(
   UINT id,
   BOOL bChecked,
   const CXlControlCheckBox* ctl
);

Parameters

id

ID of the button which was pressed.
bChecked

New checked state of the button which was pressed.
ctl

Pointer to the control which originated the event.

Remarks

This overrideable function is called whenever a check-box (CXlControlCheckBox) is checked or unchecked. Note that it will only be called if the check box has been set to trigger events (see CXlControl::SetTrigger()).

Its default behaviour is to do nothing.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::OnListBox

Event handler for list-boxes

virtual void OnListBox(
   UINT id,
   int nCurSel,
   const CXlControlListBox* ctl
);

Parameters

id

ID of the list-box.
nCurSel

New selection of the list-box.
ctl

Pointer to the control which originated the event.

Remarks

This overrideable function is called whenever the current selection of a list-box (CXlControlListBox) is changed by the user. Note that it will only be called if the list-box has been set to trigger events (see CXlControl::SetTrigger()).

Its default behaviour is to do nothing.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::OnOK

Event handler for OK buttons

virtual void OnOK(
   UINT id,
   const CXlControlOK* ctl
);

Parameters

id

ID of the button which was pressed.
ctl

Pointer to the control which originated the event.

Remarks

This overrideable function is called whenever a button of type CXlControlOK is pressed.

Its default behaviour is to call EndDialog(TRUE) in order to close the dialog.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::OnOption

Event handler for option buttons

virtual void OnOption(
   UINT id,
   const CXlControlOption* ctl
);

Parameters

id

ID of the button which was pressed.
ctl

Pointer to the control which originated the event.

Remarks

This overrideable function is called whenever an option button (CXlControlOption) is selected. Note that it will only be called if the option control or it owner CXlControlOptionGroup has been set to trigger events (see CXlControl::SetTrigger()).

Its default behaviour is to do nothing.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::OnTrigger

Event handler for all triggered events

virtual BOOL OnTrigger(
   const CXlControl* ctl
);

Parameters

ctl

Pointer to the control which originated the event.

Remarks

This function is called whenever a control triggers an event. Note that the trigger state must be set for a control in order for it to be able to trigger an event. The trigger state is on by default for push-buttons, but off for all other controls.

Its default behaviour is to call the appropraiet overrideable event handler
            OnOK(),
            OnOption(),
            OnCheckBox() or
            OnListBox()
            according to the type of control which originated the event.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::SetFocus

Sets the focus to a particular control

BOOL SetFocus(
   CXlControl& ctl
);
BOOL SetFocus(
   UINT id
);

Parameters

ctl

Reference to the control which will get the focus.
id

ID of the control which will get the focus.

Remarks

This function can be called from event handlers in order to set the focus. It can also be called before Show() to set the initial focus.

The function returns TRUE if the call succeeded, and FALSE if the control could not be found.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::SetPos

Sets the position and optinally the size of the dialog

void SetPos(
   USHORT x,
   USHORT y,
   USHORT cx = 0,
   USHORT cy = 0
);

Parameters

x

Coordinate of left side of dialog.
y

Coordinate of top of dialog.
cx

Width of dialog. Ignored if 0.
cy

Height of dialog. Ignored if 0.

Remarks

Sets the position and optionally the size of the dialog. Note that zero values for x, y, cx and cy will result in the default position and/or size being applied.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::SetSize

Sets the size of the dialog

void SetSize(
   USHORT cx,
   USHORT cy
);

Parameters

cx

Width of dialog in pixels. Ignored if 0.
cy

Height of dialog in pixels. Ignored if 0.

Remarks

Sets the size of the dialog. Note that zero values for cx and cy will result in the default size being applied.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::SetTitle

Sets the title of the dialog

void SetTitle(
   const char* pszTitle
);

Parameters

pszTitle

Text of the control.

Remarks

Sets the title of the control. This will be displayed in the dialog's title bar.

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


CXlDialog::Show

Displays the dialog

BOOL Show( );

Remarks

This function is used to display a dialog. It returns TRUE if the user pressed OK and FALSE if the user cancelled.

During the lifetime of the function, the overrideable event handlers
            OnTrigger(),
            OnOK(),
            OnOption(),
            OnCheckBox() and
            OnListBox()
            may be invoked.

The function EndDialog() may be called from any overrideable function to close the dialog and to set the return value of Show().

Requirements

Header: xldialog.h

See Also

CXlDialog Class | CXlDialog Methods


xlhandle.h

Overview

xlhandle.h contains classes for representing objects within Excel cells as handles.

See Object handles in the User Guide for more information on these classes.

Classes

The following classes are contained in xlhandles.h:

Class | Purpose
CXlHandleStore<T, S> | Class template which manages a store of objects of type T, and allows the object to be referred to in a worksheet formula by it's handle.
CXlFormulaRefresh | Utility class which causes recalculation of any cell whose formula contains a specific function.

See Also

CXlHandleStore<T, S> class | CXlFormulaRefresh class | User Guide: Object handles


CXlFormulaRefresh Class

class CXlFormulaRefresh

Overview

The CXlFormulaRefresh class allows the programmer to force a recalculation of all cells whose formulae contain a specific function.

See Object handles coded manually in the User Guide for more information.

Requirements

Header: xlhandle.h

See Also

CXlFormulaRefresh Methods | xlhandle.h | CXlHandleStore<T, S> class | User Guide: Object handles | User Guide: Object handles coded manually


CXlFormulaRefresh Methods

The methods of the CXlFormulaRefresh class are listed here.

Construction

public method CXlFormulaRefresh Constructs a CXlFormulaRefresh object

Operations

public method | RefreshAllWorkbooks | Refresh all open workbooks
public method | RefreshWorkbook | Refresh a workbook
public method | RefreshWorksheet | Refresh a worksheet

Requirements

Header: xlhandle.h

See Also

CXlFormulaRefresh Class | xlhandle.h | CXlHandleStore<T, S> class | User Guide: Object handles | User Guide: Object handles coded manually


CXlFormulaRefresh::CXlFormulaRefresh

Constructs a CXlFormulaRefresh object

CXlFormulaRefresh(
   const TCHAR* pszFunction
);
CXlFormulaRefresh(
   const TCHAR** apszFunctions
);
CXlFormulaRefresh(
   std::vector<CString> vecFunctions
);

Parameters

pszFunction

The name of the function whose instances will be recalculated.
apszFunctions

An array of function names, all of whose instances will be recalculated. The last item in the array should be a NULL pointer.
vecFunctions

A collection of function names, all of whose instances will be recalculated.

Remarks

This contructor creates a new object, which can be used to refresh all cells which contain any of the functions whose names are passed to the constructor.

Requirements

Header: xlhandle.h

See Also

CXlFormulaRefresh Class | CXlFormulaRefresh Methods


CXlFormulaRefresh::RefreshAllWorkbooks

Refresh all open workbooks

void RefreshAllWorkbooks( );

Remarks

The function iterates through all open workbooks, calling RefreshWorkbook() for each.

Requirements

Header: xlhandle.h

See Also

CXlFormulaRefresh Class | CXlFormulaRefresh Methods


CXlFormulaRefresh::RefreshWorkbook

Refresh a workbook

void RefreshWorkbook(
   const char* pszBookName
);
void RefreshWorkbook(
   const wchar_t* wpszBookName
);

Parameters

pszBookName

The name of an open workbook.
wpszBookName

The name of an open workbook.

Remarks

The function iterates through the named workbook, calling RefreshWorksheet() for each sheet.

Requirements

Header: xlhandle.h

See Also

CXlFormulaRefresh Class | CXlFormulaRefresh Methods


CXlFormulaRefresh::RefreshWorksheet

Refresh a worksheet

void RefreshWorksheet(
   DWORD dwSheet
);
void RefreshWorksheet(
   const char* pszBookName,
   const char* pszSheetName
);
void RefreshWorksheet(
   const wchar_t* wpszBookName,
   const wchar_t* wpszSheetName
);

Parameters

dwSheet

The sheet ID of a worksheet.
pszBookName

The name of an open workbook.
pszSheetName

The name of a worksheet in the workbook.
wpszBookName

The name of an open workbook.
wpszSheetName

The name of a worksheet in the workbook.

Remarks

The function calls xlcFormulaReplace for the worksheet, for each of the functions of the functions specified in the object's constructor.

Requirements

Header: xlhandle.h

See Also

CXlFormulaRefresh Class | CXlFormulaRefresh Methods


CXlHandleStore<T, S> Class

Stores objects within an add-in and exposes them in Excel as handles.

class CXlHandleStore<T, S>

Overview

The CXlHandleStore<T, S> template allows the programmer to store objects within an add-in and to expose them to Excel as handles.

See Object handles coded manually in the User Guide for more information.

Requirements

Header: xlhandle.h

See Also

CXlHandleStore<T, S> Methods | xlhandle.h | CXlFormulaRefresh class | User Guide: Object handles coded manually


CXlHandleStore<T, S> Methods

The methods of the CXlHandleStore<T, S> class are listed here.

Construction

public method CXlHandleStore Constructs a CXlHandleStore<T, S> object

Handle operations

public method | AddObjectHandle | Convert an object pointer to a handle
public method | Clear | Clear all handles from the store
public method | ObjectFromHandle | Convert a handle to an object pointer

Requirements

Header: xlhandle.h

See Also

CXlHandleStore<T, S> Class | xlhandle.h | CXlFormulaRefresh class | User Guide: Object handles coded manually


CXlHandleStore<T, S>::AddObjectHandle

Convert an object pointer to a handle

long AddObjectHandle(
   T* value
);

Parameters

value

A pointer to an object, usually created by an add-in function.

Return Value

The function returns a handle that represents the object, and which can be used later as a parameter to ObjectFromHandle().

Remarks

The function adds the object pointer to the handle store, which is thereafer in control of the object's lifetime.

Requirements

Header: xlhandle.h

See Also

CXlHandleStore<T, S> Class | CXlHandleStore<T, S> Methods


CXlHandleStore<T, S>::Clear

Clear all handles from the store

void Clear( );

Remarks

The function clears all objects from the store. It should usually be followed by a call to CXlFormulaRefresh::RefreshAllWorkbooks, which will cause all the objects for which handles still exist to be recreated.

Requirements

Header: xlhandle.h

See Also

CXlHandleStore<T, S> Class | CXlHandleStore<T, S> Methods


CXlHandleStore<T, S>::CXlHandleStore

Constructs a CXlHandleStore<T, S> object

CXlHandleStore( );

Remarks

This contructor creates a new empty store.

Requirements

Header: xlhandle.h

See Also

CXlHandleStore<T, S> Class | CXlHandleStore<T, S> Methods


CXlHandleStore<T, S>::ObjectFromHandle

Convert a handle to an object pointer

T* ObjectFromHandle(
   long handle
) const;

Parameters

handle

An object handle, usually passed to an add-in function from a worksheet cell.

Return Value

If the handle is valid, then the function returns a pointer to the object it represents. If the handle is not valid, the function returns 0.

Requirements

Header: xlhandle.h

See Also

CXlHandleStore<T, S> Class | CXlHandleStore<T, S> Methods


xlhandles.h

Overview

xlhandles.h contains classes for representing objects within Excel cells as handles.

See Object handles in the User Guide for more information on these classes.

Classes

The following classes are contained in xlhandles.h:

Class | Purpose
CXlHandleStore<T, S> | Class template which manages a store of objects of type T, and allows the object to be referred to in a worksheet formula by it's handle.
CXlFormulaRefresh | Utility class which causes recalculation of any cell whose formula contains a specific function.

See Also

CXlHandleStore<T, S> class | CXlFormulaRefresh class | User Guide: Object handles


xllfinder.h

Overview

xllfinder.h contains a class CXllFinder for finding and replacing data in Excel spreadsheets.

See Also

CXllFinder class


CXllFinder Class

Helps to search and replace the contents and formulae of cells.

class CXllFinder

Overview

The CXllFinder class is a utility class to help you search and replace the contents and formulae of cells.

Usage

Note that only one instance of CXllFinder can be used at a time, since the class manipulates the active selection. CXllFinder can only be used from macro functions. It will fail if used from worksheet functions.

Use the finder class with the following pattern:

char achMatch[] = "fred";
CXllFinder finder(achMatch, ...);
CXlRef xlrFind;
while (finder.FindNext(xlrFind)) {
    // Inspect the current value
    CXlOper xloValue;
    finder.GetCurrentValue(xloValue);
    // Use the current value...

    // Change the value in the matched cell
    finder.SetCurrentValue("replaced");
}

Requirements

Header: xllfinder.h

See Also

CXllFinder Methods | xllfinder.h | CXlRef object


CXllFinder Methods

The methods of the CXllFinder class are listed here.

Construction

public method CXllFinder Constructs a CXllFinder object

Operations

public method | FindNext | Find the next matching cell
public method | GetCurrentValue | Get the value of the current match
public method | SetCurrentValue | Set the value of the curremt matching cell

Requirements

Header: xllfinder.h

See Also

CXllFinder Class | xllfinder.h | CXlRef object


CXllFinder::CXllFinder

Constructs a CXllFinder object

CXllFinder(
   const char* pszFind,
   BOOL bLookInFormulae = FALSE,
   BOOL bMatchWhole = FALSE,
   DWORD dwSheetId = 0
);
CXllFinder(
   const char* pszFind,
   BOOL bLookInFormulae,
   BOOL bMatchWhole,
   const CString& strBook,
   const CString& strSheet
);

Parameters

pszFind

A null-terminated string that contains the text being searched for.
bLookInFormulae

If TRUE, then cell formulae will be searched; if FALSE, then cell values will be searched.
bMatchWhole

If TRUE, then only cells whose entire contents match the search string will be found; if FALSE then all cells that contain the search string will be matched.
dwSheetId

The ID of the sheet to be searched. This can be extracted from references, using CXlOper::GetSheetId(), or derived from a call to CXllApp::GetSheetId().

If the value is 0, then the current sheet will be searched.
strBook

The name of the workbook containing the sheet to be searched.
strSheet

The name of the sheet to be searched.

Remarks

Constructs a CXllFinder object, which can then be used to iterate through all the matching cells within a sheet.

Requirements

Header: xllfinder.h

See Also

CXllFinder Class | CXllFinder Methods


CXllFinder::FindNext

Find the next matching cell

BOOL FindNext(
   CXlRef& xlr
);

Parameters

xlr

If the call succeeds, this will contain a reference to the matching cell.

Return Value

Returns TRUE if another matching cell is found. Returns FALSE if no more matching cells can be found.

Requirements

Header: xllfinder.h

See Also

CXllFinder Class | CXllFinder Methods


CXllFinder::GetCurrentValue

Get the value of the current match

BOOL GetCurrentValue(
   CXlOper& xloValue
);

Parameters

xloValue

If the call succeeds, this will contain the value of the current match.

Return Value

The call will fail if there is no current match.

Requirements

Header: xllfinder.h

See Also

CXllFinder Class | CXllFinder Methods


CXllFinder::SetCurrentValue

Set the value of the curremt matching cell

BOOL SetCurrentValue(
   const CXlOper& xloValue
);

Parameters

xloValue

The value to be set into the current matching cell.

Return Value

The call will fail if there is no current match or if the supplied value is invalid.

Requirements

Header: xllfinder.h

See Also

CXllFinder Class | CXllFinder Methods


xllres.h

Overview

xllres.h contains a number of global functions that manage strings in resource files.

The file is automatically included when the AppWizard creates the XLL+ project.

Functions

The table below lists the principal functions declared in the header file.

Function | Description
XllGetStringResourceHandle | Gets the handle of the DLL which will is being used to load string resources.
XllSetStringResourceHandle | Sets the handle of the DLL which will be used to load string resources.
XllLoadString | Loads a string resource, in the current user language.
XllLoadStringForExcelLanguage | Loads a string resource, in the language of the Excel version.
XllTranslateString | Translates a string containing resource IDs to a string in the current user language.

A full list can be found here.


Global resource functions

Global resource functions are listed here.

Global values

public method | XllGetStringLanguageID | Returns the langauge used by XllLoadString()
public method | XllGetStringResourceHandle | Returns the handle of the resource file which will be used by XllLoadString()
public method | XllSetStringLanguageID | Sets the langauge used by XllLoadString()
public method | XllSetStringResourceHandle | Sets the handle of the resource file which will be used by XllLoadString()

Load resources

public method | XllLoadBitmap | Loads a bitmap from a resource file, using the current language
public method | XllLoadBitmapForExcelLanguage | Loads a bitmap from a resource file, for the language of the Excel version
public method | XllLoadBitmapForLanguage | Loads a bitmap from a resource file, using the specified language
public method | XllLoadBitmapForLocale | Loads a bitmap from a resource file, using the specified locale
public method | XllLoadString | Loads a string from the resource file, in the user's language
public method | XllLoadStringA | Loads a string from the resource file, in the user's language
public method | XllLoadStringForExcelLanguage | Loads a string from the resource file, for the language of the Excel version
public method | XllLoadStringForExcelLanguageA | Loads a string from the resource file, for the language of the Excel version
public method | XllLoadStringForExcelLanguageW | Loads a string from the resource file, for the language of the Excel version
public method | XllLoadStringForLanguage | Loads a string from the resource file, in a particular language
public method | XllLoadStringForLanguageA | Loads a string from the resource file, in a particular language
public method | XllLoadStringForLanguageW | Loads a string from the resource file, in a particular language
public method | XllLoadStringForLocale | Loads a string from the resource file, for a particular locale
public method | XllLoadStringForLocaleA | Loads a string from the resource file, for a particular locale
public method | XllLoadStringForLocaleW | Loads a string from the resource file, for a particular locale
public method | XllLoadStringW | Loads a string from the resource file, in the user's language

String translation

public method | XllGetTranslatedString | Translates a string containing resource IDs, for the language of the Excel version
public method | XllGetTranslatedStringA | Translates a string containing resource IDs, for the language of the Excel version
public method | XllGetTranslatedStringW | Translates a string containing resource IDs, for the language of the Excel version
public method | XllTranslateString | Translates a string containing resource IDs, for the language of the Excel version
public method | XllTranslateStringA | Translates a string containing resource IDs, for the language of the Excel version
public method | XllTranslateStringW | Translates a string containing resource IDs, for the language of the Excel version

Excel version

public method | XllGetExcelCountryCode | Returns the country code of Excel
public method | XllGetExcelLanguageID | Returns the language ID corresponding to the country code of Excel

General

public method | ResFindLanguageForResource | Searches a resource file for a resource whose language best matches the language requested
public method | ResFindLanguageForResourceA | Searches a resource file for a resource whose language best matches the language requested
public method | ResFindLanguageForResourceW | Searches a resource file for a resource whose language best matches the language requested
public method | ResGetCountryCodeFromLangID | Translates a language ID to a country code
public method | ResGetLangIDFromCountryCode | Searches for a resource whose language matches the country code
public method | ResGetStringFromStringTable | Gets a string from a resource file in a particular language
public method | ResGetStringFromStringTableA | Gets a string from a resource file in a particular language
public method | ResGetStringFromStringTableW | Gets a string from a resource file in a particular language
public method | ResListLanguages | Gets a list of all supported languages from a resource file
public method | ResListLanguagesA | Gets a list of all supported languages from a resource file
public method | ResListLanguagesW | Gets a list of all supported languages from a resource file
public method | ResLoadBitmap | Loads a bitmap from a resource file, using a specified language
public method | ResLoadString | Gets a string from a resource file using a preferred language
public method | ResLoadStringA | Gets a string from a resource file using a preferred language
public method | ResLoadStringW | Gets a string from a resource file using a preferred language

Requirements

Header: xllres.h

See Also

xllres.h


::ResFindLanguageForResource

Searches a resource file for a resource whose language best matches the language requested

LANGID ResFindLanguageForResource(
   HINSTANCE hinst,
   LPTSTR lpszType,
   LPTSTR lpszName,
   LANGID langidUser
);

Parameters

hinst

Module handle of a resource file.
lpszType

Resource type string, e.g. RT_STRING.
lpszName

Resource name. This may be constructed from an integer ID using the MAKEINTRESOURCE(...) macro.
langidUser

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).

Return Value

The language ID of a particular resource in a language which best matches the language requested, if found. If no such resource is found, then the next best matching language ID is returned. If no match is found, then MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) is returned.

Remarks

This function iterates through all the resources, of the specified type and name, in the resource file until it finds a resource in a language exactly matching langidUser. If no exact match is found then the first partial match (same language but a different sub-language) is returned.

This function is used by XllLoadString() and ResLoadString() to locate language-specific resources.

Requirements

Header: xllres.h

See Also

Global resource functions


::ResFindLanguageForResourceA

Searches a resource file for a resource whose language best matches the language requested

LANGID ResFindLanguageForResourceA(
   HINSTANCE hinst,
   LPSTR lpszType,
   LPSTR lpszName,
   LANGID langidUser
);

Parameters

hinst

Module handle of a resource file.
lpszType

Resource type string, e.g. RT_STRING.
lpszName

Resource name. This may be constructed from an integer ID using the MAKEINTRESOURCE(...) macro.
langidUser

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).

Return Value

The language ID of a particular resource in a language which best matches the language requested, if found. If no such resource is found, then the next best matching language ID is returned. If no match is found, then MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) is returned.

Remarks

This function iterates through all the resources, of the specified type and name, in the resource file until it finds a resource in a language exactly matching langidUser. If no exact match is found then the first partial match (same language but a different sub-language) is returned.

This function is used by XllLoadString() and ResLoadString() to locate language-specific resources.

Requirements

Header: xllres.h

See Also

Global resource functions


::ResFindLanguageForResourceW

Searches a resource file for a resource whose language best matches the language requested

LANGID ResFindLanguageForResourceW(
   HINSTANCE hinst,
   LPSTR lpszType,
   LPSTR lpszName,
   LANGID langidUser
);

Parameters

hinst

Module handle of a resource file.
lpszType

Resource type string, e.g. RT_STRING.
lpszName

Resource name. This may be constructed from an integer ID using the MAKEINTRESOURCE(...) macro.
langidUser

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).

Return Value

The language ID of a particular resource in a language which best matches the language requested, if found. If no such resource is found, then the next best matching language ID is returned. If no match is found, then MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) is returned.

Remarks

This function iterates through all the resources, of the specified type and name, in the resource file until it finds a resource in a language exactly matching langidUser. If no exact match is found then the first partial match (same language but a different sub-language) is returned.

This function is used by XllLoadString() and ResLoadString() to locate language-specific resources.

Requirements

Header: xllres.h

See Also

Global resource functions


::ResGetCountryCodeFromLangID

Translates a language ID to a country code

int ResGetCountryCodeFromLangID(
   LANGID langid
);

Parameters

langid

Language ID. This can be formed using the MAKELANGID(...) macro.

Return Value

Returns an integer representing the main country for the language and sub-language pair contained in the language ID. This normally corresponds to the international telephone dialling code for the country. Returns 0 if the lanuage ID cannot be found, or contains no main country.

Remarks

This function calls the Windows API function GetLocaleInfo(), and looks up LCTYPE LOCALE_ICOUNTRY.

Requirements

Header: xllres.h

See Also

Global resource functions


::ResGetLangIDFromCountryCode

Searches for a resource whose language matches the country code

LANGID ResGetLangIDFromCountryCode(
   HINSTANCE hinst,
   int cc
);

Parameters

hinst

Module handle of a resource file.
cc

A numeric country code, normally corresponding to the international telephone dialling code for the country.

Return Value

The language ID of a resource in the main language of the country, if found. If no such resource is found, then the next best matching language ID is returned. If no match is found, then MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) is returned.

Remarks

This function iterates through all the resources, of any type, in the resource file until it finds a resource in a language whose country code is cc, (as returned by ResGetCountryCodeFromLangID()).

This function is used by XllGetExcelLanguage() to translate the Excel version's country code to a language ID.

Requirements

Header: xllres.h

See Also

Global resource functions


::ResGetStringFromStringTable

Gets a string from a resource file in a particular language

BOOL ResGetStringFromStringTable(
   HINSTANCE hinst,
   UINT uStringID,
   LANGID langid,
   CString& res
);

Parameters

hinst

Module handle of a resource file.
uStringID

Numeric resource string identifier.
langid

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).
res

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the resource file handle is invalid, or if the resource cannot be found.

Remarks

This function looks for a resource string in a specified language and sub-language, and fails if it cannot be found. It is therefore advisable to use this method only for strings which have been specifically located using ResFindLanguageForResource().

Requirements

Header: xllres.h

See Also

Global resource functions


::ResGetStringFromStringTableA

Gets a string from a resource file in a particular language

BOOL ResGetStringFromStringTableA(
   HINSTANCE hinst,
   UINT uStringID,
   LANGID langid,
   CStringA& res
);

Parameters

hinst

Module handle of a resource file.
uStringID

Numeric resource string identifier.
langid

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).
res

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the resource file handle is invalid, or if the resource cannot be found.

Remarks

This function looks for a resource string in a specified language and sub-language, and fails if it cannot be found. It is therefore advisable to use this method only for strings which have been specifically located using ResFindLanguageForResource().

Requirements

Header: xllres.h

See Also

Global resource functions


::ResGetStringFromStringTableW

Gets a string from a resource file in a particular language

BOOL ResGetStringFromStringTableW(
   HINSTANCE hinst,
   UINT uStringID,
   LANGID langid,
   CStringW& res
);

Parameters

hinst

Module handle of a resource file.
uStringID

Numeric resource string identifier.
langid

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).
res

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the resource file handle is invalid, or if the resource cannot be found.

Remarks

This function looks for a resource string in a specified language and sub-language, and fails if it cannot be found. It is therefore advisable to use this method only for strings which have been specifically located using ResFindLanguageForResource().

Requirements

Header: xllres.h

See Also

Global resource functions


::ResListLanguages

Gets a list of all supported languages from a resource file

BOOL ResListLanguages(
   HINSTANCE hinst,
   std::vector<LANGID>& listIDs,
   LCTYPE lctype,
   std::vector<CString>& listNames
);

Parameters

hinst

Module handle of a resource file.
listIDs

Will be populated with a list of the language IDs found.
lctype

The type of language information required. This parameter os one of the LCTYPE values accepted by the API function GetLocaleInfo.
listNames

Will be populated with a list of the information found for each language ID, as selected by lctype.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the resource file handle is invalid, or if lctype is invalid.

Remarks

This function lists all the languages available in a resource file.

Requirements

Header: xllres.h

See Also

Global resource functions


::ResListLanguagesA

Gets a list of all supported languages from a resource file

BOOL ResListLanguagesA(
   HINSTANCE hinst,
   std::vector<LANGID>& listIDs,
   LCTYPE lctype,
   std::vector<CStringA>& listNames
);

Parameters

hinst

Module handle of a resource file.
listIDs

Will be populated with a list of the language IDs found.
lctype

The type of language information required. This parameter os one of the LCTYPE values accepted by the API function GetLocaleInfo.
listNames

Will be populated with a list of the information found for each language ID, as selected by lctype.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the resource file handle is invalid, or if lctype is invalid.

Remarks

This function lists all the languages available in a resource file.

Requirements

Header: xllres.h

See Also

Global resource functions


::ResListLanguagesW

Gets a list of all supported languages from a resource file

BOOL ResListLanguagesW(
   HINSTANCE hinst,
   std::vector<LANGID>& listIDs,
   LCTYPE lctype,
   std::vector<CStringW>& listNames
);

Parameters

hinst

Module handle of a resource file.
listIDs

Will be populated with a list of the language IDs found.
lctype

The type of language information required. This parameter os one of the LCTYPE values accepted by the API function GetLocaleInfo.
listNames

Will be populated with a list of the information found for each language ID, as selected by lctype.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the resource file handle is invalid, or if lctype is invalid.

Remarks

This function lists all the languages available in a resource file.

Requirements

Header: xllres.h

See Also

Global resource functions


::ResLoadBitmap

Loads a bitmap from a resource file, using a specified language

HBITMAP ResLoadBitmap(
   HINSTANCE hinst,
   UINT uBitmapID,
   LANGID langid
);

Parameters

hinst

Module handle of a resource file.
uBitmapID

Numeric bitmap resource identifier.
langid

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).

Return Value

A handle to the loaded bitmap if the function succeeds, NULL if it fails. The bitmap should be released with DeleteObject when no longer in use.

Remarks

This function loads a bitmap from a resource file, using the specified language if possible.

The bitmap should be released with DeleteObject when no longer in use.

Requirements

Header: xllres.h

See Also

Global resource functions


::ResLoadString

Gets a string from a resource file using a preferred language

BOOL ResLoadString(
   HINSTANCE hinst,
   UINT uStringID,
   LANGID langid,
   CString& res
);
BOOL ResLoadString(
   HINSTANCE hinst,
   UINT uStringID,
   CString& res
);

Parameters

hinst

Module handle of a resource file.
uStringID

Numeric resource string identifier.
langid

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).
res

If the function succeeds, the string will be loaded into this variable.
hinst
uStringID
res

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the resource file handle is invalid, or if the resource cannot be found.

Remarks

This function looks for a resource string in a specified language and sub-language. If an exact match cannot be found, then the first resource with a matching language (but not matching sub-language) is loaded. If no such match can be found, then the language neutral resource is loaded.

The second variant uses the user's current setting (from GetThreadLocale()) to create a language ID.

Requirements

Header: xllres.h

See Also

Global resource functions


::ResLoadStringA

Gets a string from a resource file using a preferred language

BOOL ResLoadStringA(
   HINSTANCE hinst,
   UINT uStringID,
   LANGID langid,
   CStringA& res
);
BOOL ResLoadStringA(
   HINSTANCE hinst,
   UINT uStringID,
   CStringA& res
);

Parameters

hinst

Module handle of a resource file.
uStringID

Numeric resource string identifier.
langid

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).
res

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the resource file handle is invalid, or if the resource cannot be found.

Remarks

This function looks for a resource string in a specified language and sub-language. If an exact match cannot be found, then the first resource with a matching language (but not matching sub-language) is loaded. If no such match can be found, then the language neutral resource is loaded.

The second variant uses the user's current setting (from GetThreadLocale()) to create a language ID.

Requirements

Header: xllres.h

See Also

Global resource functions


::ResLoadStringW

Gets a string from a resource file using a preferred language

BOOL ResLoadStringW(
   HINSTANCE hinst,
   UINT uStringID,
   LANGID langid,
   CStringW& res
);
BOOL ResLoadStringW(
   HINSTANCE hinst,
   UINT uStringID,
   CStringW& res
);

Parameters

hinst

Module handle of a resource file.
uStringID

Numeric resource string identifier.
langid

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).
res

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the resource file handle is invalid, or if the resource cannot be found.

Remarks

This function looks for a resource string in a specified language and sub-language. If an exact match cannot be found, then the first resource with a matching language (but not matching sub-language) is loaded. If no such match can be found, then the language neutral resource is loaded.

The second variant uses the user's current setting (from GetThreadLocale()) to create a language ID.

Requirements

Header: xllres.h

See Also

Global resource functions


::XllGetExcelCountryCode

Returns the country code of Excel

int XllGetExcelCountryCode( );

Return Value

Returns the Excel version's country code. This normally corresponds to the international telephone dialling code for the country.

Remarks

This function calls CXllApp::GetInternational(), and looks up XlInternationalCountryCode.

Requirements

Header: xllres.h

See Also

Global resource functions


::XllGetExcelLanguageID

Returns the language ID corresponding to the country code of Excel

LANGID XllGetExcelLanguageID( );

Return Value

Returns the language ID corresponding to the Excel version's country code.

Remarks

This function calls ResGetLangIDFromCountryCode() to translate the result of XllGetExcelCountryCode() to a language ID available in the resource file.

Requirements

Header: xllres.h

See Also

Global resource functions


::XllGetStringLanguageID

Returns the langauge used by XllLoadString()

LANGID XllGetStringLanguageID( );

Return Value

The ID of the language file used by XLL+ string loading functions. Unless set using XllSetStringLanguageID(), this will be the langauge returned by GetThreadLocale.

Remarks

All calls to XllLoadString and XllTranslateString will attempt to use the language returned by this call.

Requirements

Header: xllres.h

See Also

Global resource functions


::XllGetStringResourceHandle

Returns the handle of the resource file which will be used by XllLoadString()

HINSTANCE XllGetStringResourceHandle( );

Return Value

The handle of the resource file used by XLL+ string loading functions. Unless set using XllSetStringResourceHandle(), this will be a handle to the XLL file itself.

Remarks

All calls to XllLoadString and XllTranslateString will use the resource file returned by this call.

Requirements

Header: xllres.h

See Also

Global resource functions


::XllGetTranslatedString

Translates a string containing resource IDs, for the language of the Excel version

CString XllGetTranslatedString(
   const TCHAR* pszIn
);

Parameters

pszIn

input string, which may contain numeric resource string identifiers. See Remarks below.

Return Value

If the function succeeds, the translated string will be returned. If it fails, then an untranslated or partially translated string will be returned.

Remarks

This function attempts to replace the resource string IDs in the input string with resource strings loaded from the current resource file. The resource file searched will be that returned by XllGetStringResourceHandle). The language used will be either the current user preference (as returned by GetThreadLocale()) or the language of the Excel version (as returned by XllGetExcelLanguageID).

String identifiers should be in one of the following forms:

  • Integers preceded by a # sign, e.g.: #123, which will be replaced by strings in the user's language.
  • Integers preceded by "#@", e.g.: #@123, which will be replaced by strings in the language of the Excel version that is running.

String substitutions

This function calls XllTranslateString and ignores errors.

Requirements

Header: xllres.h

See Also

Global resource functions | XllTranslateString


::XllGetTranslatedStringA

Translates a string containing resource IDs, for the language of the Excel version

CStringA XllGetTranslatedStringA(
   const char* pszIn
);

Parameters

pszIn

input string, which may contain numeric resource string identifiers. See Remarks below.

Return Value

If the function succeeds, the translated string will be returned. If it fails, then an untranslated or partially translated string will be returned.

Remarks

This function attempts to replace the resource string IDs in the input string with resource strings loaded from the current resource file. The resource file searched will be that returned by XllGetStringResourceHandle). The language used will be either the current user preference (as returned by GetThreadLocale()) or the language of the Excel version (as returned by XllGetExcelLanguageID).

String identifiers should be in one of the following forms:

  • Integers preceded by a # sign, e.g.: #123, which will be replaced by strings in the user's language.
  • Integers preceded by "#@", e.g.: #@123, which will be replaced by strings in the language of the Excel version that is running.

String substitutions

This function calls XllTranslateString and ignores errors.

Requirements

Header: xllres.h

See Also

Global resource functions | XllTranslateString


::XllGetTranslatedStringW

Translates a string containing resource IDs, for the language of the Excel version

CStringW XllGetTranslatedStringW(
   const wchar_t* pszIn
);

Parameters

pszIn

input string, which may contain numeric resource string identifiers. See Remarks below.

Return Value

If the function succeeds, the translated string will be returned. If it fails, then an untranslated or partially translated string will be returned.

Remarks

This function attempts to replace the resource string IDs in the input string with resource strings loaded from the current resource file. The resource file searched will be that returned by XllGetStringResourceHandle). The language used will be either the current user preference (as returned by GetThreadLocale()) or the language of the Excel version (as returned by XllGetExcelLanguageID).

String identifiers should be in one of the following forms:

  • Integers preceded by a # sign, e.g.: #123, which will be replaced by strings in the user's language.
  • Integers preceded by "#@", e.g.: #@123, which will be replaced by strings in the language of the Excel version that is running.

String substitutions

This function calls XllTranslateString and ignores errors.

Requirements

Header: xllres.h

See Also

Global resource functions | XllTranslateString


::XllLoadBitmap

Loads a bitmap from a resource file, using the current language

HBITMAP XllLoadBitmap(
   UINT uBitmapID
);

Parameters

uBitmapID

Numeric bitmap resource identifier.

Return Value

A handle to the loaded bitmap if the function succeeds, NULL if it fails. The bitmap should be released with DeleteObject when no longer in use.

Remarks

This function loads a bitmap from a resource file, using the current language, as returned by XllGetStringLanguageID, if possible.

The bitmap should be released with DeleteObject when no longer in use.

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadBitmapForExcelLanguage

Loads a bitmap from a resource file, for the language of the Excel version

HBITMAP XllLoadBitmapForExcelLanguage(
   UINT uBitmapID
);

Parameters

uBitmapID

Numeric bitmap resource identifier.

Return Value

A handle to the loaded bitmap if the function succeeds, NULL if it fails. The bitmap should be released with DeleteObject when no longer in use.

Remarks

This function loads a bitmap from a resource file, using the Excel version language, as returned by XllGetExcelLanguageID(), if possible.

The bitmap should be released with DeleteObject when no longer in use.

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadBitmapForLanguage

Loads a bitmap from a resource file, using the specified language

HBITMAP XllLoadBitmapForLanguage(
   UINT uBitmapID,
   LANGID langid
);

Parameters

uBitmapID

Numeric bitmap resource identifier.
langid

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).

Return Value

A handle to the loaded bitmap if the function succeeds, NULL if it fails. The bitmap should be released with DeleteObject when no longer in use.

Remarks

This function loads a bitmap from a resource file, using the specified language if possible.

The bitmap should be released with DeleteObject when no longer in use.

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadBitmapForLocale

Loads a bitmap from a resource file, using the specified locale

HBITMAP XllLoadBitmapForLocale(
   UINT uBitmapID,
   LCID lcid
);

Parameters

uBitmapID

Numeric bitmap resource identifier.
lcid

The locale ID of the desired locale. This can be formed using the MAKELCID(...) macro, or found using GetThreadLocale().

Return Value

A handle to the loaded bitmap if the function succeeds, NULL if it fails. The bitmap should be released with DeleteObject when no longer in use.

Remarks

This function loads a bitmap from a resource file, using the specified locale if possible.

The bitmap should be released with DeleteObject when no longer in use.

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadString

Loads a string from the resource file, in the user's language

BOOL XllLoadString(
   UINT resid,
   CString& str
);

Parameters

resid

Numeric resource string identifier.
str

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the current resource file handle is invalid, or if the resource cannot be found.

Remarks

The function searches for a string resource in the user's language, as found through GetThreadLocale(). It is equivalent to calling:

XllLoadStringForLanguage(resid, LANGIDFROMLCID(GetThreadLocale()), str);

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadStringA

Loads a string from the resource file, in the user's language

BOOL XllLoadStringA(
   UINT resid,
   CStringA& str
);

Parameters

resid

Numeric resource string identifier.
str

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the current resource file handle is invalid, or if the resource cannot be found.

Remarks

The function searches for a string resource in the user's language, as found through GetThreadLocale(). It is equivalent to calling:

XllLoadStringForLanguage(resid, LANGIDFROMLCID(GetThreadLocale()), str);

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadStringForExcelLanguage

Loads a string from the resource file, for the language of the Excel version

BOOL XllLoadStringForExcelLanguage(
   UINT resid,
   CString& str
);

Parameters

resid

Numeric resource string identifier.
str

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the current resource file handle is invalid, or if the resource cannot be found.

Remarks

The function searches for a string resource in the language implied by the country code of the version of Excel that is running. It is equivalent to calling:

XllLoadStringForLanguage(resid, XllGetExcelLanguage(), str);

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadStringForExcelLanguageA

Loads a string from the resource file, for the language of the Excel version

BOOL XllLoadStringForExcelLanguageA(
   UINT resid,
   CStringA& str
);

Parameters

resid

Numeric resource string identifier.
str

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the current resource file handle is invalid, or if the resource cannot be found.

Remarks

The function searches for a string resource in the language implied by the country code of the version of Excel that is running. It is equivalent to calling:

XllLoadStringForLanguage(resid, XllGetExcelLanguage(), str);

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadStringForExcelLanguageW

Loads a string from the resource file, for the language of the Excel version

BOOL XllLoadStringForExcelLanguageW(
   UINT resid,
   CStringW& str
);

Parameters

resid

Numeric resource string identifier.
str

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the current resource file handle is invalid, or if the resource cannot be found.

Remarks

The function searches for a string resource in the language implied by the country code of the version of Excel that is running. It is equivalent to calling:

XllLoadStringForLanguage(resid, XllGetExcelLanguage(), str);

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadStringForLanguage

Loads a string from the resource file, in a particular language

BOOL XllLoadStringForLanguage(
   UINT resid,
   LANGID langid,
   CString& str
);

Parameters

resid

Numeric resource string identifier.
langid

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).
str

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the current resource file handle is invalid, or if the resource cannot be found.

Remarks

The function searches the current string resource file (as returned by XllGetStringResourceHandle) for a string resource in the specified language, using the logic described in ResLoadString().

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadStringForLanguageA

Loads a string from the resource file, in a particular language

BOOL XllLoadStringForLanguageA(
   UINT resid,
   LANGID langid,
   CStringA& str
);

Parameters

resid

Numeric resource string identifier.
langid

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).
str

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the current resource file handle is invalid, or if the resource cannot be found.

Remarks

The function searches the current string resource file (as returned by XllGetStringResourceHandle) for a string resource in the specified language, using the logic described in ResLoadString().

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadStringForLanguageW

Loads a string from the resource file, in a particular language

BOOL XllLoadStringForLanguageW(
   UINT resid,
   LANGID langid,
   CStringW& str
);

Parameters

resid

Numeric resource string identifier.
langid

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).
str

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the current resource file handle is invalid, or if the resource cannot be found.

Remarks

The function searches the current string resource file (as returned by XllGetStringResourceHandle) for a string resource in the specified language, using the logic described in ResLoadString().

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadStringForLocale

Loads a string from the resource file, for a particular locale

BOOL XllLoadStringForLocale(
   UINT resid,
   LCID lcid,
   CString& str
);

Parameters

resid

Numeric resource string identifier.
lcid

The locale ID of the desired locale. This can be formed using the MAKELCID(...) macro, or found using GetThreadLocale().
str

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the current resource file handle is invalid, or if the resource cannot be found.

Remarks

The function searches for a string resource in the language implied by the locale. It is equivalent to calling:

XllLoadStringForLanguage(resid, LANGIDFROMLCID(lcid), str);

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadStringForLocaleA

Loads a string from the resource file, for a particular locale

BOOL XllLoadStringForLocaleA(
   UINT resid,
   LCID lcid,
   CStringA& str
);

Parameters

resid

Numeric resource string identifier.
lcid

The locale ID of the desired locale. This can be formed using the MAKELCID(...) macro, or found using GetThreadLocale().
str

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the current resource file handle is invalid, or if the resource cannot be found.

Remarks

The function searches for a string resource in the language implied by the locale. It is equivalent to calling:

XllLoadStringForLanguage(resid, LANGIDFROMLCID(lcid), str);

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadStringForLocaleW

Loads a string from the resource file, for a particular locale

BOOL XllLoadStringForLocaleW(
   UINT resid,
   LCID lcid,
   CStringW& str
);

Parameters

resid

Numeric resource string identifier.
lcid

The locale ID of the desired locale. This can be formed using the MAKELCID(...) macro, or found using GetThreadLocale().
str

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the current resource file handle is invalid, or if the resource cannot be found.

Remarks

The function searches for a string resource in the language implied by the locale. It is equivalent to calling:

XllLoadStringForLanguage(resid, LANGIDFROMLCID(lcid), str);

Requirements

Header: xllres.h

See Also

Global resource functions


::XllLoadStringW

Loads a string from the resource file, in the user's language

BOOL XllLoadStringW(
   UINT resid,
   CStringW& str
);

Parameters

resid

Numeric resource string identifier.
str

If the function succeeds, the string will be loaded into this variable.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if the current resource file handle is invalid, or if the resource cannot be found.

Remarks

The function searches for a string resource in the user's language, as found through GetThreadLocale(). It is equivalent to calling:

XllLoadStringForLanguage(resid, LANGIDFROMLCID(GetThreadLocale()), str);

Requirements

Header: xllres.h

See Also

Global resource functions


::XllSetStringLanguageID

Sets the langauge used by XllLoadString()

LANGID XllSetStringLanguageID(
   LANGID langid
);

Parameters

langid

The language ID of the desired language. This can be formed using the MAKELANGID(...) macro, or found using LANGIDFROMLCID(GetThreadLocale()).

A value of 0 will set the language back to the default setting (as returned by GetThreadLocale).

Return Value

The previous value.

Remarks

All calls to XllLoadString and XllTranslateString will attempt to use the language specified in this call.

Requirements

Header: xllres.h

See Also

Global resource functions


::XllSetStringResourceHandle

Sets the handle of the resource file which will be used by XllLoadString()

HINSTANCE XllSetStringResourceHandle(
   HINSTANCE hinst
);

Parameters

hinst

Module handle of a resource file.

Return Value

The previous value.

Remarks

All calls to XllLoadString and XllTranslateString will use the resource file specified in this call.

Requirements

Header: xllres.h

See Also

Global resource functions


::XllTranslateString

Translates a string containing resource IDs, for the language of the Excel version

BOOL XllTranslateString(
   const TCHAR* pszIn,
   CString& strOut
);

Parameters

pszIn

input string, which may contain numeric resource string identifiers. See Remarks below.
strOut

If the function succeeds, the translated string will be loaded into this variable. If it fails, then an untranslated or partially translated string will be placed here.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if any the resources cannot be found or if the current resource file handle is invalid. If it fails, then a partially or wholly untranslated string will be returned.

Remarks

This function attempts to replace the resource string IDs in the input string with resource strings loaded from the current resource file. The resource file searched will be that returned by XllGetStringResourceHandle). The language used will be either the current user preference (as returned by GetThreadLocale()) or the language of the Excel version (as returned by XllGetExcelLanguageID).

String identifiers should be in one of the following forms:

  • Integers preceded by a # sign, e.g.: #123, which will be replaced by strings in the user's language.
  • Integers preceded by "#@", e.g.: #@123, which will be replaced by strings in the language of the Excel version that is running.

String substitutions

String substitution by XLL+ functions

The functions, macros and data members that accept and translate resource ID strings are listed below.

IMPLEMENT_XLLFN2 | IMPLEMENT_XLLFN_EX | CXllApp::m_stName
CXllApp::WinMessageBox | CXllApp::XlMessageBox | CXllFn::m_stCategory
CXllFn::m_stHelpText | CXllFn::m_astArgHelpText | CXllFn::m_astArgExt
CXlMenu::Create | CXlMenu::AddItem | CXlMenu::SetTexts
CXlMenu::DeleteItem | CXlMenu::ReplaceItem | CXlMenu::EnableItem
CXlMenu::CheckItem | CXlToolbar::AddSeparator | CXlToolbar::AddTool
CXlToolbar::AddToolbar | CXlToolbar::AssignToTool | CXlToolbar::DeleteTool
CXlToolbar::DeleteToolbar | CXlToolbar::EnableTool | CXlToolbar::PressTool
CXlToolbar::SetToolBitmap | CXlToolbar::ShowToolbar |

Requirements

Header: xllres.h

See Also

Global resource functions


::XllTranslateStringA

Translates a string containing resource IDs, for the language of the Excel version

BOOL XllTranslateStringA(
   const char* pszIn,
   CStringA& strOut
);

Parameters

pszIn

input string, which may contain numeric resource string identifiers. See Remarks below.
strOut

If the function succeeds, the translated string will be loaded into this variable. If it fails, then an untranslated or partially translated string will be placed here.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if any the resources cannot be found or if the current resource file handle is invalid. If it fails, then a partially or wholly untranslated string will be returned.

Remarks

This function attempts to replace the resource string IDs in the input string with resource strings loaded from the current resource file. The resource file searched will be that returned by XllGetStringResourceHandle). The language used will be either the current user preference (as returned by GetThreadLocale()) or the language of the Excel version (as returned by XllGetExcelLanguageID).

String identifiers should be in one of the following forms:

  • Integers preceded by a # sign, e.g.: #123, which will be replaced by strings in the user's language.
  • Integers preceded by "#@", e.g.: #@123, which will be replaced by strings in the language of the Excel version that is running.

String substitutions

String substitution by XLL+ functions

The functions, macros and data members that accept and translate resource ID strings are listed below.

IMPLEMENT_XLLFN2 | IMPLEMENT_XLLFN_EX | CXllApp::m_stName
CXllApp::WinMessageBox | CXllApp::XlMessageBox | CXllFn::m_stCategory
CXllFn::m_stHelpText | CXllFn::m_astArgHelpText | CXllFn::m_astArgExt
CXlMenu::Create | CXlMenu::AddItem | CXlMenu::SetTexts
CXlMenu::DeleteItem | CXlMenu::ReplaceItem | CXlMenu::EnableItem
CXlMenu::CheckItem | CXlToolbar::AddSeparator | CXlToolbar::AddTool
CXlToolbar::AddToolbar | CXlToolbar::AssignToTool | CXlToolbar::DeleteTool
CXlToolbar::DeleteToolbar | CXlToolbar::EnableTool | CXlToolbar::PressTool
CXlToolbar::SetToolBitmap | CXlToolbar::ShowToolbar |

Requirements

Header: xllres.h

See Also

Global resource functions


::XllTranslateStringW

Translates a string containing resource IDs, for the language of the Excel version

BOOL XllTranslateStringW(
   const wchar_t* pszIn,
   CStringW& strOut
);

Parameters

pszIn

input string, which may contain numeric resource string identifiers. See Remarks below.
strOut

If the function succeeds, the translated string will be loaded into this variable. If it fails, then an untranslated or partially translated string will be placed here.

Return Value

TRUE if the function succeeds, FALSE if it fails. It will fail if any the resources cannot be found or if the current resource file handle is invalid. If it fails, then a partially or wholly untranslated string will be returned.

Remarks

This function attempts to replace the resource string IDs in the input string with resource strings loaded from the current resource file. The resource file searched will be that returned by XllGetStringResourceHandle). The language used will be either the current user preference (as returned by GetThreadLocale()) or the language of the Excel version (as returned by XllGetExcelLanguageID).

String identifiers should be in one of the following forms:

  • Integers preceded by a # sign, e.g.: #123, which will be replaced by strings in the user's language.
  • Integers preceded by "#@", e.g.: #@123, which will be replaced by strings in the language of the Excel version that is running.

String substitutions

String substitution by XLL+ functions

The functions, macros and data members that accept and translate resource ID strings are listed below.

IMPLEMENT_XLLFN2 | IMPLEMENT_XLLFN_EX | CXllApp::m_stName
CXllApp::WinMessageBox | CXllApp::XlMessageBox | CXllFn::m_stCategory
CXllFn::m_stHelpText | CXllFn::m_astArgHelpText | CXllFn::m_astArgExt
CXlMenu::Create | CXlMenu::AddItem | CXlMenu::SetTexts
CXlMenu::DeleteItem | CXlMenu::ReplaceItem | CXlMenu::EnableItem
CXlMenu::CheckItem | CXlToolbar::AddSeparator | CXlToolbar::AddTool
CXlToolbar::AddToolbar | CXlToolbar::AssignToTool | CXlToolbar::DeleteTool
CXlToolbar::DeleteToolbar | CXlToolbar::EnableTool | CXlToolbar::PressTool
CXlToolbar::SetToolBitmap | CXlToolbar::ShowToolbar |

Requirements

Header: xllres.h

See Also

Global resource functions


XllRtdFeedServerProxy.h

Overview

XllRtdFeedServerProxy.h contains classes that support the use of Real-time data (RTD) using the XllRtdFeed RTD server.

Classes

The table below lists the principal C++ object classes declared in the header file.

Class | Description
IXllRtdFeedCallback | Contains a common API for the XllRtdFeed RTD server, for calls from the RTD server to XLL clients.
CXllRtdFeedServerProxy | Contains an API for use with the XllRtdFeed RTD server, for calls from an XLL client to the RTD server.

See Also

XllRtdFeed RTD server


CXllRtdFeedServerProxy Class

Contains an API for use with the XllRtdFeed RTD server, for calls from an XLL client to the RTD server.

class CXllRtdFeedServerProxy

Overview

An XLL add-in makes calls to the RTD server via the CXllRtdFeedServerProxy class.

The XLL also must provide a callback object, derived from IXllRtdFeedCallback, which will handle events raised by the RTD server.

Initialization and termination

During initialization (usually OnXllOpenEx()), a client should create an instance of a class that implements IXllRtdFeedCallback, and pass it to the RTD server via CXllRtdFeedServerProxy::RegisterClient().

The instance should be removed during termination (usually OnXllClose()) with CXllRtdFeedServerProxy::UnregisterClient().

Usage

An XLL should call CallRtd during an add-in function to indicate that the result is dynamic data linked to the specified topic string, and that the caller range should be recalculated whenever the topic is updated.

An XLL should call UpdateTopic whenever the specified topic has been updated. Any cells depending on the topic will automatically be recalculated. This method may be called from any thread.

Requirements

Header: XllRtdFeedServerProxy.h

See Also

CXllRtdFeedServerProxy Methods | XllRtdFeedServerProxy.h | XllRtdFeed RTD server | IXllRtdFeedCallback class


CXllRtdFeedServerProxy Methods

The methods of the CXllRtdFeedServerProxy class are listed here.

Construction

public method CXllRtdFeedServerProxy Constructs a CXllRtdFeedServerProxy object

Initialization and termination

public method | RegisterClient | Registers the calling XLL as a client of the RTD server, and initializes the RTD server if necessary.
public method | UnregisterClient | Unregisters as a client of the RTD server. No further call-backs will be routed to the client.

Operations

public method | CallRtd | Makes a call to the RTD server, via Excel, indicating to Excel that the result of the current add-in function is dynamic.
public method | UpdateTopic | Informs Excel that the specified topic has been updated, and that cells linked to it should be recalculated.

Requirements

Header: XllRtdFeedServerProxy.h

See Also

CXllRtdFeedServerProxy Class | XllRtdFeedServerProxy.h | XllRtdFeed RTD server | IXllRtdFeedCallback class


CXllRtdFeedServerProxy::CallRtd

Makes a call to the RTD server, via Excel, indicating to Excel that the result of the current add-in function is dynamic.

int CallRtd(
   CXlOper& xloRtdResult,
   LPCWSTR lpszTopic
);

Parameters

xloRtdResult

A reference to a CXlOper object that will receive the result of the RTD call. This result is usually ignored by client applications.

lpszTopic

A pointer to a null-terminated unicode string containing the topic to which the calling cell will be linked.

Remarks

This call should be made during an add-in function that returns dynamic data. Whenever the topic's data is updated, the caller cell will be recalculated.

Requirements

Header: XllRtdFeedServerProxy.h

See Also

CXllRtdFeedServerProxy Class | CXllRtdFeedServerProxy Methods


CXllRtdFeedServerProxy::CXllRtdFeedServerProxy

Constructs a CXllRtdFeedServerProxy object

CXllRtdFeedServerProxy( );

Remarks

This constructor creates an instance of CXllRtdFeedServerProxy.

Requirements

Header: XllRtdFeedServerProxy.h

See Also

CXllRtdFeedServerProxy Class | CXllRtdFeedServerProxy Methods


CXllRtdFeedServerProxy::RegisterClient

Registers the calling XLL as a client of the RTD server, and initializes the RTD server if necessary.

bool RegisterClient(
   LPCWSTR lpszClient,
   IXllRtdFeedCallback* callback
);

Parameters

lpszClient

A pointer to a null-terminated unicode string containing the name of the client. This should be a name used only by this XLL. The RTD server can support multiple XLLs simultaneously, and therefore each client XLL must have a unique name. You can safely use the file name of the XLL for this purpose.

callback

A pointer to an instance of a class derived from IXllRtdFeedCallback. This instance will receive events from the RTD serevr via call-back functions.

Return Value

The function will return true if the registration succeeded. It will return false if registration failed, or if the RTD server could not be initialized.

Remarks

An XLL should call RegisterClient during initialization, usually during CXllApp::OnXllOpenEx.

Requirements

Header: XllRtdFeedServerProxy.h

See Also

CXllRtdFeedServerProxy Class | CXllRtdFeedServerProxy Methods


CXllRtdFeedServerProxy::UnregisterClient

Unregisters as a client of the RTD server. No further call-backs will be routed to the client.

bool UnregisterClient( );

Return Value

The function will return true if unregistration succeeded. It will return false if the client could not be found.

Remarks

An XLL should call RegisterClient during close-down, usually during CXllApp::OnXllClose.

Requirements

Header: XllRtdFeedServerProxy.h

See Also

CXllRtdFeedServerProxy Class | CXllRtdFeedServerProxy Methods


CXllRtdFeedServerProxy::UpdateTopic

Informs Excel that the specified topic has been updated, and that cells linked to it should be recalculated.

void UpdateTopic(
   LPCWSTR lpszTopic
);

Parameters

lpszTopic

A pointer to a null-terminated unicode string containing the topic whose value has been updated.

Remarks

This function informs the RTD server that the specified topic has been updated. Any cells depending on the topic will automatically be recalculated. This method may be called from any thread.

Requirements

Header: XllRtdFeedServerProxy.h

See Also

CXllRtdFeedServerProxy Class | CXllRtdFeedServerProxy Methods


IXllRtdFeedCallback Class

Contains a common API for the XllRtdFeed RTD server, for calls from the RTD server to XLL clients.

class IXllRtdFeedCallback

Overview

IXllRtdFeedCallback is the abstract base class that handles events raised by the XllRtdFeed RTD server. A class that is derived from IXllRtdFeedCallback must implement two virtual functions: OnGetDataState() and OnTopicRemoved().

An XLL that uses the XllRtdFeed RTD server must create an instance of a class derived from IXllRtdFeedCallback, and pass a pointer to the instance using CXllRtdFeedServerProxy::RegisterClient().

Instantiation

During initialization (usually OnXllOpenEx()), a client should create an instance of a class that implements IXllRtdFeedCallback, and pass it to the RTD server via CXllRtdFeedServerProxy::RegisterClient().

The instance should be removed during termination (usually OnXllClose()) with CXllRtdFeedServerProxy::UnregisterClient().

Requirements

Header: XllRtdFeedServerProxy.h

See Also

IXllRtdFeedCallback Methods | XllRtdFeedServerProxy.h | XllRtdFeed RTD server | CXllRtdFeedServerProxy class


IXllRtdFeedCallback Methods

The methods of the IXllRtdFeedCallback class are listed here.

Callbacks

public method | OnGetDataState | Called by the RTD server whenever Excel requests data for the specified topic.
public method | OnTopicRemoved | Called by the RTD server whenever a topic has been removed from the RTD server's list of active topics.

Construction

public method IXllRtdFeedCallback Constructs a IXllRtdFeedCallback object

Requirements

Header: XllRtdFeedServerProxy.h

See Also

IXllRtdFeedCallback Class | XllRtdFeedServerProxy.h | XllRtdFeed RTD server | CXllRtdFeedServerProxy class


IXllRtdFeedCallback::IXllRtdFeedCallback

Constructs a IXllRtdFeedCallback object

IXllRtdFeedCallback( );

Requirements

Header: XllRtdFeedServerProxy.h

See Also

IXllRtdFeedCallback Class | IXllRtdFeedCallback Methods


IXllRtdFeedCallback::OnGetDataState

Called by the RTD server whenever Excel requests data for the specified topic.

virtual bool OnGetDataState(
   LPCWSTR lpszClient,
   LPCWSTR lpszTopic,
   LPVARIANT lpvntState
);

Parameters

lpszClient

A pointer to a null-terminated unicode string containing the name of the client. This will always be the same as the value passed in CXllRtdFeedServerProxy::RegisterClient().

lpszTopic

A pointer to a null-terminated unicode string containing the topic about which Excel requires information.

lpvntState

A pointer to an empty VARIANT which should be populated with the state value for the requested topic.

Remarks

This call may occur at any of three points:

  1. For a new topic, that has just been requested from an add-in function, via a call to CXllRtdFeedServerProxy::CallRtd().
  2. From a range in a previously saved workbook which has been reopened.
  3. For a topic that has been updated by the client XLL using CXllRtdFeedServerProxy::UpdateTopic().

If data is available, the implementation method should set *lpvntState to a scalar state variable and return true. If no data is yet available, the implementation method should return false.

Requirements

Header: XllRtdFeedServerProxy.h

See Also

IXllRtdFeedCallback Class | IXllRtdFeedCallback Methods


IXllRtdFeedCallback::OnTopicRemoved

Called by the RTD server whenever a topic has been removed from the RTD server's list of active topics.

virtual bool OnTopicRemoved(
   LPCWSTR lpszClient,
   LPCWSTR lpszTopic,
   long lTopicID
);

Parameters

lpszClient

A pointer to a null-terminated unicode string containing the name of the client. This will always be the same as the value passed in CXllRtdFeedServerProxy::RegisterClient().

lpszTopic

A pointer to a null-terminated unicode string containing the topic about which Excel requires information.

lTopicID

The numeric topic identifier assigned by Excel for this topic.

Remarks

This call will occur after the last cell range that uses the topic is removed, closed, or for any other reason ceases to be connected to the specified topic - for instance because an argument to a formula has changed, and therefore the topic has changed.

The call is not guaranteed to come immediately after the topic becomes unused. Excel controls the timing.

Requirements

Header: XllRtdFeedServerProxy.h

See Also

IXllRtdFeedCallback Class | IXllRtdFeedCallback Methods


xlmarshal.h

Overview

xlmarshal.h contains classes that allow you to convert Excel argument and result types to and from a byte stream.

This behavior is useful for several reasons:

  1. Cacheing results. The byte stream can be used as an efficient key to a map. This means you can very easily cache the results of an add-in function in a map keyed by its inputs. The CXlOperCache class implements this behavior.
  2. Persistence. A byte stream can be saved to file explicitly, or can be save as binary data with any worksheet.
  3. Messaging. The byte stream can be passed along pipes or other simple channels, between threads, processes or machines.

Classes

Class | Description
CXlMarshaledData | A byte stream containing native and Excel data types.
CXlInputKey | A specialised instance of marshaled data, which contains all the inputs to an add-in function, as a byte stream.
CXlOperCache | A data store holding the results of functions, keyed by the values of all inputs.

See Also

CXlMarshaledData object | CXlInputKey object | CXlOperCache object | xldialog.h


CXlMarshaledData Class

Converts Excel data-types to and from a byte stream.

class CXlMarshaledData

Overview

The CXlMarshaledData class can be used to convert Excel data-types to and from a byte stream.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Methods | xlmarshal.h | CXlOperCache class | CXlInputKey class | Cache sample


CXlMarshaledData Methods

The methods of the CXlMarshaledData class are listed here.

Construction

public method CXlMarshaledData Constructs a CXlMarshaledData object

Assignment operators

public method operator = Assigns a new value to the byte stream

Data operations

public method | Attach | Attaches the supplied data to the object, replacing any current contents
public method | Clear | Clears all data
public method | Detach | Detaches the current data from the object
public method | MoveFrom | Detaches the data from another object and attaches it to this object
public method | Set | Copies the supplied data into the object, replacing any current contents

Operations

public method ReadArgs Returns the state of the byte stream buffer

Accessor methods

public method | GetCount | Returns the size of the byte stream buffer
public method | GetData | Returns a pointer to the byte stream buffer
public method | IsGood | Returns the state of the byte stream buffer

Memory management

Alloc | Allocates memory for a byte stream
Destroy | Deallocates memory for a byte stream

Comparison methods & operators

public method | Compare | Compares the object with another
public method | operator != | Compares the object with another
public method | operator < | Compares the object with another
public method | operator <= | Compares the object with another
public method | operator = | Compares the object with another
public method | operator > | Compares the object with another
public method | operator >= | Compares the object with another

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | xlmarshal.h | CXlOperCache class | CXlInputKey class | Cache sample


CXlMarshaledData::Alloc

Allocates memory for a byte stream

static void* Alloc(
   size_t cbData
) const;

Parameters

cbData

Number of bytes required.

Return Value

Returns a pointer to tha allocated memory.

Remarks

This static function allocates memory for a byte stream. This allocator should be used for any memory that will be attached to an object using the Attach() method. Unless the buffer is later attached to another object, it should be deallocated using the CXlMarshaledData::Destroy() static method.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::Attach

Attaches the supplied data to the object, replacing any current contents

void Attach(
   void* pvData,
   size_t cbData
) const;

Parameters

pvData

A pointer to an array of bytes, of size cbData.
cbData

Size of array of bytes.

Remarks

This function removes the current contents and replace them with a reference to the supplied data buffer. The buffer must have been allocated using the CXlMarshaledData::Alloc() static method.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::Clear

Clears all data

void Clear( );

Remarks

This function clears the byte stream from the object and releases all memory.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::Compare

Compares the object with another

int Compare(
   const CXlMarshaledData& that
) const;

Parameters

that

A CXlMarshaledData object that will be compared to *this.

Return Value

This function compares the current object with another and returns -1, 0 or 1 depending on their order.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::CXlMarshaledData

Constructs a CXlMarshaledData object

CXlMarshaledData( );
CXlMarshaledData(
   const char* pszFnName,
   void* pvFirstArg,
   bool bPrefixFn
);
CXlMarshaledData(
   void* pvData,
   size_t cbData
);
CXlMarshaledData(
   const CXlMarshaledData& srcKey
);

Parameters

pszFnName

Name of add-in function whose arguments are being converted to a byte stream.
pvFirstArg

Address of the first argument to the add-in function. This pointer is used to traverse the argument stack, using the add-in function's registered definition to interpret the items in the stack.
bPrefixFn

If true, the name of the function will be prefixed to the byte stream. This is useful if a single cache is used for more than one add-in function. If false, then the function is not prefixed. This is appropriate if each add-in function uses its own cache.
pvData

A pointer to an array of bytes, of size cbData.
cbData

Size of array of bytes.
srcKey

An object to be deep copied.

Remarks

This method constructs a CXlMarshaledData object.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::Destroy

Deallocates memory for a byte stream

static void Destroy(
   void* pvData,
   size_t cbData
) const;

Parameters

pvData

A pointer to an array of bytes, of size cbData, which was allocated using Alloc().
cbData

Number of bytes in buffer.

Return Value

This static function deallocates memory used for a byte stream. This deallocator should be used for any memory that has been detached from an object using the Detach() method.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::Detach

Detaches the current data from the object

void Detach(
   void*& pvData,
   size_t& cbData
) const;

Parameters

pvData

Reference to a pointer to an array of bytes, of size cbData.
cbData

Reference to size of byte array.

Remarks

This function detaches the current contents. Unless the buffer is later attached to another object, it should be deallocated using the CXlMarshaledData::Destroy() static method.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::GetCount

Returns the size of the byte stream buffer

size_t GetCount( ) const;

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::GetData

Returns a pointer to the byte stream buffer

void* GetData( ) const;

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::IsGood

Returns the state of the byte stream buffer

bool IsGood( ) const;

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::MoveFrom

Detaches the data from another object and attaches it to this object

void MoveFrom(
   CXlMarshaledData& that
) const;

Parameters

that

Reference to an object whose memory will be transfered to *this.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::operator !=

Compares the object with another

bool operator !=(
   const CXlMarshaledData& that
) const;

Parameters

that

A CXlMarshaledData object that will be compared to *this.

Return Value

The operator returns false if the current object is identical to that, and true otherwise.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::operator <

Compares the object with another

bool operator <(
   const CXlMarshaledData& that
) const;

Parameters

that

A CXlMarshaledData object that will be compared to *this.

Return Value

The operator returns true if the current object is sorted before that, and false otherwise.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::operator <=

Compares the object with another

bool operator <=(
   const CXlMarshaledData& that
) const;

Parameters

that

A CXlMarshaledData object that will be compared to *this.

Return Value

The operator returns true if the current object is sorted equal to or before that, and false otherwise.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::operator =

Assigns a new value to the byte stream

const CXlMarshaledData& operator =(
   const CXlMarshaledData& srcKey
);

Parameters

srcKey

A CXlMarshaledData object that will be deep-copied to *this.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::operator =

Compares the object with another

bool operator =(
   const CXlMarshaledData& that
) const;

Parameters

that

A CXlMarshaledData object that will be compared to *this.

Return Value

The operator returns true if the current object is identical to that, and false otherwise.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::operator >

Compares the object with another

bool operator >(
   const CXlMarshaledData& that
) const;

Parameters

that

A CXlMarshaledData object that will be compared to *this.

Return Value

The operator returns true if the current object is sorted after that, and false otherwise.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::operator >=

Compares the object with another

bool operator >=(
   const CXlMarshaledData& that
) const;

Parameters

that

A CXlMarshaledData object that will be compared to *this.

Return Value

The operator returns true if the current object is sorted equal to or after that, and false otherwise.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::ReadArgs

Returns the state of the byte stream buffer

bool ReadArgs(
   const char* pszFnName,
   void* pvFirstArg,
   bool bPrefixFn
);

Parameters

pszFnName

Name of add-in function whose arguments are being converted to a byte stream.
pvFirstArg

Address of the first argument to the add-in function. This pointer is used to traverse the argument stack, using the add-in function's registered definition to interpret the items in the stack.
bPrefixFn

If true, the name of the function will be prefixed to the byte stream. This is useful if a single cache is used for more than one add-in function. If false, then the function is not prefixed. This is appropriate if each add-in function uses its own cache.

Remarks

This method iterates through the arguments of an add-in function, and writes their values to a single continuous byte stream, optionally prefixed by the name of the add-in function.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


CXlMarshaledData::Set

Copies the supplied data into the object, replacing any current contents

void Set(
   void* pvData,
   size_t cbData
) const;

Parameters

pvData

A pointer to an array of bytes, of size cbData.
cbData

Size of array of bytes.

Remarks

This function removes the current contents and replace them with a copy of the supplied data buffer.

Requirements

Header: xlmarshal.h

See Also

CXlMarshaledData Class | CXlMarshaledData Methods


xlmenu.h

Overview

xlmenu.h contains a class that allows you to add menus to the Excel main application menu bar.

For details on how to use the class see CXlMenu Object overview

Classes

Class | Description
CXlMenu | A run-time menu added to Excel's main application menu bar.

See Also

CXlMenu object | xldialog.h


CXlMenu Class

Used to create run-time menus which are attached to the Excel application menu bar.

class CXlMenu

Overview

The CXlMenu class can be used to create run-time menus which are attached to the Excel application menu bar.

An instance of CXlMenu should be created for each top-level menu to be added. Each menu can contain any number of menu items.

The menu object should be a member of the add-in's application class (derived from CXllApp). The menu should be attached to the application bar during the CXllApp::OnXllOpenEx() event, using the Create() method. The menu should be removed during the CXllApp::OnXllClose() event, using the Destroy() method.

Items can be added to the menu (before Create() is called) using the AddItem() method. After Create() has been called, you can call the following functions to manipulate the menu or sub-menu: AddItem, DeleteItem, ReplaceItem, EnableItem, and CheckItem.

Internationalization

Many of the text arguments to CXlMenu methods may be resource ID strings. These are loaded from the application resource file at run-time. For example, you can add a menu item whose caption is held in resource 234 in the resource file, as follows:

m_menu.AddItem("#234", "Intl3_SelectLanguage");
The string will be loaded in the current user's preferred language, if available. See International support for more information.

The functions that accept and translate resource ID strings are listed below.

CXlMenu::Create | CXlMenu::AddItem | CXlMenu::SetTexts
CXlMenu::DeleteItem | CXlMenu::ReplaceItem | CXlMenu::EnableItem
CXlMenu::CheckItem |  |

Sample applications

You can find full examples of using the CXlMenu class below:

  • Simple menus sample
  • Advanced menus sample

Requirements

Header: xlmenu.h

See Also

CXlMenu Methods | xlmenu.h | Menus (User Guide) | Simple menus sample | Advanced menus sample | CXllApp object


CXlMenu Methods

The methods of the CXlMenu class are listed here.

Construction

public method CXlMenu Constructs a CXlMenu object without displaying it

Pre-create functions

public method | AddItem | Adds a menu item
public method | SetTexts | Sets the menu text and (optionally) description

Creation functions

public method | Create | Adds the menu or sub-menu to the Excel main application menu bar
public method | Destroy | Removes the menu from Excels' application menu bar.

Item methods

public method | CheckItem | Set the chcked state of an item in a menu
public method | DeleteItem | Deletes an item from a menu
public method | EnableItem | Enables or disables an item in a menu
public method | ReplaceItem | Replaces an item in a menu

Service functions

GetCallingMenu | Determine which menu item called the current add-in function
GetCallingMenuItemPosition | Determine which the position of the menu item which called the current add-in function

Requirements

Header: xlmenu.h

See Also

CXlMenu Class | xlmenu.h | Menus (User Guide) | Simple menus sample | Advanced menus sample | CXllApp object


CXlMenu::AddItem

Adds a menu item

void AddItem(
   const TCHAR* pszText,
   const TCHAR* pszMacro,
   const TCHAR* pszDescription = 0
);

Parameters

pszText

The text of the new menu item, which may include an ampersand for a short-cut key.

To create a separator item, with no text, pass "-" as pszText.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
pszMacro

The name of the macro function which will be called by the menu. This should be marked in the XLL+ Function Wizard as a macro function.
pszDescription

Optional description which will appear on the status bar in some versions of Excel.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.

Remarks

Adds an item to the menu.

Unlike any of the other item methods, this function may be called either before or after Create() has been called.

Requirements

Header: xlmenu.h

See Also

CXlMenu Class | CXlMenu Methods


CXlMenu::CheckItem

Set the chcked state of an item in a menu

void CheckItem(
   const TCHAR* pszText,
   BOOL bChecked
);
void CheckItem(
   int nPosition,
   BOOL bChecked
);

Parameters

pszText

The current text of the menu item, which may include an ampersand for a short-cut key.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
bChecked

The new checked state of the menu item. TRUE to show a tick next to the item, FALSE to hide it.
nPosition

The index of the item in the menu. Note that the index of the first item is 1.

Remarks

Sets the checked state of an item in the menu, either by name or position.

This function may only be called after Create() has been called. It will have no effect if it is called before Create().

Requirements

Header: xlmenu.h

See Also

CXlMenu Class | CXlMenu Methods


CXlMenu::Create

Adds the menu or sub-menu to the Excel main application menu bar

BOOL Create(
   const TCHAR* pszNextMenu = "Help"
);
BOOL Create(
   const CXlMenu& menuParent,
   const TCHAR* pszNextItem
);
BOOL Create(
   const CXlMenu& menuParent,
   int nNextItem
);

Parameters

pszNextMenu

The name of the existing menu before which this menu will appear.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
menuParent

The parent menu to which this menu will be attached. The parent must already have called Create().

pszNextItem

The name of the existing item before which this sub-menu will appear.
nNextItem

The index of the existing item before which this sub-menu will appear. Note that the index of the first item is 1.

Return Value

Returns TRUE if the call is successful, FALSE if it fails.

Remarks

Create the new menu. This function should be called during the OnXllOpen() or OnXllOpenEx() event handlers.

Note that the first form creates a new menu in Excel's main application menu bar. The second and third forms create a sub-menu as an item in a menu of the first form.

Requirements

Header: xlmenu.h

See Also

CXlMenu Class | CXlMenu Methods


CXlMenu::CXlMenu

Constructs a CXlMenu object without displaying it

CXlMenu( );

Remarks

This method constructs a menu object. It will not be displayed until the Create() method has been called.

Requirements

Header: xlmenu.h

See Also

CXlMenu Class | CXlMenu Methods


CXlMenu::DeleteItem

Deletes an item from a menu

void DeleteItem(
   const TCHAR* pszText
);
void DeleteItem(
   int nPosition
);

Parameters

pszText

The text of the menu item, which may include an ampersand for a short-cut key.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
nPosition

The index of the item in the menu. Note that the index of the first item is 1.

Remarks

Deletes an item from the menu, either by name or position.

This function may only be called after Create() has been called. It will have no effect if it is called before Create().

Requirements

Header: xlmenu.h

See Also

CXlMenu Class | CXlMenu Methods


CXlMenu::Destroy

Removes the menu from Excels' application menu bar.

BOOL Destroy( );

Return Value

Returns TRUE if the call is successful, FALSE if it fails.

Remarks

Removes the menu from Excel's application menu bar. This function should be called during the OnXllClose() event handler.

Requirements

Header: xlmenu.h

See Also

CXlMenu Class | CXlMenu Methods


CXlMenu::EnableItem

Enables or disables an item in a menu

void EnableItem(
   const TCHAR* pszText,
   BOOL bEnabled
);
void EnableItem(
   int nPosition,
   BOOL bEnabled
);

Parameters

pszText

The current text of the menu item, which may include an ampersand for a short-cut key.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
bEnabled

The new enabled state of the menu item. TRUE to enable the item, FALSE to disable it.
nPosition

The index of the item in the menu. Note that the index of the first item is 1.

Remarks

Enables or disables an item in the menu, either by name or position.

This function may only be called after Create() has been called. It will have no effect if it is called before Create().

Requirements

Header: xlmenu.h

See Also

CXlMenu Class | CXlMenu Methods


CXlMenu::GetCallingMenu

Determine which menu item called the current add-in function

static BOOL GetCallingMenu(
   int& nBar,
   int& nMenu,
   int& nItem,
   int& nSubItem
);

Parameters

nBar

The index of the menu bar to which the menu item belongs. Note that the index of the Excel main application menu bar is 10.
nMenu

The index of the menu within the bar. Note that the index of the first menu is 1.
nItem

The index of the item in the menu. Note that the index of the first item is 1. If the function was called from an item on a sub-menu, then nItem will contain the index of the sub-menu in the main menu.
nSubItem

The index of the item in a sub-menu. If the item was not part of a sub-menu then this will contain 0, and should be ignored. Note that the index of the first item is 1.

Return Value

Returns TRUE if the current add-in function was called from a menu, FALSE if not.

Remarks

If the current add-in function was called from a menu item, this static function returns TRUE and sets the values of the nBar, nMenu, nItem and nSubItem arguments.

Excel 2007/Excel 12

There is a bug in Excel 2007, which means that this method returns inconsistent and incorrect results. Add-ins that must run under Excel 2007 (and optionally other versions of Excel) should instead use CXlMenu::GetCallingMenuItemPosition(). This simpler method works around the Excel 2007 bug and returns correct results under all versions of Excel. Note however that GetCallingMenuItemPosition() has less capability than this method and cannot differentiate between different menus and submenus.

Requirements

Header: xlmenu.h

See Also

CXlMenu Class | CXlMenu Methods | CXlMenu::GetCallingMenuItemPosition()


CXlMenu::GetCallingMenuItemPosition

Determine which the position of the menu item which called the current add-in function

static BOOL GetCallingMenuItemPosition(
   int& nItem
);

Parameters

nItem

The index of the item in the menu or sub-menu. Note that the index of the first item is 1.

Return Value

Returns TRUE if the current add-in function was called from a menu, FALSE if not.

Remarks

If the current add-in function was called from a menu item, this static function returns TRUE and sets the values of the nItem argument.

Excel 2007/Excel 12

This method is provided for use by add-ins that must run under Excel 2007 (and optionally other versions of Excel). There is a bug in Excel 2007, which means that the standard method CXlMenu::GetCallingMenu() returns inconsistent and incorrect results. This simpler method works around the Excel 2007 bug and returns correct results under all versions of Excel. Note that this method cannot differentiate between different menus or submenus - it can only return the position of the called item within its menu or submenu. It is therefore essential that the developer provide different call-back functions for different menus and sub-menus; within each menu-specific call-back function this method can be used to check which item within the menu or sub-menu was clicked.

Requirements

Header: xlmenu.h

See Also

CXlMenu Class | CXlMenu Methods | CXlMenu::GetCallingMenu()


CXlMenu::ReplaceItem

Replaces an item in a menu

void ReplaceItem(
   const TCHAR* pszOldText,
   const TCHAR* pszNewText
);
void ReplaceItem(
   int nPosition,
   const TCHAR* pszNewText
);

Parameters

pszOldText

The current text of the menu item, which may include an ampersand for a short-cut key.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
pszNewText

The new text of the menu item, which may include an ampersand for a short-cut key.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
nPosition

The index of the item in the menu. Note that the index of the first item is 1.

Remarks

Replaces the text of an item in the menu, either by name or position.

This function may only be called after Create() has been called. It will have no effect if it is called before Create().

Requirements

Header: xlmenu.h

See Also

CXlMenu Class | CXlMenu Methods


CXlMenu::SetTexts

Sets the menu text and (optionally) description

void SetTexts(
   const TCHAR* pszText,
   const TCHAR* pszDescription = 0
);

Parameters

pszText

The text of the menu, which may include an ampersand for a short-cut key.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
pszDescription

Optional description which will appear on the status bar in some versions of Excel.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.

Remarks

Set the menu text and (optionally) description.

Requirements

Header: xlmenu.h

See Also

CXlMenu Class | CXlMenu Methods


xlpasync.h

Overview

xlpasync.h contains classes and functions that support the Excel 2010 queued asynchronous function mechanism.

For more information, see Queued functions in the User Guide.

Classes

The table below lists the public C++ object classes declared in the header file.

Class | Description
CXlAsyncManager | Provides access to the asynchronous function API, allowing the developer to control the background threads.


CXlAsyncManager Class

Provides access to the asynchronous function API, allowing the developer to control the background threads.

class CXlAsyncManager

Overview

Beginning in Excel 2010, functions can be marked as "Asynchronous". The CXlAsyncManager class manages the execution of queued asynchronous worksheet functions. These functions use a background (worker) thread to run their implementations and inform the Excel calculation tree that they are complete by calling the xlAsyncReturn SDK call-back. See Queued functions in the User Guide for more information.

Usage

The object should not be created directly. A single instance of the class is created on demand by the method CXllApp::GetXlAsyncManager().

Once you have retrieved a pointer to the CXlAsyncManager instance, you can set the maximum number of threads used by the asynchronous function mechanism with the SetMaxThreads() method. During operation, you can use Stop() and Start() to control the worker threads.

Requirements

Header: xlpasync.h

See Also

CXlAsyncManager Methods | xlpasync.h


CXlAsyncManager Methods

The methods of the CXlAsyncManager class are listed here.

Operations

public method | Start | Allocates the background threads and starts any queued tasks.
public method | Stop | Kills any running threads and queues tasks until Start is called.

Properties

public method | GetMaxThreads | Gets the maximum number of background threads that will be used to run asynchronous functions.
public method | SetMaxThreads | Sets the maximum number of background threads that will be used to run asynchronous functions.

Construction

public method CXlAsyncManager Constructs a CXlAsyncManager object

Requirements

Header: xlpasync.h

See Also

CXlAsyncManager Class | xlpasync.h


CXlAsyncManager::CXlAsyncManager

Constructs a CXlAsyncManager object

CXlAsyncManager( );

Requirements

Header: xlpasync.h

See Also

CXlAsyncManager Class | CXlAsyncManager Methods


CXlAsyncManager::GetMaxThreads

Gets the maximum number of background threads that will be used to run asynchronous functions.

size_t GetMaxThreads( );

Return Value

Returns the maximum number of threads.

Requirements

Header: xlpasync.h

See Also

CXlAsyncManager Class | CXlAsyncManager Methods


CXlAsyncManager::SetMaxThreads

Sets the maximum number of background threads that will be used to run asynchronous functions.

void SetMaxThreads(
   size_t maxThreads
);

Parameters

maxThreads

The maximum number of threads that will be used by for asynchronous functions.

If the value is 0 then an exception of type CXlOutOfRangeException will be thrown.

Remarks

If Start has already been called, then SetMaxThreads will fail and an exception of type CXlRuntimeException will be thrown.

Requirements

Header: xlpasync.h

See Also

CXlAsyncManager Class | CXlAsyncManager Methods


CXlAsyncManager::Start

Allocates the background threads and starts any queued tasks.

void Start( );

Requirements

Header: xlpasync.h

See Also

CXlAsyncManager Class | CXlAsyncManager Methods


CXlAsyncManager::Stop

Kills any running threads and queues tasks until Start is called.

void Stop( );

Requirements

Header: xlpasync.h

See Also

CXlAsyncManager Class | CXlAsyncManager Methods


xlpclrconvert.h

Overview

xlpclrconvert.h contains some global functions that help with conversion between Excel value types and Common Language Runtime value types. All these functions are in the namespace ple::clr.

The file is automatically included in the project when the AppWizard creates an XLL+ project with CLR checked. In addition, the statement using namespace ple::clr; is added, to make use of the conversion functions simpler.

Functions

The table below lists the principal functions declared in the header file.

Function | Description
toClr | Transform an Excel value or array to an equivalent CLR value or array.
toClr<T> | Transform an Excel array to a CLR array of the same type.
toXl | Transform a CLR value or array to an equivalent Excel value or array.
toXl<T> | Transform a CLR array to an Excel array of the same type.
objectToXl | Transform a CLR object or array of unknown type to an Excel array of the appropriate type.

A full list can be found here.


Common Language Runtime support functions

Common Language Runtime support functions are listed here.

Excel to CLR

public method | toClr | Transform a value received from Excel to a CLR form
public method | toClr<T> | Transform an array received from Excel to a CLR array
public method | toClrDate | Transform an Excel date value to a CLR DateTime value
public method | toClrDates | Transform an array of Excel date values to a CLR DateTime array
public method | toClrInts | Transform an array of long to a CLR int array
public method | toClrObject | Transform an Excel value of unknown type to a CLR object
public method | toClrObjectMatrix | Transform an Excel matrix containing values of unknown type to a two-dimensional CLR object array
public method | toClrObjectVector | Transform an Excel vector containing values of unknown type to a one-dimensional CLR object array

CLR to Excel

public method | objectToXl | Transform a value of indeterminate type, received from .NET, to an Excel return value
public method | toXl | Transform a value received from .NET to an Excel return value
public method | toXl<T> | Transform a value received from .NET to an Excel return value

Requirements

Header: xlpclrconvert.h
Namespace: ple::clr

See Also

xlpclrconvert.h


ple::clr::objectToXl

Transform a value of indeterminate type, received from .NET, to an Excel return value

CXlOper objectToXl(
   System::Object^ src
);

Parameters

src

A CLR type.

Return Value

A CXlOper value, populated with the transformed values.

Remarks

This function transforms CLR values or arrays of indeterminate type to an Excel value type. The following types are directly supported, as scalars, and as 1- or 2-dimensional arrays:

  • System.Boolean (C# bool)
  • System.DateTime
  • System.Double (C# double)
  • System.Single
  • System.Int16
  • System.Int32 (C# int)
  • System.Int64
  • System.UInt16
  • System.UInt32
  • System.UInt64
  • System.Decimal
  • System.String (C# string)

All other types are converted to strings, using the ToString() method.

Requirements

Header: xlpclrconvert.h

See Also

Common Language Runtime support functions | toXl


ple::clr::toClr

Transform a value received from Excel to a CLR form

System::String^ toClr(
   const CXlStringArg& arg
);
System::String^ toClr(
   const std::string& str
);
System::String^ toClr(
   const std::wstring& wstr
);
System::String^ toClr(
   const CString& cstr
);
System::String^ toClr(
   const CStringA& cstra
);
System::String^ toClr(
   const CStringW& cstrw
);
System::String^ toClr(
   const char* psz
);
System::String^ toClr(
   const wchar_t* wpsz
);
array<System::String^>^ toClr(
   const std::vector<CString>& vector
);
array<System::String^, 2>^ toClr(
   const ple::mtx_ptrs<CString>& matrix
);

Parameters

arg

A string argument received from Excel.
str

An STL string.
wstr

An STL wide string.
cstr

A string object, whose character type depends on the value of the pre-processor definition _UNICODE.
cstra

A string object.
cstrw

A unicode string object.
psz

A non-zero, null-terminated character array.
wpsz

A non-zero, null-terminated wide character array.
vector

A vector of string objects, whose character type depends on the value of the pre-processor definition _UNICODE.

matrix

A matrix of string objects, whose character type depends on the value of the pre-processor definition _UNICODE.

Return Value

A CLR object, that may be passed directly to a .NET method, using C++/CLI.

Remarks

The various forms of this function transform C++ string types or arrays to equivalent .NET string or array.

The template function toClr<T> handles the majority of array conversions, where the C++ element type is the same as the CLR element type.

Requirements

Header: xlpclrconvert.h

See Also

Common Language Runtime support functions | toClr<T>


ple::clr::toClr<T>

Transform an array received from Excel to a CLR array

template< class T >
array<T>^ toClr<T>(
   const std::vector<T>& vector
);
template< class T >
array<T, 2>^ toClr<T>(
   const ple::mtx_ptrs<T>& matrix
);

Parameters

vector

A vector of values, whose elements must be one of the following types:

  • double
  • int
  • bool
matrix

A matrix of values, whose elements must be one of the following types:

  • double
  • int
  • bool

Return Value

A CLR array, that may be passed directly to a .NET method, using C++/CLI.

Remarks

The various forms of this template function transform C++ arrays to equivalent .NET arrays.

A large number of specializations exist, for transforming between arrays of similar but different types. See toClr (function) for a complete list.

Requirements

Header: xlpclrconvert.h

See Also

Common Language Runtime support functions | toClr


ple::clr::toClrDate

Transform an Excel date value to a CLR DateTime value

System::DateTime^ toClrDate(
   double datetime
);
System::DateTime^ toClrDate(
   long date
);

Parameters

datetime

A numeric date/time value received from Excel.
date

An integer date value received from Excel.

Return Value

A CLR object, that may be passed directly to a .NET method, using C++/CLI.

Requirements

Header: xlpclrconvert.h

See Also

Common Language Runtime support functions | toClr | toClrDates


ple::clr::toClrDates

Transform an array of Excel date values to a CLR DateTime array

array<System::DateTime>^ toClrDates(
   std::vector<double>& tvec
);
array<System::DateTime>^ toClrDates(
   std::vector<long>& dvec
);
array<System::DateTime, 2>^ toClrDates(
   ple::mtx_ptrs<double>& tmat
);
array<System::DateTime, 2>^ toClrDates(
   ple::mtx_ptrs<double>& dmat
);

Parameters

tvec

A vector of numeric date/time values received from Excel.
dvec

A vector of integer date values received from Excel.
tmat

A matrix of numeric date/time values received from Excel.
dmat

A matrix of integer date values received from Excel.

Return Value

A CLR object, that may be passed directly to a .NET method, using C++/CLI.

Requirements

Header: xlpclrconvert.h

See Also

Common Language Runtime support functions | toClr | toClrDate


ple::clr::toClrInts

Transform an array of long to a CLR int array

array<int>^ toClrInts(
   std::vector<long>& vec
);
array<int, 2>^ toClrInts(
   ple::mtx_ptrs<long>& mat
);

Parameters

vec

A vector of integer values received from Excel.
mat

A matrix of integer values received from Excel.

Return Value

A CLR object, that may be passed directly to a .NET method, using C++/CLI.

Requirements

Header: xlpclrconvert.h

See Also

Common Language Runtime support functions | toClr<T> | toClrDates


ple::clr::toClrObject

Transform an Excel value of unknown type to a CLR object

System::Object^ toClrObject(
   const CXlOperBase& xloValue,
   const wchar_t* argName
);

Parameters

xloValue

A single value received from Excel. This can be a single cell value, or a cell contained in an array value.

Note: if this value is specified as a parameter of the add-in function, it must be of type "Value", and not type "Reference". If the parameter has been passed as type "Reference", then the value must be extracted, using CXlOper::Coerce().

argName

The name of the argument that is being converted. This will be used in error messages.

Return Value

A CLR object, that may be passed directly to a .NET method, using C++/CLI. If the input cell is empty, then null will be returned.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpclrconvert.h

See Also

Common Language Runtime support functions | toClr | toClrObjectVector | toClrObjectMatrix


ple::clr::toClrObjectMatrix

Transform an Excel matrix containing values of unknown type to a two-dimensional CLR object array

array<System::Object^, 2> toClrObjectMatrix(
   const CXlOper& xloValue,
   const wchar_t* argName
);

Parameters

xloValue

An array value received from Excel. This can be a single cell, a vector of cells or a matrix of cells.

Note: if this value is specified as a parameter of the add-in function, it must be of type "Value", and not type "Reference". If the parameter has been passed as type "Reference", then the value must be extracted, using CXlOper::Coerce().

argName

The name of the argument that is being converted. This will be used in error messages.

Return Value

A two-dimensional CLR object array, that may be passed directly to a .NET method, using C++/CLI.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpclrconvert.h

See Also

Common Language Runtime support functions | toClr | toClrObject | toClrObjectVector


ple::clr::toClrObjectVector

Transform an Excel vector containing values of unknown type to a one-dimensional CLR object array

array<System::Object^, 1> toClrObjectVector(
   const CXlOper& xloValue,
   const wchar_t* argName
);

Parameters

xloValue

An array value received from Excel. This can be a single cell, or a vector of cells.

Note: if this value is specified as a parameter of the add-in function, it must be of type "Value", and not type "Reference". If the parameter has been passed as type "Reference", then the value must be extracted, using CXlOper::Coerce().

argName

The name of the argument that is being converted. This will be used in error messages.

Return Value

A one-dimensional CLR object array, that may be passed directly to a .NET method, using C++/CLI.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpclrconvert.h

See Also

Common Language Runtime support functions | toClr | toClrObject | toClrObjectMatrix


ple::clr::toXl

Transform a value received from .NET to an Excel return value

std::tstring toXl(
   System::String^ str
);
double toXl(
   System::DateTime datevalue
);
double toXl(
   System::DateTime^ dateref
);
double toXl(
   int ival
);
double toXl(
   long lval
);
BOOL toXl(
   bool boolval
);
std::vector<std::tstring> toXl(
   array<System::String^>^ svec
);
std::vector<double> toXl(
   array<System::DateTime>^ dvec
);
std::vector<double> toXl(
   array<int>^ ivec
);
std::vector<double> toXl(
   array<long>^ lvec
);
std::vector<BOOL> toXl(
   array<bool>^ bvec
);
ple::mtx_ptrs<std::tstring> toXl(
   array<System::String^, 2>^ smat
);
ple::mtx_ptrs<double> toXl(
   array<System::DateTime, 2>^ dmat
);
ple::mtx_ptrs<double> toXl(
   array<int, 2>^ imat
);
ple::mtx_ptrs<double> toXl(
   array<long, 2>^ lmat
);
ple::mtx_ptrs<BOOL> toXl(
   array<bool, 2>^ bmat
);

Parameters

str

A CLR string type.
datevalue

A CLR date/time value.
dateref

A CLR date/time reference.
ival

An integer value, which will be converted to a double prior to being returned to Excel.
lval

An integer value, which will be converted to a double prior to being returned to Excel.

boolval

An integer value, which will be converted to a double prior to being returned to Excel.

svec

A CLR single-dimensional array of strings.
dvec

A CLR single-dimensional array of date/time values.
ivec

A CLR single-dimensional array of integer values.
lvec

A CLR single-dimensional array of long integer values.
bvec

A CLR single-dimensional array of boolean values.
smat

A CLR two-dimensional array of strings.
dmat

A CLR two-dimensional array of date/time values.
imat

A CLR two-dimensional array of integer values.
lmat

A CLR two-dimensional array of long integer values.
bmat

A CLR two-dimensional array of boolean values.

Return Value

A standard C++ value or array, that may be passed directly to the CXlOper assignment operator.

Remarks

The various forms of this function transform CLR values or arrays to equivalent C++ types. The transforms are designed to ensure that the correct overload of CXlOper::= will be invoked, when the method is used to return values to Excel, e.g.:

xloResult = toXl(clrValue);

The template function toXl<T> handles the majority of array conversions, where the C++ element type is the same as the CLR element type.

Requirements

Header: xlpclrconvert.h

See Also

Common Language Runtime support functions | objectToXl | toXl<T>


ple::clr::toXl<T>

Transform a value received from .NET to an Excel return value

template< class T >
std::vector<T> toXl<T>(
   array<T>^ vector
);
template< class T >
ple::mtx_ptrs<T> toXl<T>(
   array<T, 2>^ matrix
);

Parameters

vector

A CLR single-dimensional array type, whose elements are one of the following:

  • double
  • int
  • bool
matrix

A CLR two-dimensional array type, whose elements are one of the following:

  • double
  • int
  • bool

Return Value

A C++ array, that may be passed directly to the CXlOper assignment operator.

Remarks

The various forms of this template function transform CLR arrays to equivalent C++ types. The transforms are designed to ensure that the correct overload of CXlOper::= will be invoked, when the method is used to return values to Excel, e.g.:

xloResult = toXl(clrValue);

A large number of specializations exist, for transforming between similar but different types. See toXl for a complete list.

Requirements

Header: xlpclrconvert.h

See Also

Common Language Runtime support functions | toXl


xlpclrforms.h

Overview

xlpclrforms.h contains a class XllPlus::Forms::ExcelForm that connects the .NET Windows Forms library to the Excel application library.

Note that the file is not automatically included in the project when the AppWizard creates an XLL+ project with CLR checked.

Requirements

Your project must use the CLR build, in order to be able to include this header. See XLL+ Application Wizard - Application Settings for instructions on using CLR builds.

You will also need to add a reference to System.Windows.Forms.dll to your project in order to use this header file.

Classes

The table below lists the classes declared in the header file.

Class | Description
ExcelForm | A wrapper class to allow the Excel window to be used as a parent for .NET Forms.
WinWrapper | A wrapper class to allow HWND handles to be used as a parent for .NET Forms.


ExcelForm Class

Used to link .NET forms to Excel.

class ExcelForm

Overview

The ExcelForm class establishes a link between the Excel application window and the .NET runtime Forms classes. In order to show a modal dialog during an add-in function (or during an add-in library event handler), you should construct a ExcelForm to use as the parent of your own window.

ExcelForm implements the IWin32Window interface, and can be used wherever .NET expects a window handle, as in the example C++/CLI code below.

System::Windows::Forms::MessageBox::Show(
    gcnew XllPlus::Forms::ExcelForm(),
    "Hello from .NET");

Requirements

Header: xlpclrforms.h

See Also

ExcelForm Methods | xlpclrforms.h | WinWrapper class


ExcelForm Methods

The methods of the ExcelForm class are listed here.

Construction

public method XllPlus::Forms::ExcelForm Constructs a ExcelForm object and attaches it to Excel's application window

Requirements

Header: xlpclrforms.h

See Also

ExcelForm Class | xlpclrforms.h | WinWrapper class


ExcelForm::XllPlus::Forms::ExcelForm

Constructs a ExcelForm object and attaches it to Excel's application window

XllPlus::Forms::ExcelForm( );

Remarks

This constructor is all that is required to initialise the object.

Because ExcelForm is a managed class, you should use gcnew to construct it, rather than new, as shown below.

System::Windows::Forms::MessageBox::Show(
    gcnew XllPlus::Forms::ExcelForm(),
    "Hello from .NET");

Requirements

Header: xlpclrforms.h

See Also

ExcelForm Class | ExcelForm Methods


WinWrapper Class

Used to link .NET forms to Excel.

class WinWrapper

WinWrapper

The WinWrapper class establishes a link between a Windows API window handle (HWND) and the .NET runtime Forms classes. In order to show a modal dialog during an add-in function (or during an add-in library event handler), you can construct a WinWrapper to use as the parent of your own window.

WinWrapper implements the IWin32Window interface, and can be used wherever .NET expects a window handle, as in the example C++/CLI code below.

HWND hwndOwner;
System::Windows::Forms::MessageBox::Show(
    gcnew XllPlus::Forms::WinWrapper(hwndOwner),
    "Hello from .NET");

Requirements

Header: xlpclrforms.h

See Also

WinWrapper Methods | xlpclrforms.h | ExcelForm class


WinWrapper Methods

The methods of the WinWrapper class are listed here.

Construction

public method XllPlus::Forms::WinWrapper Constructs a WinWrapper object and attaches it to the specified window handle

Requirements

Header: xlpclrforms.h

See Also

WinWrapper Class | xlpclrforms.h | ExcelForm class


WinWrapper::XllPlus::Forms::WinWrapper

Constructs a WinWrapper object and attaches it to the specified window handle

XllPlus::Forms::WinWrapper(
   HWND hwnd
);

Parameters

hwnd

A valid window handle.

Remarks

This constructor is all that is required to initialise the object.

Because WinWrapper is a managed class, you should use gcnew to construct it, rather than new, as shown below.

System::Windows::Forms::MessageBox::Show(
    gcnew XllPlus::Forms::WinWrapper(hwnd),
    "Hello from .NET");

Requirements

Header: xlpclrforms.h

See Also

WinWrapper Class | WinWrapper Methods


xlpcom.h

Overview

xlpcom.h contains classes and definitions for accessing Excel's OLE automation interface.

Public access is via an instance of the CXllCom object. An initialised object of this type is available by calling the CXllApp::GetCom() method.

See Also

CXllCom object


CXllCom Class

Encapsulates an addin's interaction with Excel's COM interface.

class CXllCom

Overview

The CXllCom class encapsulates an addin's interaction with Excel's COM interface. Different versions of Excel have noticeably different object models; by using the CXllCom class, you are immunised from these differences.

Usage

CXllCom methods cannot be used during addin worksheet functions. Any attempt to use them will fail and may have unexpected side-effects. CXllCom methods should only be used during macro functions and as a result of processing window messages in the foreground thread.

Requirements

Header: xlpcom.h

See Also

CXllCom Methods | xlpcom.h | CXllApp::SetSinkEvents()


CXllCom Methods

The methods of the CXllCom class are listed here.

Shortcuts

public method | OleGetRange | Get a Range
public method | OleGetWorkbook | Get a member of the Application.Workbooks collection by name
public method | OleGetWorkbooks | Get the Application.Workbooks collection
public method | OleGetWorksheet | Get a Worksheet by name
public method | OleGetWorksheets | Get the Worksheets collection for a named workbook

Properties

public method | OleGetOnCalculate | Get the value of Application.OnCalculate
public method | OleGetOnSheetActivate | Get the value of Application.OnSheetActivate
public method | OleGetOnSheetDeactivate | Get the value of Application.OnSheetDeactivate
 | OleGetRangeAddress | Get the value of Range.Address
 | OleGetRangeFormula | Get the value of Range.Formula
 | OleGetRangeValue | Get the value of Range.Value
 | OleGetRangeWorksheet | Get the value of Range.Worksheet
public method | OleGetWarnings | Get the value of Application.DisplayAlerts
 | OleGetWorkbookName | Get the name of a workbook
 | OleGetWorksheetName | Get the name of a worksheet
 | OleGetWorksheetWorkbook | Get the value of Worksheet.Parent
public method | OleSetOnCalculate | Set the value of Application.OnCalculate
public method | OleSetOnSheetActivate | Set the value of Application.OnSheetActivate
public method | OleSetOnSheetDeactivate | Set the value of Application.OnSheetDeactivate
public method | OleSetWarnings | Set the value of Application.DisplayAlerts

Search

OleRangeIsCurrent | Get the value of Range.Address = Range.CurrentArray.Address
OleRangeIsFirst | Returns whether range is the first (or only) cell of an array
OleWorksheetFindFormula | Search for an instance of a formula in a worksheet

Operations

public method | OleExecuteExcel4Macro | Call Application.ExecuteExcel4Macro
 | OleTouchRange | Force a range to recalculate

Construction

public method CXllCom Constructs a CXllCom object

Requirements

Header: xlpcom.h

See Also

CXllCom Class | xlpcom.h | CXllApp::SetSinkEvents()


CXllCom::CXllCom

Constructs a CXllCom object

CXllCom( );

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods


CXllCom::OleExecuteExcel4Macro

Call Application.ExecuteExcel4Macro

HRESULT OleExecuteExcel4Macro(
   const CString& strMacroCommand,
   LPVARIANT pvntResult
);

Parameters

strMacroCommand

The command to be run. Any arguments should be in parentheses, e.g. "do_macro(1.0,TRUE)"
pvntResult

If a result is returned by the macro, it will be placed here. Ignored if NULL.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods


CXllCom::OleGetOnCalculate

Get the value of Application.OnCalculate

HRESULT OleGetOnCalculate(
   CString& strMacro
);

Parameters

strMacro

If the function is successful, the value of Application.OnCalculate will be placed here.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleSetOnCalculate()


CXllCom::OleGetOnSheetActivate

Get the value of Application.OnSheetActivate

HRESULT OleGetOnSheetActivate(
   CString& strMacro
);

Parameters

strMacro

If the function is successful, the value of Application.OnSheetActivate will be placed here.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleSetOnSheetActivate()


CXllCom::OleGetOnSheetDeactivate

Get the value of Application.OnSheetDeactivate

HRESULT OleGetOnSheetDeactivate(
   CString& strMacro
);

Parameters

strMacro

If the function is successful, the value of Application.OnSheetDeactivate will be placed here.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleSetOnSheetDeactivate()


CXllCom::OleGetRange

Get a Range

HRESULT OleGetRange(
   LPCSTR pszWorkbook,
   LPCSTR pszWorksheet,
   const CXlRef& xlref,
   LPDISPATCH* lpdisp
);

Parameters

pszWorkbook

Name of the workbook.
pszWorksheet

Name of the worksheet.
xlref

Rectangular range reference
lpdisp

If the function is successful, a pointer to the Range object will be placed here. It is the responsibility of the caller to Release() it.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleGetWorkbook() | CXllCom::OleGetWorksheet()


CXllCom::OleGetRangeAddress

Get the value of Range.Address

static HRESULT OleGetRangeAddress(
   LPDISPATCH dispRange,
   CString& strAddress,
   BOOL bExternal = FALSE
);

Parameters

dispRange

The range to be recalculated.
strAddress

If the function is successful, the value of Range.Address will be copied here.
bExternal

TRUE if the address is to be complete, FALSE if the address is local (ie. it excludes workbook and sheet).

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleGetRangeFormula() | CXllCom::OleGetRangeValue()


CXllCom::OleGetRangeFormula

Get the value of Range.Formula

static HRESULT OleGetRangeFormula(
   LPDISPATCH dispRange,
   CString& strFormula
);

Parameters

dispRange

The range to be recalculated.
strFormula

If the function is successful, the value of Range.Formula will be placed here.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleGetRangeValue() | CXllCom::OleGetRangeAddress()


CXllCom::OleGetRangeValue

Get the value of Range.Value

static HRESULT OleGetRangeValue(
   LPDISPATCH dispRange,
   VARIANT* pvntValue
);

Parameters

dispRange

The range to be recalculated.
pvntValue

If the function is successful, the value of Range.Value will be copied here.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleGetRangeFormula() | CXllCom::OleGetRangeAddress()


CXllCom::OleGetRangeWorksheet

Get the value of Range.Worksheet

static HRESULT OleGetRangeWorksheet(
   LPDISPATCH dispRange,
   LPDISPATCH* lpdisp
);

Parameters

dispRange

Range object.
lpdisp

If the function is successful, a pointer to the worksheet object will be placed here. It is the responsibility of the caller to Release() it.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleGetRangeAddress() | CXllCom::OleGetWorksheetWorkbook()


CXllCom::OleGetWarnings

Get the value of Application.DisplayAlerts

HRESULT OleGetWarnings(
   BOOL& bWarnings
);

Parameters

bWarnings

If the function is successful, the value of Application.DisplayAlerts will be placed here.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleSetWarnings()


CXllCom::OleGetWorkbook

Get a member of the Application.Workbooks collection by name

HRESULT OleGetWorkbook(
   LPCSTR pszWorkbook,
   LPDISPATCH* lpdisp
);

Parameters

pszWorkbook

Name of the workbook.
lpdisp

If the function is successful, a pointer to the Workbook object will be placed here. It is the responsibility of the caller to Release() it.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleGetWorkbooks()


CXllCom::OleGetWorkbookName

Get the name of a workbook

static HRESULT OleGetWorkbookName(
   LPDISPATCH dispWorkbook,
   CString& strName
);

Parameters

dispWorkbook

Workbook object.
strName

If the function is successful, the workbook's name will be placed here.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods


CXllCom::OleGetWorkbooks

Get the Application.Workbooks collection

HRESULT OleGetWorkbooks(
   LPDISPATCH* lpdisp
);

Parameters

lpdisp

If the function is successful, a pointer to the Workbooks object will be placed here. It is the responsibility of the caller to Release() it.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleGetWorkbook()


CXllCom::OleGetWorksheet

Get a Worksheet by name

HRESULT OleGetWorksheet(
   LPCSTR pszWorkbook,
   LPCSTR pszWorksheet,
   LPDISPATCH* lpdisp
);

Parameters

pszWorkbook

Name of the workbook.
pszWorksheet

Name of the worksheet.
lpdisp

If the function is successful, a pointer to the Worksheet object will be placed here. It is the responsibility of the caller to Release() it.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleGetWorksheets()


CXllCom::OleGetWorksheetName

Get the name of a worksheet

static HRESULT OleGetWorksheetName(
   LPDISPATCH dispWorksheet,
   CString& strName
);

Parameters

dispWorksheet

Worksheet object.
strName

If the function is successful, the worksheet's name will be placed here.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods


CXllCom::OleGetWorksheets

Get the Worksheets collection for a named workbook

HRESULT OleGetWorksheets(
   LPCSTR pszWorkbook,
   LPDISPATCH* lpdisp
);

Parameters

pszWorkbook

Name of the workbook.
lpdisp

If the function is successful, a pointer to the Worksheets object will be placed here. It is the responsibility of the caller to Release() it.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleGetWorksheet()


CXllCom::OleGetWorksheetWorkbook

Get the value of Worksheet.Parent

static HRESULT OleGetWorksheetWorkbook(
   LPDISPATCH dispWorksheet,
   LPDISPATCH* lpdisp
);

Parameters

dispWorksheet

Worksheet object.
lpdisp

If the function is successful, a pointer to the workbook object will be placed here. It is the responsibility of the caller to Release() it.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleGetRangeWorksheet() | CXllCom::OleGetRangeAddress()


CXllCom::OleRangeIsCurrent

Get the value of Range.Address = Range.CurrentArray.Address

static HRESULT OleRangeIsCurrent(
   LPDISPATCH dispRange,
   BOOL& bIsFirst
);

Parameters

dispRange

The range to be inspected.
bIsFirst

This will be set to TRUE if the range contains a complete array, and FALSE if the range is a superset or subset of it current array.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleRangeIsFirst()


CXllCom::OleRangeIsFirst

Returns whether range is the first (or only) cell of an array

static HRESULT OleRangeIsFirst(
   LPDISPATCH dispRange,
   BOOL& bIsFirst
);

Parameters

dispRange

The range to be inspected.
bIsFirst

This will be set to TRUE if the range is the first (top left) cell of a formula array, or if the range is not part of a formula array. It will be set to FALSE if the range is a member of a formula array, and is not the first cell.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleRangeIsCurrent()


CXllCom::OleSetOnCalculate

Set the value of Application.OnCalculate

HRESULT OleSetOnCalculate(
   const CString& strMacro
);

Parameters

strMacro

The new value of Application.OnCalculate which should be a macro name.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleGetOnCalculate()


CXllCom::OleSetOnSheetActivate

Set the value of Application.OnSheetActivate

HRESULT OleSetOnSheetActivate(
   const CString& strMacro
);

Parameters

strMacro

The new value of Application.OnSheetActivate which should be a macro name.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleGetOnSheetActivate()


CXllCom::OleSetOnSheetDeactivate

Set the value of Application.OnSheetDeactivate

HRESULT OleSetOnSheetDeactivate(
   const CString& strMacro
);

Parameters

strMacro

The new value of Application.OnSheetDeactivate which should be a macro name.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleGetOnSheetDeactivate()


CXllCom::OleSetWarnings

Set the value of Application.DisplayAlerts

HRESULT OleSetWarnings(
   BOOL bWarnings
);

Parameters

bWarnings

The new value of Application.DisplayAlerts.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods | CXllCom::OleSetWarnings()


CXllCom::OleTouchRange

Force a range to recalculate

static HRESULT OleTouchRange(
   LPDISPATCH dispRange
);

Parameters

dispRange

The range to be recalculated.

Remarks

This function calls Range.Formula = Range.Formula or Range.FormulaArray = Range.FormulaArray as is appropriate.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods


CXllCom::OleWorksheetFindFormula

Search for an instance of a formula in a worksheet

static HRESULT OleWorksheetFindFormula(
   LPDISPATCH dispWorksheet,
   LPCSTR pszSearch,
   LPDISPATCH dispLastRange,
   CString& strFirstAddress,
   LPDISPATCH* lpdisp
);

Parameters

dispWorksheet

Worksheet object.
pszSearch

The string to be searched for.
dispLastRange

The range returned by the last call to OleWorksheetFindFormula(). NULL the first time the function is called.
strFirstAddress

If this string is empty, it will be filled with the first address where the search starts. On subsequent calls, it will be used as a stop marker for the search.
lpdisp

If the function is successful, the range containing the search string will be placed here. It is the responsibility of the caller to Release() it.

Requirements

Header: xlpcom.h

See Also

CXllCom Class | CXllCom Methods


xlpconvert.h

Overview

xlpconvert.h contains the global functions that handle the conversion of arguments passed from Excel to more useful types.

The file is automatically included in the project files when the AppWizard creates the XLL+ project.

Functions

The table below lists the principal functions declared in the header file.

Function | Description
XlReadScalar | Reads an optional scalar (single-cell) argument.
XlReadVector | Reads a vector argument.
XlReadMatrix | Reads a matrix argument.

A full list can be found here.

Classes

The table below lists the principal classes declared in the header file.

Class | Description
CXlUserConverterBase | The base class for extended type converter classes.
CScalarConvertParams<T> | The set of parameters used by the scalar conversion functions.
CVectorConvertParams<T> | The set of parameters used by the vector conversion functions.
CMatrixConvertParams<T> | The set of parameters used by the matrix conversion functions.

Enumerations

The table below lists the principal enumerations declared in the header file.

Enumeration | Description
XlConvertFlags | Flag values used by the XLL+ conversion functions.


CMatrixConvertParams<T> Class

The set of parameters used by the matrix conversion functions.

class CMatrixConvertParams<T>

Overview

The CMatrixConvertParams<T> template class is used to pass conversion parameters to the matrix conversion function XlReadMatrix(), which converts an Excel argument (of type CXlOper) into a value of type ple::imtx<T>, or some other container for which an adapter exists.

Requirements

Header: xlpconvert.h

See Also

CMatrixConvertParams<T> Methods | xlpconvert.h | Conversion Functions | CScalarConvertParams<T> class | CVectorConvertParams<T> class


CMatrixConvertParams<T> Methods

The methods of the CMatrixConvertParams<T> class are listed here.

Construction

public method CMatrixConvertParams Constructs a CMatrixConvertParams<T> object

Name

public method | GetArgFullName | Gets the full untranslated name of the argument
public method | GetArgFullNameTranslated | Gets the full translated name of the argument
public method | GetArgName | Gets the untranslated name of the argument
public method | GetArgNameTranslated | Get the name of the argument, translated into the current language

Parameters

public method | GetBoolParam | Gets the value of an extended parameter of boolean type
public method | GetIntParam | Gets the value of an extended parameter of integer type
public method | GetStringParam | Gets the value of an extended parameter of string type
public method | SetBoolParam | Sets the value of an extended parameter of boolean type
public method | SetIntParam | Sets the value of an extended parameter of integer type
public method | SetStringParam | Sets the value of an extended parameter of string type

Requirements

Header: xlpconvert.h

See Also

CMatrixConvertParams<T> Class | xlpconvert.h | Conversion Functions | CScalarConvertParams<T> class | CVectorConvertParams<T> class


CMatrixConvertParams<T>::CMatrixConvertParams

Constructs a CMatrixConvertParams<T> object

CMatrixConvertParams( );
CMatrixConvertParams(
   const wchar_t* argName,
   unsigned long flags = 0,
   long* expectedSize0 = NULL,
   unsigned long lowerBound0 = 0,
   long* expectedSize1 = NULL,
   unsigned long lowerBound1 = 0,
   T& defaultCellValue = T()
);

Parameters

argName

The name of the argument to be converted, as it appears in Excel. This name is inserted into error messages if conversion fails.

flags

A set of flags, which are members of the XlConvertFlags enumeration.

expectedSize0

A pointer to variable that will receive the number of rows in the matrix. If it has already been set (i.e. does not have a value of -1), and the height of the matrix is not equal to the value. then an exception of type CXlConversionException will be thrown, along with a user-friendly message, such as "Expected 15 rows in X". If the pointer is NULL, then the argument will be ignored.

lowerBound0

The number of empty rows to insert at the start of the result matrix. If you are going to pass the matrix to a library function that expects arrays to be 1-based, then this value should be set to 1.

expectedSize1

A pointer to variable that will receive the number of columns in the matrix. If it has already been set (i.e. does not have a value of -1), and the width of the matrix is not equal to the value. then an exception of type CXlConversionException will be thrown, along with a user-friendly message, such as "Expected 15 columns in X". If the pointer is NULL, then the argument will be ignored.

lowerBound1

The number of empty columns to insert at the start of the result matrix. If you are going to pass the matrix to a library function that expects arrays to be 1-based, then this value should be set to 1.

defaultCellValue

The default value to be used if a cell within the argument is empty. Ignored unless flags contains one or more of the XLA_DEFAULT_* values.

Requirements

Header: xlpconvert.h

See Also

CMatrixConvertParams<T> Class | CMatrixConvertParams<T> Methods


CMatrixConvertParams<T>::GetArgFullName

Gets the full untranslated name of the argument

virtual std::wstring GetArgFullName( ) const;

Return Value

Returns the argument name, as passed to the object's constructor.

Requirements

Header: xlpconvert.h

See Also

CMatrixConvertParams<T> Class | CMatrixConvertParams<T> Methods | GetArgName | GetArgFullNameTranslated | GetArgNameTranslated


CMatrixConvertParams<T>::GetArgFullNameTranslated

Gets the full translated name of the argument

virtual std::wstring GetArgFullNameTranslated( ) const;

Return Value

Returns the translated argument name, as passed to the object's constructor. Any numeric IDs are translated using the resources for the current user language.

Requirements

Header: xlpconvert.h

See Also

CMatrixConvertParams<T> Class | CMatrixConvertParams<T> Methods | GetArgName | GetArgFullName | GetArgNameTranslated


CMatrixConvertParams<T>::GetArgName

Gets the untranslated name of the argument

const wchar_t* GetArgName( ) const;

Return Value

Returns the argument name, as passed to the object's constructor.

Requirements

Header: xlpconvert.h

See Also

CMatrixConvertParams<T> Class | CMatrixConvertParams<T> Methods | GetArgNameTranslated | GetArgFullName | GetArgFullNameTranslated


CMatrixConvertParams<T>::GetArgNameTranslated

Get the name of the argument, translated into the current language

CStringW GetArgNameTranslated( ) const;

Return Value

Returns the argument name, with any numeric IDs translated using the resources for the current user language.

Requirements

Header: xlpconvert.h

See Also

CMatrixConvertParams<T> Class | CMatrixConvertParams<T> Methods | GetArgName | GetArgFullName | GetArgFullNameTranslated


CMatrixConvertParams<T>::GetBoolParam

Gets the value of an extended parameter of boolean type

bool GetBoolParam(
   unsigned int index
) const;

Parameters

index

The position of the parameter within the set of boolean extended parameters of the argument.

If the index value is out of range, then an exception of type CXlUserConversionException will be thrown.

Return Value

Returns the value of the specified extended parameter as set by SetBoolParam.

Remarks

This method is used by extended type converter functions in classes derived from CXlUserConverterBase.

Requirements

Header: xlpconvert.h

See Also

CMatrixConvertParams<T> Class | CMatrixConvertParams<T> Methods | SetBoolParam | GetIntParam | SetIntParam | GetStringParam | SetStringParam


CMatrixConvertParams<T>::GetIntParam

Gets the value of an extended parameter of integer type

int GetIntParam(
   unsigned int index
) const;

Parameters

index

The position of the parameter within the set of integer extended parameters of the argument.

If the index value is out of range, then an exception of type CXlUserConversionException will be thrown.

Return Value

Returns the value of the specified extended parameter as set by SetIntParam.

Remarks

This method is used by extended type converter functions in classes derived from CXlUserConverterBase.

Requirements

Header: xlpconvert.h

See Also

CMatrixConvertParams<T> Class | CMatrixConvertParams<T> Methods | SetIntParam | GetBoolParam | SetBoolParam | GetStringParam | SetStringParam


CMatrixConvertParams<T>::GetStringParam

Gets the value of an extended parameter of string type

std::wstring& GetStringParam(
   unsigned int index
) const;

Parameters

index

The position of the parameter within the set of string extended parameters of the argument.

If the index value is out of range, then an exception of type CXlUserConversionException will be thrown.

Return Value

Returns the value of the specified extended parameter as set by SetStringParam.

Remarks

This method is used by extended type converter functions in classes derived from CXlUserConverterBase.

Requirements

Header: xlpconvert.h

See Also

CMatrixConvertParams<T> Class | CMatrixConvertParams<T> Methods | SetStringParam | GetIntParam | SetIntParam | GetBoolParam | SetBoolParam


CMatrixConvertParams<T>::SetBoolParam

Sets the value of an extended parameter of boolean type

CMatrixConvertParams<T>& SetBoolParam(
   unsigned int index,
   bool value
);

Parameters

index

The position of the parameter within the set of boolean extended parameters of the argument.

value

The new value of the parameter.

Return Value

Returns a reference to the calling object, for the convenience of generated code.

Remarks

This method is used by generated code that converts extended types.

Requirements

Header: xlpconvert.h

See Also

CMatrixConvertParams<T> Class | CMatrixConvertParams<T> Methods | GetBoolParam | GetIntParam | SetIntParam | GetStringParam | SetStringParam


CMatrixConvertParams<T>::SetIntParam

Sets the value of an extended parameter of integer type

CMatrixConvertParams<T>& SetIntParam(
   unsigned int index,
   int value
);

Parameters

index

The position of the parameter within the set of integer extended parameters of the argument.

value

The new value of the parameter.

Return Value

Returns a reference to the calling object, for the convenience of generated code.

Remarks

This method is used by generated code that converts extended types.

Requirements

Header: xlpconvert.h

See Also

CMatrixConvertParams<T> Class | CMatrixConvertParams<T> Methods | GetIntParam | GetBoolParam | SetBoolParam | GetStringParam | SetStringParam


CMatrixConvertParams<T>::SetStringParam

Sets the value of an extended parameter of string type

CMatrixConvertParams<T>& SetStringParam(
   unsigned int index,
   const wchar_t* value
);

Parameters

index

The position of the parameter within the set of string extended parameters of the argument.

value

The new value of the parameter.

Return Value

Returns a reference to the calling object, for the convenience of generated code.

Remarks

This method is used by generated code that converts extended types.

Requirements

Header: xlpconvert.h

See Also

CMatrixConvertParams<T> Class | CMatrixConvertParams<T> Methods | GetStringParam | GetIntParam | SetIntParam | GetBoolParam | SetBoolParam


CScalarConvertParams<T> Class

The set of parameters used by the scalar conversion functions.

class CScalarConvertParams<T>

Overview

The CScalarConvertParams<T> template class is used to pass conversion parameters to the scalar conversion function XlReadScalar(), which converts an Excel argument (of type CXlOper) into a value of type T.

Requirements

Header: xlpconvert.h

See Also

CScalarConvertParams<T> Methods | xlpconvert.h | Conversion Functions | CVectorConvertParams<T> class | CMatrixConvertParams<T> class


CScalarConvertParams<T> Methods

The methods of the CScalarConvertParams<T> class are listed here.

Construction

public method CScalarConvertParams Constructs a CScalarConvertParams<T> object

Name

public method | GetArgFullName | Gets the full untranslated name of the argument
public method | GetArgFullNameTranslated | Gets the full translated name of the argument
public method | GetArgName | Gets the untranslated name of the argument
public method | GetArgNameTranslated | Get the name of the argument, translated into the current language

Parameters

public method | GetBoolParam | Gets the value of an extended parameter of boolean type
public method | GetIntParam | Gets the value of an extended parameter of integer type
public method | GetStringParam | Gets the value of an extended parameter of string type
public method | SetBoolParam | Sets the value of an extended parameter of boolean type
public method | SetIntParam | Sets the value of an extended parameter of integer type
public method | SetStringParam | Sets the value of an extended parameter of string type

Requirements

Header: xlpconvert.h

See Also

CScalarConvertParams<T> Class | xlpconvert.h | Conversion Functions | CVectorConvertParams<T> class | CMatrixConvertParams<T> class


CScalarConvertParams<T>::CScalarConvertParams

Constructs a CScalarConvertParams<T> object

CScalarConvertParams( );
CScalarConvertParams(
   const wchar_t* argName,
   unsigned long flags,
   const wchar_t* groupName = 0,
   size_t index = (size_t)-1,
   T& defaultValue = T()
);

Parameters

argName

The name of the argument to be converted, as it appears in Excel. This name is inserted into error messages if conversion fails.

flags

A set of flags, which are members of the XlConvertFlags enumeration.

groupName

The name of the grouped argument of which this argument is an item. Ignored unless flags contains XLA_OPER_IS_GROUP.

index

The position of the argument within its container. Used by error messages to indicate which item within a vector or matrix could not be converted.

defaultValue

The default value to be used if the argument is missing or empty. Ignored unless flags contains one or more of the XLA_DEFAULT_* values.

Requirements

Header: xlpconvert.h

See Also

CScalarConvertParams<T> Class | CScalarConvertParams<T> Methods


CScalarConvertParams<T>::GetArgFullName

Gets the full untranslated name of the argument

virtual std::wstring GetArgFullName( ) const;

Return Value

Returns the argument name, as passed to the object's constructor, along with any indexing suffixes which apply if the object is being used to extract scalar values from a vector or matrix input, e.g. x[2] or y[3,1].

Requirements

Header: xlpconvert.h

See Also

CScalarConvertParams<T> Class | CScalarConvertParams<T> Methods | GetArgName | GetArgFullNameTranslated | GetArgNameTranslated


CScalarConvertParams<T>::GetArgFullNameTranslated

Gets the full translated name of the argument

virtual std::wstring GetArgFullNameTranslated( ) const;

Return Value

Returns the translated argument name, as passed to the object's constructor, along with any indexing suffixes which apply if the object is being used to extract scalar values from a vector or matrix input, e.g. x[2] or y[3,1]. In addition, any numeric IDs are translated using the resources for the current user language.

Requirements

Header: xlpconvert.h

See Also

CScalarConvertParams<T> Class | CScalarConvertParams<T> Methods | GetArgName | GetArgFullName | GetArgNameTranslated


CScalarConvertParams<T>::GetArgName

Gets the untranslated name of the argument

const wchar_t* GetArgName( ) const;

Return Value

Returns the argument name, as passed to the object's constructor.

Requirements

Header: xlpconvert.h

See Also

CScalarConvertParams<T> Class | CScalarConvertParams<T> Methods | GetArgNameTranslated | GetArgFullName | GetArgFullNameTranslated


CScalarConvertParams<T>::GetArgNameTranslated

Get the name of the argument, translated into the current language

CStringW GetArgNameTranslated( ) const;

Return Value

Returns the argument name, with any numeric IDs translated using the resources for the current user language.

Requirements

Header: xlpconvert.h

See Also

CScalarConvertParams<T> Class | CScalarConvertParams<T> Methods | GetArgName | GetArgFullName | GetArgFullNameTranslated


CScalarConvertParams<T>::GetBoolParam

Gets the value of an extended parameter of boolean type

bool GetBoolParam(
   unsigned int index
) const;

Parameters

index

The position of the parameter within the set of boolean extended parameters of the argument.

If the index value is out of range, then an exception of type CXlUserConversionException will be thrown.

Return Value

Returns the value of the specified extended parameter as set by SetBoolParam.

Remarks

This method is used by extended type converter functions in classes derived from CXlUserConverterBase.

Requirements

Header: xlpconvert.h

See Also

CScalarConvertParams<T> Class | CScalarConvertParams<T> Methods | SetBoolParam | GetIntParam | SetIntParam | GetStringParam | SetStringParam


CScalarConvertParams<T>::GetIntParam

Gets the value of an extended parameter of integer type

int GetIntParam(
   unsigned int index
) const;

Parameters

index

The position of the parameter within the set of integer extended parameters of the argument.

If the index value is out of range, then an exception of type CXlUserConversionException will be thrown.

Return Value

Returns the value of the specified extended parameter as set by SetIntParam.

Remarks

This method is used by extended type converter functions in classes derived from CXlUserConverterBase.

Requirements

Header: xlpconvert.h

See Also

CScalarConvertParams<T> Class | CScalarConvertParams<T> Methods | SetIntParam | GetBoolParam | SetBoolParam | GetStringParam | SetStringParam


CScalarConvertParams<T>::GetStringParam

Gets the value of an extended parameter of string type

std::wstring& GetStringParam(
   unsigned int index
) const;

Parameters

index

The position of the parameter within the set of string extended parameters of the argument.

If the index value is out of range, then an exception of type CXlUserConversionException will be thrown.

Return Value

Returns the value of the specified extended parameter as set by SetStringParam.

Remarks

This method is used by extended type converter functions in classes derived from CXlUserConverterBase.

Requirements

Header: xlpconvert.h

See Also

CScalarConvertParams<T> Class | CScalarConvertParams<T> Methods | SetStringParam | GetIntParam | SetIntParam | GetBoolParam | SetBoolParam


CScalarConvertParams<T>::SetBoolParam

Sets the value of an extended parameter of boolean type

CScalarConvertParams<T>& SetBoolParam(
   unsigned int index,
   bool value
);

Parameters

index

The position of the parameter within the set of boolean extended parameters of the argument.

value

The new value of the parameter.

Return Value

Returns a reference to the calling object, for the convenience of generated code.

Remarks

This method is used by generated code that converts extended types.

Requirements

Header: xlpconvert.h

See Also

CScalarConvertParams<T> Class | CScalarConvertParams<T> Methods | GetBoolParam | GetIntParam | SetIntParam | GetStringParam | SetStringParam


CScalarConvertParams<T>::SetIntParam

Sets the value of an extended parameter of integer type

CScalarConvertParams<T>& SetIntParam(
   unsigned int index,
   int value
);

Parameters

index

The position of the parameter within the set of integer extended parameters of the argument.

value

The new value of the parameter.

Return Value

Returns a reference to the calling object, for the convenience of generated code.

Remarks

This method is used by generated code that converts extended types.

Requirements

Header: xlpconvert.h

See Also

CScalarConvertParams<T> Class | CScalarConvertParams<T> Methods | GetIntParam | GetBoolParam | SetBoolParam | GetStringParam | SetStringParam


CScalarConvertParams<T>::SetStringParam

Sets the value of an extended parameter of string type

CScalarConvertParams<T>& SetStringParam(
   unsigned int index,
   const wchar_t* value
);

Parameters

index

The position of the parameter within the set of string extended parameters of the argument.

value

The new value of the parameter.

Return Value

Returns a reference to the calling object, for the convenience of generated code.

Remarks

This method is used by generated code that converts extended types.

Requirements

Header: xlpconvert.h

See Also

CScalarConvertParams<T> Class | CScalarConvertParams<T> Methods | GetStringParam | GetIntParam | SetIntParam | GetBoolParam | SetBoolParam


CVectorConvertParams<T> Class

The set of parameters used by the vector conversion functions.

class CVectorConvertParams<T>

Overview

The CVectorConvertParams<T> template class is used to pass conversion parameters to the vector conversion function XlReadVector(), which converts an Excel argument (of type CXlOper) into a value of type std::vector<T>.

Requirements

Header: xlpconvert.h

See Also

CVectorConvertParams<T> Methods | xlpconvert.h | Conversion Functions | CScalarConvertParams<T> class | CMatrixConvertParams<T> class


CVectorConvertParams<T> Methods

The methods of the CVectorConvertParams<T> class are listed here.

Construction

public method CVectorConvertParams Constructs a CVectorConvertParams<T> object

Name

public method | GetArgFullName | Gets the full untranslated name of the argument
public method | GetArgFullNameTranslated | Gets the full translated name of the argument
public method | GetArgName | Gets the untranslated name of the argument
public method | GetArgNameTranslated | Get the name of the argument, translated into the current language

Parameters

public method | GetBoolParam | Gets the value of an extended parameter of boolean type
public method | GetIntParam | Gets the value of an extended parameter of integer type
public method | GetStringParam | Gets the value of an extended parameter of string type
public method | SetBoolParam | Sets the value of an extended parameter of boolean type
public method | SetIntParam | Sets the value of an extended parameter of integer type
public method | SetStringParam | Sets the value of an extended parameter of string type

Requirements

Header: xlpconvert.h

See Also

CVectorConvertParams<T> Class | xlpconvert.h | Conversion Functions | CScalarConvertParams<T> class | CMatrixConvertParams<T> class


CVectorConvertParams<T>::CVectorConvertParams

Constructs a CVectorConvertParams<T> object

CVectorConvertParams( );
CVectorConvertParams(
   const wchar_t* argName,
   unsigned long flags = 0,
   const wchar_t* groupName = 0,
   size_t rowOrColumn = (size_t)-1,
   long* expectedSize = 0,
   unsigned long lowerBound = 0,
   T& defaultCellValue = T()
);

Parameters

argName

The name of the argument to be converted, as it appears in Excel. This name is inserted into error messages if conversion fails.

flags

A set of flags, which are members of the XlConvertFlags enumeration.

groupName

The name of the grouped argument of which this argument is an item. Ignored unless flags contains XLA_OPER_IS_GROUP.

rowOrColumn

The position of the argument within its container. Used by error messages to indicate which item within a matrix group could not be converted.

expectedSize

A pointer to an integer containing the expected size of the vector, or -1 if the size is not yet known. Used to compare the sizes of vectors that are constrained with regard to size. Ignored if NULL.

During the conversion function, if *expectedSize contains a non-negative number then the size of the vector being read will be compared to that value and, if they do not match, an exception of type CXlConversionException is thrown. If *expectedSize contains a number, then it will be set to the size of the vector being read.

lowerBound

The number of empty items to insert at the start of the result vector. If you are going to pass the vector to a library function that expects vectors to be 1-based, then this value should be set to 1.

defaultCellValue

The default value to be used if a cell within the argument is empty. Ignored unless flags contains one or more of the XLA_DEFAULT_* values.

Requirements

Header: xlpconvert.h

See Also

CVectorConvertParams<T> Class | CVectorConvertParams<T> Methods


CVectorConvertParams<T>::GetArgFullName

Gets the full untranslated name of the argument

virtual std::wstring GetArgFullName( ) const;

Return Value

Returns the argument name, as passed to the object's constructor, along with any indexing suffixes which apply if the object is being used to extract vector values from a matrix input, e.g. x[2] or y[3].

Requirements

Header: xlpconvert.h

See Also

CVectorConvertParams<T> Class | CVectorConvertParams<T> Methods | GetArgName | GetArgFullNameTranslated | GetArgNameTranslated


CVectorConvertParams<T>::GetArgFullNameTranslated

Gets the full translated name of the argument

virtual std::wstring GetArgFullNameTranslated( ) const;

Return Value

Returns the translated argument name, as passed to the object's constructor, along with any indexing suffixes which apply if the object is being used to extract vector values from a matrix input, e.g. x[2] or y[3]. In addition, any numeric IDs are translated using the resources for the current user language.

Requirements

Header: xlpconvert.h

See Also

CVectorConvertParams<T> Class | CVectorConvertParams<T> Methods | GetArgName | GetArgFullName | GetArgNameTranslated


CVectorConvertParams<T>::GetArgName

Gets the untranslated name of the argument

const wchar_t* GetArgName( ) const;

Return Value

Returns the argument name, as passed to the object's constructor.

Requirements

Header: xlpconvert.h

See Also

CVectorConvertParams<T> Class | CVectorConvertParams<T> Methods | GetArgNameTranslated | GetArgFullName | GetArgFullNameTranslated


CVectorConvertParams<T>::GetArgNameTranslated

Get the name of the argument, translated into the current language

CStringW GetArgNameTranslated( ) const;

Return Value

Returns the argument name, with any numeric IDs translated using the resources for the current user language.

Requirements

Header: xlpconvert.h

See Also

CVectorConvertParams<T> Class | CVectorConvertParams<T> Methods | GetArgName | GetArgFullName | GetArgFullNameTranslated


CVectorConvertParams<T>::GetBoolParam

Gets the value of an extended parameter of boolean type

bool GetBoolParam(
   unsigned int index
) const;

Parameters

index

The position of the parameter within the set of boolean extended parameters of the argument.

If the index value is out of range, then an exception of type CXlUserConversionException will be thrown.

Return Value

Returns the value of the specified extended parameter as set by SetBoolParam.

Remarks

This method is used by extended type converter functions in classes derived from CXlUserConverterBase.

Requirements

Header: xlpconvert.h

See Also

CVectorConvertParams<T> Class | CVectorConvertParams<T> Methods | SetBoolParam | GetIntParam | SetIntParam | GetStringParam | SetStringParam


CVectorConvertParams<T>::GetIntParam

Gets the value of an extended parameter of integer type

int GetIntParam(
   unsigned int index
) const;

Parameters

index

The position of the parameter within the set of integer extended parameters of the argument.

If the index value is out of range, then an exception of type CXlUserConversionException will be thrown.

Return Value

Returns the value of the specified extended parameter as set by SetIntParam.

Remarks

This method is used by extended type converter functions in classes derived from CXlUserConverterBase.

Requirements

Header: xlpconvert.h

See Also

CVectorConvertParams<T> Class | CVectorConvertParams<T> Methods | SetIntParam | GetBoolParam | SetBoolParam | GetStringParam | SetStringParam


CVectorConvertParams<T>::GetStringParam

Gets the value of an extended parameter of string type

std::wstring& GetStringParam(
   unsigned int index
) const;

Parameters

index

The position of the parameter within the set of string extended parameters of the argument.

If the index value is out of range, then an exception of type CXlUserConversionException will be thrown.

Return Value

Returns the value of the specified extended parameter as set by SetStringParam.

Remarks

This method is used by extended type converter functions in classes derived from CXlUserConverterBase.

Requirements

Header: xlpconvert.h

See Also

CVectorConvertParams<T> Class | CVectorConvertParams<T> Methods | SetStringParam | GetIntParam | SetIntParam | GetBoolParam | SetBoolParam


CVectorConvertParams<T>::SetBoolParam

Sets the value of an extended parameter of boolean type

CVectorConvertParams<T>& SetBoolParam(
   unsigned int index,
   bool value
);

Parameters

index

The position of the parameter within the set of boolean extended parameters of the argument.

value

The new value of the parameter.

Return Value

Returns a reference to the calling object, for the convenience of generated code.

Remarks

This method is used by generated code that converts extended types.

Requirements

Header: xlpconvert.h

See Also

CVectorConvertParams<T> Class | CVectorConvertParams<T> Methods | GetBoolParam | GetIntParam | SetIntParam | GetStringParam | SetStringParam


CVectorConvertParams<T>::SetIntParam

Sets the value of an extended parameter of integer type

CVectorConvertParams<T>& SetIntParam(
   unsigned int index,
   int value
);

Parameters

index

The position of the parameter within the set of integer extended parameters of the argument.

value

The new value of the parameter.

Return Value

Returns a reference to the calling object, for the convenience of generated code.

Remarks

This method is used by generated code that converts extended types.

Requirements

Header: xlpconvert.h

See Also

CVectorConvertParams<T> Class | CVectorConvertParams<T> Methods | GetIntParam | GetBoolParam | SetBoolParam | GetStringParam | SetStringParam


CVectorConvertParams<T>::SetStringParam

Sets the value of an extended parameter of string type

CVectorConvertParams<T>& SetStringParam(
   unsigned int index,
   const wchar_t* value
);

Parameters

index

The position of the parameter within the set of string extended parameters of the argument.

value

The new value of the parameter.

Return Value

Returns a reference to the calling object, for the convenience of generated code.

Remarks

This method is used by generated code that converts extended types.

Requirements

Header: xlpconvert.h

See Also

CVectorConvertParams<T> Class | CVectorConvertParams<T> Methods | GetStringParam | GetIntParam | SetIntParam | GetBoolParam | SetBoolParam


CXlUserConverterBase<ElemType, XlNativeType> Class

The template class for user-defined type converters.

class CXlUserConverterBase<ElemType, XlNativeType>

Overview

To add a new data type to the XLL+ framework, a converter class must be written and registered. All converter classes are derived from CXlUserConverterBase.

Deriving a class from CXlUserConverterBase<ElemType, XlNativeType>

To implement a class derived from CXlUserConverterBase, the developer must provide:

  1. A public constructor with no arguments.
  2. ConvertFromExcel()
  3. One of the following:
    1. GetTypeMessageId
    2. GetTypeNameW
    3. GetTypeName

The developer may also choose to implement ConvertToExcel() so that extended types can be returned to Excel.

See Creating an extended type in the User Guide for more information.

XlNativeType

The table below lists the types available for use as the XlNativeType template argument, along with the type required for the excelType attribute of the <ScalarType> element in the extension file.

excelType attribute | XlNativeType
Boolean | bool BOOL
Double | double
String | CString CStringA CStringW std::tstring std::string std::wstring
Short | short int
UShort | unsigned short int
Int | long

Requirements

Header: xlpconvert.h

See Also

CXlUserConverterBase<ElemType, XlNativeType> Methods | xlpconvert.h | Extended types


CXlUserConverterBase<ElemType, XlNativeType> Methods

The methods of the CXlUserConverterBase<ElemType, XlNativeType> class are listed here.

Construction

public method CXlUserConverterBase Constructs a CXlUserConverterBase object

Overrideables

public method | ConvertFromExcel | Converts a single value from Excel format to a native type
public method | ConvertToExcel | Converts a single value from a C++ type to Excel format

Names

public method | GetTypeMessageId | Returns the ID of a resource string containing the extended type name
public method | GetTypeName | Returns the name of the extended type
public method | GetTypeNameW | Returns the name of the extended type as a wide string
public method | ResolveTypeName | Returns the name of the extended type for use in error messages

Requirements

Header: xlpconvert.h

See Also

CXlUserConverterBase<ElemType, XlNativeType> Class | xlpconvert.h | Extended types


CXlUserConverterBase<ElemType, XlNativeType>::ConvertFromExcel

Converts a single value from Excel format to a native type

virtual bool ConvertFromExcel(
   const XlNativeType& xlValue,
   ElemType& outerValue,
   const CConvertParamsBase& params
) const;

Parameters

xlValue

A reference to a value extracted from the Excel argument. This needs to be converted to type ElemType
outerValue

A reference to a the target value. If the conversion succeeds, this should be set to the converted value.

params

The conversion parameters supplied for the conversion. These include the argument name, and any extended type parameters set by the developer when the argument was specified.

Return Value

Returns true if the conversion succeeds, and outerValue has been read from xlValue and set to a valid value. Returns false if the conversion fails.

Remarks

TODO

Exceptions

TODO - CXlUserConversionException

Requirements

Header: xlpconvert.h

See Also

CXlUserConverterBase<ElemType, XlNativeType> Class | CXlUserConverterBase<ElemType, XlNativeType> Methods


CXlUserConverterBase<ElemType, XlNativeType>::ConvertToExcel

Converts a single value from a C++ type to Excel format

virtual bool ConvertToExcel(
   const ElemType& outerValue,
   XlNativeType& xlValue,
   const CConvertParamsBase& params
) const;

Parameters

outerValue

A reference to an ElemType value which is to be returned to Excel. This needs to be converted to type XlNativeType
xlValue

A reference to a the target value. If the conversion succeeds, this should be set to the converted value.

params

The conversion parameters supplied for the conversion. These include the argument name, and any extended type parameters set by the developer when the argument was specified.

Return Value

Returns true if the conversion succeeds, and xlValue has been read from outerValue and set to a valid value. Returns false if the conversion fails.

Remarks

This method is only called by the global conversion functions XlWriteScalarEx(), XlWriteVectorEx() and XlWriteMatrixEx(). It does not need to be implemented unless you are intending to return results of the extended type ElemType to Excel. The default implementation of the function fails (returns false).

Requirements

Header: xlpconvert.h

See Also

CXlUserConverterBase<ElemType, XlNativeType> Class | CXlUserConverterBase<ElemType, XlNativeType> Methods


CXlUserConverterBase<ElemType, XlNativeType>::CXlUserConverterBase

Constructs a CXlUserConverterBase object

CXlUserConverterBase( );

Remarks

The constructor for a class derived from CXlUserConverterBase should also not have any arguments.

Requirements

Header: xlpconvert.h

See Also

CXlUserConverterBase<ElemType, XlNativeType> Class | CXlUserConverterBase<ElemType, XlNativeType> Methods


CXlUserConverterBase<ElemType, XlNativeType>::GetTypeMessageId

Returns the ID of a resource string containing the extended type name

virtual unsigned int GetTypeMessageId(
   const CConvertParamsBase& params
) const;

Parameters

params

The conversion parameters supplied for the conversion. These include the argument name, and any extended type parameters set by the developer when the argument was specified.

Return Value

Returns 0 if no resource string is available. Returns the ID of a string in the application resource file if this is available.

Remarks

This method offers a localizable way of defining the name of an extended type. A string needs to be added to the resource file containing the name, e.g. "date". The method should return the resource ID of the string. If this method is not implemented then the default implementation will return 0.

Name resolution

If validation fails, and false is returned by one of the conversion methods, then the extended type name will be resolved using the first of the following methods that has been implemented in the concrete class.

  1. GetTypeMessageId
  2. GetTypeNameW
  3. GetTypeName

Requirements

Header: xlpconvert.h

See Also

CXlUserConverterBase<ElemType, XlNativeType> Class | CXlUserConverterBase<ElemType, XlNativeType> Methods


CXlUserConverterBase<ElemType, XlNativeType>::GetTypeName

Returns the name of the extended type

virtual std::string GetTypeName(
   const CConvertParamsBase& params
) const;

Parameters

params

The conversion parameters supplied for the conversion. These include the argument name, and any extended type parameters set by the developer when the argument was specified.

Return Value

Returns the name of the extended type, as it will appear in error messages.

Remarks

This method should return the name of the extended type in singular form, e.g. "date".

Name resolution

If validation fails, and false is returned by one of the conversion methods, then the extended type name will be resolved using the first of the following methods that has been implemented in the concrete class.

  1. GetTypeMessageId
  2. GetTypeNameW
  3. GetTypeName

Requirements

Header: xlpconvert.h

See Also

CXlUserConverterBase<ElemType, XlNativeType> Class | CXlUserConverterBase<ElemType, XlNativeType> Methods


CXlUserConverterBase<ElemType, XlNativeType>::GetTypeNameW

Returns the name of the extended type as a wide string

virtual std::wstring GetTypeNameW(
   const CConvertParamsBase& params
) const;

Parameters

params

The conversion parameters supplied for the conversion. These include the argument name, and any extended type parameters set by the developer when the argument was specified.

Return Value

Returns the name of the extended type as a wide string, as it will appear in error messages.

Remarks

This method should return the name of the extended type in singular form, e.g. L"date".

Name resolution

If validation fails, and false is returned by one of the conversion methods, then the extended type name will be resolved using the first of the following methods that has been implemented in the concrete class.

  1. GetTypeMessageId
  2. GetTypeNameW
  3. GetTypeName

Requirements

Header: xlpconvert.h

See Also

CXlUserConverterBase<ElemType, XlNativeType> Class | CXlUserConverterBase<ElemType, XlNativeType> Methods


CXlUserConverterBase<ElemType, XlNativeType>::ResolveTypeName

Returns the name of the extended type for use in error messages

virtual std::wstring ResolveTypeName(
   const CConvertParamsBase& params
) const;

Parameters

params

The conversion parameters supplied for the conversion. These include the argument name, and any extended type parameters set by the developer when the argument was specified.

Return Value

Returns the name of the extended type, as it will appear in error messages.

Remarks

If validation fails, and false is returned by one of the conversion methods, then the ResolveTypeName will be used to resolve the extended type name. It will use the first of the following methods that has been implemented in the concrete class.

  1. GetTypeMessageId
  2. GetTypeNameW
  3. GetTypeName

Requirements

Header: xlpconvert.h

See Also

CXlUserConverterBase<ElemType, XlNativeType> Class | CXlUserConverterBase<ElemType, XlNativeType> Methods


Global conversion functions

Global conversion functions are listed here.

Remarks

For a detailed discussion of the conversion functions see the technical note Conversion functions.

Conversion

public method | XlReadGroupedScalar | Transform one item in a grouped CXlOper into a single value
public method | XlReadGroupedScalarEx | Transform one item in a grouped CXlOper into a single value of an extended type
public method | XlReadGroupedVector | Transform one row or column of a CXlOper into a vector
public method | XlReadGroupedVectorEx | Transform one row or column of a CXlOper into a vector of an extended type
public method | XlReadMatrix | Transform a CXlOper into a matrix
public method | XlReadMatrixEx | Transform a CXlOper into a matrix of an extended type
public method | XlReadScalar | Transform a CXlOper into a single value
public method | XlReadScalarEx | Transform a CXlOper into a single value of an extended type
public method | XlReadVector | Transform all or part of a CXlOper into a vector
public method | XlReadVectorEx | Transform all or part of a CXlOper into a vector of an extended type

Conversion of return values

public method | XlWriteMatrixEx | Transform a matrix of extended type values into a CXlOper
public method | XlWriteScalarEx | Transform a single value of extended type into a CXlOper
public method | XlWriteVectorEx | Transform a vector of extended type values into a CXlOper

Requirements

Header: xlpconvert.h

See Also

xlpconvert.h


::XlReadGroupedScalar

Transform one item in a grouped CXlOper into a single value

template< class T >
void XlReadGroupedScalar(
   const CXlOper& xlo,
   T& value,
   const wchar_t* groupName,
   unsigned long index,
   const wchar_t* argName,
   unsigned long flags = 0,
   const T& defaultValue = T()
);

Parameters

xlo

A reference to the input passed by Excel. This will contain all members of the group.
value

A reference to a variable into which the result will placed, if the conversion is successful.
groupName

The name of the Excel argument that contains the group. This will be used in error messages.

index

The index of the item within the group.

argName

The name of the item within the group that is being converted. This will be used in error messages, and may also be used to search the grouped input.

flags

A set of flags that control the conversion. See Conversion functions for a list of values.

defaultValue

The default value that will be used for an optional argument, if the argument is omitted by the user.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpconvert.h

See Also

Global conversion functions


::XlReadGroupedScalarEx

Transform one item in a grouped CXlOper into a single value of an extended type

template< class T, class XLT >
void XlReadGroupedScalarEx(
   const CXlOper& xlo,
   T& value,
   const CXlUserConverterBase<T, XLT>& outerConverter,
   const wchar_t* groupName,
   unsigned long index,
   const wchar_t* argName,
   unsigned long flags = 0,
   const T& defaultValue = T()
);

Parameters

xlo

A reference to the input passed by Excel. This will contain all members of the group.
value

A reference to a variable into which the result will placed, if the conversion is successful.
outerConverter

An instance of the extended type's converter class. See CXlUserConverterBase for details.

groupName

The name of the Excel argument that contains the group. This will be used in error messages.

index

The index of the item within the group.

argName

The name of the item within the group that is being converted. This will be used in error messages, and may also be used to search the grouped input.

flags

A set of flags that control the conversion. See Conversion functions for a list of values.

defaultValue

The default value that will be used for an optional argument, if the argument is omitted by the user.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpconvert.h

See Also

Global conversion functions


::XlReadGroupedVector

Transform one row or column of a CXlOper into a vector

template< class T >
void XlReadGroupedVector(
   const CXlOper& xlo,
   std::vector<T>& value,
   const wchar_t* groupName,
   unsigned long rowOrColumn,
   const wchar_t* argName,
   unsigned long flags = 0,
   long* expectedSize = NULL,
   unsigned long lowerBound = 0,
   const T& defaultCellValue = T()
);

Parameters

xlo

A reference to the input passed by Excel.
value

A reference to a variable into which the results will placed, if the conversion is successful.
groupName

The name of the Excel argument that contains the vector group. This will be used in error messages.

rowOrColumn

The index of the item within the group. Depending on the orientation of the vector group, this may be a row index or a column index.

argName

The name of the item within the group that is being converted. This will be used in error messages, and may also be used to search the grouped input.

flags

A set of flags that control the conversion. See Conversion functions for a list of values.

expectedSize

A pointer to variable that will receive the size of the vector. If it has already been set (i.e. does not have a value of -1), and the size of the vector is not equal to the value. then an exception of type CXlConversionException will be thrown, along with a user-friendly message, such as "Expected 15 items in X". If the pointer is NULL, then the argument will be ignored.

lowerBound

The number of empty items to insert at the start of the result vector. If you are going to pass the vector to a library function that expects vectors to be 1-based, then this value should be set to 1.

defaultCellValue

The default value that will be used for empty cells, if the appropriate flags have been set for the conversion.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpconvert.h

See Also

Global conversion functions


::XlReadGroupedVectorEx

Transform one row or column of a CXlOper into a vector of an extended type

template< class T, class XLT >
void XlReadGroupedVectorEx(
   const CXlOper& xlo,
   std::vector<T>& value,
   const CXlUserConverterBase<T, XLT>& outerConverter,
   const wchar_t* groupName,
   unsigned long rowOrColumn,
   const wchar_t* argName,
   unsigned long flags = 0,
   long* expectedSize = NULL,
   unsigned long lowerBound = 0,
   const T& defaultCellValue = T()
);

Parameters

xlo

A reference to the input passed by Excel.
value

A reference to a variable into which the results will placed, if the conversion is successful.
outerConverter

An instance of the extended type's converter class. See CXlUserConverterBase for details.

groupName

The name of the Excel argument that contains the vector group. This will be used in error messages.

rowOrColumn

The index of the item within the group. Depending on the orientation of the vector group, this may be a row index or a column index.

argName

The name of the item within the group that is being converted. This will be used in error messages, and may also be used to search the grouped input.

flags

A set of flags that control the conversion. See Conversion functions for a list of values.

expectedSize

A pointer to variable that will receive the size of the vector. If it has already been set (i.e. does not have a value of -1), and the size of the vector is not equal to the value. then an exception of type CXlConversionException will be thrown, along with a user-friendly message, such as "Expected 15 items in X". If the pointer is NULL, then the argument will be ignored.

lowerBound

The number of empty items to insert at the start of the result vector. If you are going to pass the vector to a library function that expects vectors to be 1-based, then this value should be set to 1.

defaultCellValue

The default value that will be used for empty cells, if the appropriate flags have been set for the conversion.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpconvert.h

See Also

Global conversion functions


::XlReadMatrix

Transform a CXlOper into a matrix

template< class T >
void XlReadMatrix(
   const CXlOper& xlo,
   ple::imtx<T>& value,
   CMatrixConvertParams<T>& params
);
template< class T >
void XlReadMatrix(
   const CXlOper& xlo,
   ple::imtx<T>& value,
   const wchar_t* argName,
   unsigned long flags = 0,
   long* expectedSize0 = NULL,
   unsigned long lowerBound0 = 0,
   long* expectedSize1 = NULL,
   unsigned long lowerBound1 = 0,
   const T& defaultCellValue = T()
);

Parameters

xlo

A reference to the input passed by Excel.
value

A reference to a variable into which the results will placed, if the conversion is successful.
params

A set of parameters that control the conversion.

See CMatrixConvertParams<T> for details.
argName

The name of the argument that is being converted. This will be used in error messages.

flags

A set of flags that control the conversion. See Conversion functions for a list of values.

expectedSize0

A pointer to variable that will receive the number of rows in the matrix. If it has already been set (i.e. does not have a value of -1), and the height of the matrix is not equal to the value. then an exception of type CXlConversionException will be thrown, along with a user-friendly message, such as "Expected 15 rows in X". If the pointer is NULL, then the argument will be ignored.

lowerBound0

The number of empty rows to insert at the start of the result matrix. If you are going to pass the matrix to a library function that expects arrays to be 1-based, then this value should be set to 1.

expectedSize1

A pointer to variable that will receive the number of columns in the matrix. If it has already been set (i.e. does not have a value of -1), and the width of the matrix is not equal to the value. then an exception of type CXlConversionException will be thrown, along with a user-friendly message, such as "Expected 15 columns in X". If the pointer is NULL, then the argument will be ignored.

lowerBound1

The number of empty columns to insert at the start of the result matrix. If you are going to pass the matrix to a library function that expects arrays to be 1-based, then this value should be set to 1.

defaultCellValue

The default value that will be used for empty cells, if the appropriate flags have been set for the conversion.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpconvert.h

See Also

Global conversion functions


::XlReadMatrixEx

Transform a CXlOper into a matrix of an extended type

template< class T, class XLT >
void XlReadMatrixEx(
   const CXlOper& xlo,
   ple::imtx<T>& value,
   const CXlUserConverterBase<T, XLT>& outerConverter,
   CMatrixConvertParams<T>& params
);
template< class T, class XLT >
void XlReadMatrixEx(
   const CXlOper& xlo,
   ple::imtx<T>& value,
   const CXlUserConverterBase<T, XLT>& outerConverter,
   const wchar_t* argName,
   unsigned long flags = 0,
   long* expectedSize0 = NULL,
   unsigned long lowerBound0 = 0,
   long* expectedSize1 = NULL,
   unsigned long lowerBound1 = 0,
   const T& defaultCellValue = T()
);

Parameters

xlo

A reference to the input passed by Excel.
value

A reference to a variable into which the results will placed, if the conversion is successful.
outerConverter

An instance of the extended type's converter class. See CXlUserConverterBase for details.

params

A set of parameters that control the conversion.

See CMatrixConvertParams<T> for details.
argName

The name of the argument that is being converted. This will be used in error messages.

flags

A set of flags that control the conversion. See Conversion functions for a list of values.

expectedSize0

A pointer to variable that will receive the number of rows in the matrix. If it has already been set (i.e. does not have a value of -1), and the height of the matrix is not equal to the value. then an exception of type CXlConversionException will be thrown, along with a user-friendly message, such as "Expected 15 rows in X". If the pointer is NULL, then the argument will be ignored.

lowerBound0

The number of empty rows to insert at the start of the result vector. If you are going to pass the matrix to a library function that expects arrays to be 1-based, then this value should be set to 1.

expectedSize1

A pointer to variable that will receive the number of columns in the matrix. If it has already been set (i.e. does not have a value of -1), and the width of the matrix is not equal to the value. then an exception of type CXlConversionException will be thrown, along with a user-friendly message, such as "Expected 15 columns in X". If the pointer is NULL, then the argument will be ignored.

lowerBound1

The number of empty columns to insert at the start of the result vector. If you are going to pass the matrix to a library function that expects arrays to be 1-based, then this value should be set to 1.

defaultCellValue

The default value that will be used for empty cells, if the appropriate flags have been set for the conversion.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpconvert.h

See Also

Global conversion functions


::XlReadScalar

Transform a CXlOper into a single value

template< class T >
void XlReadScalar(
   const CXlOper& xlo,
   T& value,
   CScalarConvertParams<T>& params
);
template< class T >
void XlReadScalar(
   const CXlOper& xlo,
   T& value,
   const wchar_t* argName,
   unsigned long flags = 0,
   const T& defaultValue = T()
);

Parameters

xlo

A reference to the input passed by Excel.
value

A reference to a variable into which the result will placed, if the conversion is successful.
params

A set of parameters that control the conversion. See CScalarConvertParams<T> for details.

argName

The name of the argument that is being converted. This will be used in error messages.

flags

A set of flags that control the conversion. See Conversion functions for a list of values.

defaultValue

The default value that will be used for an optional argument, if the argument is omitted by the user.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpconvert.h

See Also

Global conversion functions


::XlReadScalarEx

Transform a CXlOper into a single value of an extended type

template< class T, class XLT >
void XlReadScalarEx(
   const CXlOper& xlo,
   T& value,
   const CXlUserConverterBase<T, XLT>& outerConverter,
   CScalarConvertParams<T>& params
);
template< class T, class XLT >
void XlReadScalarEx(
   const CXlOper& xlo,
   T& value,
   const CXlUserConverterBase<T, XLT>& outerConverter,
   const wchar_t* argName,
   unsigned long flags = 0,
   const T& defaultValue = T()
);
template< class T, class XLT >
void XlReadScalarEx(
   const XLT& nativeValue,
   T& value,
   const CXlUserConverterBase<T, XLT>& outerConverter,
   CScalarConvertParams<T>& params
);
template< class T, class XLT >
void XlReadScalarEx(
   const XLT& nativeValue,
   T& value,
   const CXlUserConverterBase<T, XLT>& outerConverter,
   const wchar_t* argName
);

Parameters

xlo

A reference to the input passed by Excel.
value

A reference to a variable into which the result will placed, if the conversion is successful.
outerConverter

An instance of the extended type's converter class. See CXlUserConverterBase for details.

params

A set of parameters that control the conversion. See CScalarConvertParams<T> for details.

argName

The name of the argument that is being converted. This will be used in error messages.

flags

A set of flags that control the conversion. See Conversion functions for a list of values.

defaultValue

The default value that will be used for an optional argument, if the argument is omitted by the user.

nativeValue

A reference to the input passed by Excel in its native form.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpconvert.h

See Also

Global conversion functions


::XlReadVector

Transform all or part of a CXlOper into a vector

template< class T >
void XlReadVector(
   const CXlOper& xlo,
   std::vector<T>& value,
   CVectorConvertParams<T>& params
);
template< class T >
void XlReadVector(
   const CXlOper& xlo,
   std::vector<T>& value,
   const wchar_t* argName,
   unsigned long flags = 0,
   long* expectedSize = NULL,
   unsigned long lowerBound = 0,
   const T& defaultCellValue = T()
);

Parameters

xlo

A reference to the input passed by Excel.
value

A reference to a variable into which the results will placed, if the conversion is successful.
params

A set of parameters that control the conversion.

See CVectorConvertParams<T> for details.
argName

The name of the argument that is being converted. This will be used in error messages.

flags

A set of flags that control the conversion. See Conversion functions for a list of values.

expectedSize

A pointer to variable that will receive the size of the vector. If it has already been set (i.e. does not have a value of -1), and the size of the vector is not equal to the value. then an exception of type CXlConversionException will be thrown, along with a user-friendly message, such as "Expected 15 items in X". If the pointer is NULL, then the argument will be ignored.

lowerBound

The number of empty items to insert at the start of the result vector. If you are going to pass the vector to a library function that expects vectors to be 1-based, then this value should be set to 1.

defaultCellValue

The default value that will be used for empty cells, if the appropriate flags have been set for the conversion.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpconvert.h

See Also

Global conversion functions


::XlReadVectorEx

Transform all or part of a CXlOper into a vector of an extended type

template< class T, class XLT >
void XlReadVectorEx(
   const CXlOper& xlo,
   std::vector<T>& value,
   const CXlUserConverterBase<T, XLT>& outerConverter,
   CVectorConvertParams<T>& params
);
template< class T, class XLT >
void XlReadVectorEx(
   const CXlOper& xlo,
   std::vector<T>& value,
   const CXlUserConverterBase<T, XLT>& outerConverter,
   const wchar_t* argName,
   unsigned long flags = 0,
   long* expectedSize = NULL,
   unsigned long lowerBound = 0,
   const T& defaultCellValue = T()
);

Parameters

xlo

A reference to the input passed by Excel.
value

A reference to a variable into which the results will placed, if the conversion is successful.
outerConverter

An instance of the extended type's converter class. See CXlUserConverterBase for details.

params

A set of parameters that control the conversion.

See CVectorConvertParams<T> for details.
argName

The name of the argument that is being converted. This will be used in error messages.

flags

A set of flags that control the conversion. See Conversion functions for a list of values.

expectedSize

A pointer to variable that will receive the size of the vector. If it has already been set (i.e. does not have a value of -1), and the size of the vector is not equal to the value. then an exception of type CXlConversionException will be thrown, along with a user-friendly message, such as "Expected 15 items in X". If the pointer is NULL, then the argument will be ignored.

lowerBound

The number of empty items to insert at the start of the result vector. If you are going to pass the vector to a library function that expects vectors to be 1-based, then this value should be set to 1.

defaultCellValue

The default value that will be used for empty cells, if the appropriate flags have been set for the conversion.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpconvert.h

See Also

Global conversion functions


::XlWriteMatrixEx

Transform a matrix of extended type values into a CXlOper

template< class T, class XLT >
void XlWriteMatrixEx(
   const ple::mtx_imtx<T>& values,
   CXlOper& xlo,
   const CXlUserConverterBase<T, XLT>& outerConverter
);

Parameters

values

A reference to an input variable containing a matrix of extended type values.
xlo

A reference to a CXlOper which will be set to values, if the conversion is successful.

outerConverter

An instance of the extended type's converter class. See CXlUserConverterBase for details.

If the converter class does not implement ConvertToExcel() then this method will fail, and an exception of type CXlConversionException will be thrown.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpconvert.h

See Also

Global conversion functions


::XlWriteScalarEx

Transform a single value of extended type into a CXlOper

template< class T, class XLT >
void XlWriteScalarEx(
   const T& value,
   CXlOper& xlo,
   const CXlUserConverterBase<T, XLT>& outerConverter
);

Parameters

value

A reference to an input variable containing an extended type value.
xlo

A reference to a CXlOper which will be set to value, if the conversion is successful.
outerConverter

An instance of the extended type's converter class. See CXlUserConverterBase for details.

If the converter class does not implement ConvertToExcel() then this method will fail, and an exception of type CXlConversionException will be thrown.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpconvert.h

See Also

Global conversion functions


::XlWriteVectorEx

Transform a vector of extended type values into a CXlOper

template< class T, class XLT >
void XlWriteVectorEx(
   const std::vector<T>& values,
   CXlOper& xlo,
   const CXlUserConverterBase<T, XLT>& outerConverter,
   bool asRow = false
);

Parameters

values

A reference to an input variable containing a vector of extended type values.
xlo

A reference to a CXlOper which will be set to values, if the conversion is successful.

outerConverter

An instance of the extended type's converter class. See CXlUserConverterBase for details.

If the converter class does not implement ConvertToExcel() then this method will fail, and an exception of type CXlConversionException will be thrown.

asRow

Controls the shape of the resulting Excel array. If false, then the result will be a column; if true, it will be a row.

Remarks

If the function fails for any reason, an exception of type CXlConversionException is thrown. This will be caught by the outer wrapper function, and converted into an appropriate form to be returned to Excel.

Requirements

Header: xlpconvert.h

See Also

Global conversion functions


Enumerations

The enumerations declared in xlpconvert.h are listed below.

XlConvertFlags

Requirements

Header: xlpconvert.h

See Also

xlpconvert.h


XlConvertFlags Enumeration

The conversion flags used by XLL+ run-time library conversion functions.

enum XlConvertFlags

Overview

The XlConvertFlags enumeration contains the conversion flags used by XLL+ run-time library conversion functions.

For more information please see the technical note Conversion functions.

Members

XLA_TRUNC_ONZERO | 0x00000001 | Arrays are truncated when a cell containing the value zero is encountered.
XLA_TRUNC_ONEMPTY | 0x00000002 | Arrays are truncated when an empty cell is encountered.
XLA_TRUNC_ONNONNUMERIC | 0x00000004 | Arrays are truncated when a cell containing a non-numeric value is encountered.
XLA_TRUNC_ONBLANK | 0x00000008 | Arrays are truncated when a cell containing a blank string (e.g. ="") is encountered.
XLA_FILL_USED_AREA | 0x01000000 | Any empty cell in the used area of an input array is filled with the default value.
XLA_FILL_ALL | 0x02000000 | Any empty cell in the entire area of an input array is filled with the default value.
XLA_DEFAULT_ZERO | 0x00000010 | Use default value if cell contains zero.
XLA_DEFAULT_EMPTY | 0x00000020 | Use default value if cell is empty.
XLA_DEFAULT_NONNUMERIC | 0x00000040 | Use default value if cell contains a non-numeric value.
XLA_DEFAULT_BLANK | 0x00000080 | Use default value if cell contains a blank (e.g. ="").
XLA_FLAG_TRANSPOSE | 0x00000100 | Transpose the rows and columns of a matrix input.
XLA_FLAG_VECTOR_COLUMN | 0x00004000 | A vector input must in the form of a column (i.e. a vertical array).
XLA_FLAG_VECTOR_ROW | 0x00010000 | A vector input must in the form of a row (i.e. a horizontal array).
XLA_BOUND_UBOUND_INNER | 0x00100000 | A array whose size is constrained will treat the constraint as the index of the upper bound, i.e. size - 1
XLA_BOUND_UBOUND_AUTO | 0x00100000 | A array whose size is constrained will treat the constraint as the index of the upper bound, i.e. size - 1, if the lower bound of the dimension is not zero. If the lower bound is zero (or is not specified) then the constraint will be treated as the size of the array (in the given dimension).
XLA_CELL_DEFAULT_ZERO | 0x08000000 | If an array is to be filled, fill cells that contain the value zero.
XLA_CELL_DEFAULT_EMPTY | 0x10000000 | If an array is to be filled, fill cells that are empty.
XLA_CELL_DEFAULT_NONNUMERIC | 0x20000000 | If an array is to be filled, fill cells that are non-numeric.
XLA_CELL_DEFAULT_BLANK | 0x40000000 | If an array is to be filled, fill cells that are blank.
XLA_OPER_IS_GROUP | 0x00020000 | This flag is used internally by the conversion functions, and should not be set by any other code.

Requirements

Header: xlpconvert.h

See Also

xlpconvert.h | Exceptions | CXlErrorException


xlpevents.h

Overview

xlpevents.h contains definitions of all the event-related classes that implement the XLL+ unified event model.

The file is automatically included in the project files when the AppWizard creates the XLL+ project.

Classes

The table below lists the core classes declared in the header file.

Class | Description
CXlEvent | The base class for events. This class implements the Subject of the observer pattern.
CXlEventArgs | The base class for the arguments passed with any event.
CXlEventObserver | The template class for event observers. This class implements the Observer of the observer pattern.
CXlStaticEventObserver | The base class for event observers that are created statically, and register themselves automatically.

Event classes

The table below lists the concrete event classes declared in the header file.

Class | Description
CXllOpenEvent | Occurs when the XLL is opened, after OnXllOpenEx().
CXllCloseEvent | Occurs when the XLL is closed, before OnXllClose().
CXlRegisterFunctionsEvent | Occurs before the XLL's add-in functions are registered.
CXlNewWorkbookEvent | Occurs when a new workbook is created.
CXlSelectionChangeEvent | Occurs when Excel's active cell selection is changed.
CXlBeforeDoubleClickEvent | Occurs when the user double-clicks in a worksheet.
CXlBeforeRightClickEvent | Occurs when the user right-clicks in a worksheet.
CXlSheetActivateEvent | Occurs when a worksheet is activated.
CXlSheetDeactivateEvent | Occurs when a worksheet is deactivated.
CXlCalculateEvent | Occurs just after Excel has finished calculating a worksheet.
CXlSheetChangeEvent | Occurs when a cell is changed in a worksheet.
CXlWorkbookOpenEvent | Occurs when a workbook is opened.
CXlWorkbookActivateEvent | Occurs when a workbook is activated.
CXlWorkbookDeactivateEvent | Occurs when a workbook is deactivated.
CXlWorkbookBeforeCloseEvent | Occurs when a workbook is about to be closed, and allows the event to be cancelled.
CXlWorkbookBeforeSaveEvent | Occurs when a workbook is about to be saved, and allows the event to be cancelled.
CXlWorkbookNewSheetEvent | Occurs when a new worksheet is added to a workbook.
CXlAfterCalculateEvent | Occurs after one or more worksheets have been calculated (only available under Excel 2010/Excel 14 or above).
CXlWorkbookAfterSaveEvent | Occurs after a workbook has been saved, and provides the new workbook name if the name has been changed by the user (only available under Excel 2010/Excel 14 or above).

Event argument classes

The table below lists the event argument classes declared in the header file.

Class | Description
CXllOpenArgs | An event argument class allowing the event to be cancelled.
CXlWorkbookEventArgs | An event argument class containing only a workbook name.
CXlWorksheetEventArgs | An event argument class containing only a complete worksheet name.
CXlRangeEventArgs | An event argument class containing a complete worksheet name, and a range address.
CXlCancellableRangeEventArgs | An event argument class containing a complete worksheet name, and a range address, which can be used to cancel the event.
CXlBeforeCloseEventArgs | An event argument class specifying a workbook about to be closed, which can be used to cancel the event.
CXlBeforeSaveEventArgs | An event argument class specifying a workbook about to be saved, which can be used to cancel the event.
CXlWorkbookNewSheetEventArgs | An event argument class specifying a workbook and its new sheet.
CXlAfterSaveEventArgs | An event argument class specifying a workbook which has been saved, with the saved name of the workbook and a flag indicating whether the save operation succeeded.
CXlAfterCalculateEventArgs | An event argument class passed for the AfterCalculate event. It contains no data.

Static observer classes

The table below lists the static observer classes declared in the header file. There is one class for each concrete event.

Class | Description
CXllOpenEventStaticObserver | Observes CXllOpenEvent.
CXllCloseEventStaticObserver | Observes CXllCloseEvent.
CXlRegisterFunctionsEventStaticObserver | Observes CXlRegisterFunctionsEvent.
CXlNewWorkbookEventStaticObserver | Observes CXlNewWorkbookEvent.
CXlSelectionChangeEventStaticObserver | Observes CXlSelectionChangeEvent.
CXlBeforeDoubleClickEventStaticObserver | Observes CXlBeforeDoubleClickEvent.
CXlBeforeRightClickEventStaticObserver | Observes CXlBeforeRightClickEvent.
CXlSheetActivateEventStaticObserver | Observes CXlSheetActivateEvent.
CXlSheetDeactivateEventStaticObserver | Observes CXlSheetDeactivateEvent.
CXlCalculateEventStaticObserver | Observes CXlCalculateEvent.
CXlSheetChangeEventStaticObserver | Observes CXlSheetChangeEvent.
CXlWorkbookOpenEventStaticObserver | Observes CXlWorkbookOpenEvent.
CXlWorkbookActivateEventStaticObserver | Observes CXlWorkbookActivateEvent.
CXlWorkbookDeactivateEventStaticObserver | Observes CXlWorkbookDeactivateEvent.
CXlWorkbookBeforeCloseEventStaticObserver | Observes CXlWorkbookBeforeCloseEvent.
CXlWorkbookBeforeSaveEventStaticObserver | Observes CXlWorkbookBeforeSaveEvent.
CXlWorkbookNewSheetEventStaticObserver | Observes CXlWorkbookNewSheetEvent.
CXlWorkbookAfterSaveEventStaticObserver | Observes CXlWorkbookAfterSaveEvent.
CXlAfterCalculateEventStaticObserver | Observes CXlAfterCalculateEvent.


CXlAfterCalculateEvent Class

An event which is raised after one or more worksheets are calculated.

class CXlAfterCalculateEvent : public CXlEvent

Overview

The event occurs after one or more worksheets have been calculated.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlAfterCalculateEventStaticObserver.

When observers are notified, an argument of type CXlAfterCalculateEventArgs is passed.

Availability

Note that this event is only available when running under Excel 2010 (Excel 14) or above.

Requirements

Header: xlpevents.h

See Also

CXlAfterCalculateEvent Methods | xlpevents.h | CXllApp::AfterCalculateEvent | Events | CXlAfterCalculateEventArgs | CXlAfterCalculateEventStaticObserver


CXlAfterCalculateEvent Methods

The methods of the CXlAfterCalculateEvent class are listed here.

Construction

public method CXlAfterCalculateEvent Constructs a CXlAfterCalculateEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlAfterCalculateEvent Class | xlpevents.h | CXllApp::AfterCalculateEvent | Events | CXlAfterCalculateEventArgs | CXlAfterCalculateEventStaticObserver


CXlAfterCalculateEvent::CXlAfterCalculateEvent

Constructs a CXlAfterCalculateEvent object

CXlAfterCalculateEvent( );

Requirements

Header: xlpevents.h

See Also

CXlAfterCalculateEvent Class | CXlAfterCalculateEvent Methods


CXlAfterCalculateEventArgs Class

An event argument class containing no additional data.

class CXlAfterCalculateEventArgs : public CXlEventArgs

Overview

This is the event argument used by the following workbook event:

  • CXlAfterCalculateEvent

Requirements

Header: xlpevents.h

See Also

CXlAfterCalculateEventArgs Methods | xlpevents.h | Events


CXlAfterCalculateEventArgs Methods

The methods of the CXlAfterCalculateEventArgs class are listed here.

Construction

public method CXlAfterCalculateEvent Constructs a CXlAfterCalculateEvent object

Methods of CXlEventArgs

Requirements

Header: xlpevents.h

See Also

CXlAfterCalculateEventArgs Class | xlpevents.h | Events


CXlAfterCalculateEventArgs::CXlAfterCalculateEvent

Constructs a CXlAfterCalculateEvent object

CXlAfterCalculateEvent( );

Requirements

Header: xlpevents.h

See Also

CXlAfterCalculateEventArgs Class | CXlAfterCalculateEventArgs Methods


CXlAfterCalculateEventStaticObserver Class

An event observer for XlAfterCalculate, which is automatically registered and unregistered.

class CXlAfterCalculateEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

During the XlAfterCalculate event, after the completion of the calculation of one or more sheets, the object's Update method will be called.

See the Update method for an example of this class in use.

Availability

Note that this event is only available when running under Excel 2010 (Excel 14) or above.

Requirements

Header: xlpevents.h

See Also

CXlAfterCalculateEventStaticObserver Methods | xlpevents.h | CXlAfterCalculateEvent | Events


CXlAfterCalculateEventStaticObserver Methods

The methods of the CXlAfterCalculateEventStaticObserver class are listed here.

Construction

public method CXlAfterCalculateEventStaticObserver Constructs a CXlAfterCalculateEventStaticObserver object

Events

public method Update Respond to an event

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlAfterCalculateEventStaticObserver Class | xlpevents.h | CXlAfterCalculateEvent | Events


CXlAfterCalculateEventStaticObserver::CXlAfterCalculateEventStaticObserver

Constructs a CXlAfterCalculateEventStaticObserver object

CXlAfterCalculateEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

See the Update method for an example of this class in use.

Availability

Note that this event is only available when running under Excel 2010 (Excel 14) or above.

Requirements

Header: xlpevents.h

See Also

CXlAfterCalculateEventStaticObserver Class | CXlAfterCalculateEventStaticObserver Methods


CXlAfterCalculateEventStaticObserver::Update

Respond to an event

virtual void Update(
   CXlAfterCalculateEventArgs* e
);

Parameters

e

A pointer to an event arguments object is sent to the Update method.

Remarks

Derived classes should implement this function, which is the event handler for the XLL+ event model.

Availability

Note that this event is only available when running under Excel 2010 (Excel 14) or above.

Example

The code below defines a class derived from CXlCalculateEventStaticObserver, implements an Update method which is called when the event occurs, and instantiates an instance of the new class.

CopyC++
// Define a class derived from CXlAfterCalculateEventStaticObserver
class CMyAfterCalculateEventObserver : CXlAfterCalculateEventStaticObserver
{
public:
    // This method will be called during the XlAfterCalculate event.
    virtual void Update(CXlAfterCalculateEventArgs* e)
    {
        CXllApp::XlMessageBox(_T("Calculation complete"),
            XlMessageBoxTypeInformation);
    }
};

// Create an instance of the class
CMyAfterCalculateEventObserver myAfterCalculateObserver;

Requirements

Header: xlpevents.h

See Also

CXlAfterCalculateEventStaticObserver Class | CXlAfterCalculateEventStaticObserver Methods


CXlAfterSaveEventArgs Class

An event argument class identifying a workbook about to be saved, which contains the saved name of the workbook and a flag indicating whether the save operation was successful.

class CXlAfterSaveEventArgs : public CXlEventArgs

Overview

This is the event argument used by the following workbook event:

  • CXlWorkbookAfterSaveEvent

Requirements

Header: xlpevents.h

See Also

CXlAfterSaveEventArgs Methods | xlpevents.h | Events


CXlAfterSaveEventArgs Methods

The methods of the CXlAfterSaveEventArgs class are listed here.

Construction

public method CXlAfterSaveEventArgs Constructs a CXlAfterSaveEventArgs object

Properties

public method | GetBookName | Gets the name of the workbook
public method | GetSuccess | Gets the value of the Success flag

Methods of CXlEventArgs

Requirements

Header: xlpevents.h

See Also

CXlAfterSaveEventArgs Class | xlpevents.h | Events


CXlAfterSaveEventArgs::CXlAfterSaveEventArgs

Constructs a CXlAfterSaveEventArgs object

CXlAfterSaveEventArgs(
   const TCHAR* bookName,
   bool bSuccess
);

Parameters

bookName

The name of the workbook for which the event is being raised.
bSuccess

True if the workbook was saved successfully; false if the save operation failed.

Requirements

Header: xlpevents.h

See Also

CXlAfterSaveEventArgs Class | CXlAfterSaveEventArgs Methods


CXlAfterSaveEventArgs::GetBookName

Gets the name of the workbook

const CString& GetBookName( ) const;

Return Value

Returns a reference to the name of the workbook for which the event is being raised.

Requirements

Header: xlpevents.h

See Also

CXlAfterSaveEventArgs Class | CXlAfterSaveEventArgs Methods


CXlAfterSaveEventArgs::GetSuccess

Gets the value of the Success flag

bool GetSuccess( ) const;

Return Value

Returns the value of the Success flag.

Requirements

Header: xlpevents.h

See Also

CXlAfterSaveEventArgs Class | CXlAfterSaveEventArgs Methods


CXlBeforeCloseEventArgs Class

An event argument class identifying a workbook about to be saved, which allows the event to be cancelled.

class CXlBeforeCloseEventArgs : public CXlEventArgs

Overview

This is the event argument used by the following workbook event:

  • CXlWorkbookBeforeCloseEvent

Requirements

Header: xlpevents.h

See Also

CXlBeforeCloseEventArgs Methods | xlpevents.h | Events


CXlBeforeCloseEventArgs Methods

The methods of the CXlBeforeCloseEventArgs class are listed here.

Construction

public method CXlBeforeCloseEventArgs Constructs a CXlBeforeCloseEventArgs object

Properties

public method | GetBookName | Gets the name of the workbook
public method | GetCancel | Gets the value of the event cancel flag
public method | SetCancel | Sets the value of the event cancel flag

Methods of CXlEventArgs

Requirements

Header: xlpevents.h

See Also

CXlBeforeCloseEventArgs Class | xlpevents.h | Events


CXlBeforeCloseEventArgs::CXlBeforeCloseEventArgs

Constructs a CXlBeforeCloseEventArgs object

CXlBeforeCloseEventArgs(
   const TCHAR* bookName
);

Parameters

bookName

The name of the workbook for which the event is being raised.

Requirements

Header: xlpevents.h

See Also

CXlBeforeCloseEventArgs Class | CXlBeforeCloseEventArgs Methods


CXlBeforeCloseEventArgs::GetBookName

Gets the name of the workbook

const CString& GetBookName( ) const;

Return Value

Returns a reference to the name of the workbook for which the event is being raised.

Requirements

Header: xlpevents.h

See Also

CXlBeforeCloseEventArgs Class | CXlBeforeCloseEventArgs Methods


CXlBeforeCloseEventArgs::GetCancel

Gets the value of the event cancel flag

bool GetCancel( ) const;

Return Value

Returns the value of the event cancel flag. If it is true, then the event has been cancelled. If it is false, the event will occur.

Requirements

Header: xlpevents.h

See Also

CXlBeforeCloseEventArgs Class | CXlBeforeCloseEventArgs Methods


CXlBeforeCloseEventArgs::SetCancel

Sets the value of the event cancel flag

void SetCancel(
   bool cancel
);

Parameters

cancel

true to cancel the event. false to let it continue.

Remarks

This method can be used by an event observer to cancel the event being notified.

Requirements

Header: xlpevents.h

See Also

CXlBeforeCloseEventArgs Class | CXlBeforeCloseEventArgs Methods


CXlBeforeDoubleClickEvent Class

An event which is raised when the user double-clicks in a worksheet.

class CXlBeforeDoubleClickEvent : public CXlEvent

Overview

The event occurs when the user double-clicks in a worksheet.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlBeforeDoubleClickEventStaticObserver.

When observers are notified, an argument of type CXlCancellableRangeEventArgs is passed. Observers can cancel normal processing of the double-click by cancelling the event using CXlCancellableRangeEventArgs::SetCancel(false).

Requirements

Header: xlpevents.h

See Also

CXlBeforeDoubleClickEvent Methods | xlpevents.h | CXllApp::BeforeDoubleClickEvent | Events | CXlCancellableRangeEventArgs | CXlBeforeDoubleClickEventStaticObserver


CXlBeforeDoubleClickEvent Methods

The methods of the CXlBeforeDoubleClickEvent class are listed here.

Construction

public method CXlBeforeDoubleClickEvent Constructs a CXlBeforeDoubleClickEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlBeforeDoubleClickEvent Class | xlpevents.h | CXllApp::BeforeDoubleClickEvent | Events | CXlCancellableRangeEventArgs | CXlBeforeDoubleClickEventStaticObserver


CXlBeforeDoubleClickEvent::CXlBeforeDoubleClickEvent

Constructs a CXlBeforeDoubleClickEvent object

CXlBeforeDoubleClickEvent( );

Requirements

Header: xlpevents.h

See Also

CXlBeforeDoubleClickEvent Class | CXlBeforeDoubleClickEvent Methods


CXlBeforeDoubleClickEventStaticObserver Class

An event observer for XlBeforeDoubleClick, which is automatically registered and unregistered.

class CXlBeforeDoubleClickEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

During the XlBeforeDoubleClick event, the object's Update method will be called.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlBeforeDoubleClickEventStaticObserver Methods | xlpevents.h | CXlBeforeDoubleClickEvent | Events


CXlBeforeDoubleClickEventStaticObserver Methods

The methods of the CXlBeforeDoubleClickEventStaticObserver class are listed here.

Construction

public method CXlBeforeDoubleClickEventStaticObserver Constructs a CXlBeforeDoubleClickEventStaticObserver object

Events

public method Update Respond to an event

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlBeforeDoubleClickEventStaticObserver Class | xlpevents.h | CXlBeforeDoubleClickEvent | Events


CXlBeforeDoubleClickEventStaticObserver::CXlBeforeDoubleClickEventStaticObserver

Constructs a CXlBeforeDoubleClickEventStaticObserver object

CXlBeforeDoubleClickEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlBeforeDoubleClickEventStaticObserver Class | CXlBeforeDoubleClickEventStaticObserver Methods


CXlBeforeDoubleClickEventStaticObserver::Update

Respond to an event

virtual void Update(
   CXlCancellableRangeEventArgs* e
);

Parameters

e

A pointer to an event arguments object is sent to the Update method.

Remarks

Derived classes should implement this function, which is the event handler for the XLL+ event model.

Example

The code below defines a class derived from CXlBeforeDoubleClickEventStaticObserver, implements an Update method which is called when the event occurs, and instantiates an instance of the new class.

Note that this particular Update method uses CXlCancellableRangeEventArgs::SetCancel to cancel the double-click event. As a result, Excel does not switch to edit mode.

CopyC++
// Define a class derived from CXlBeforeDoubleClickEventStaticObserver
class CMyBeforeDoubleClickEventObserver : CXlBeforeDoubleClickEventStaticObserver
{
public:
    // This method will be called during the XlBeforeDoubleClick event.
    virtual void Update(CXlCancellableRangeEventArgs* e)
    {
        CXllApp::XlMessageBox(_T("Double-click at ") + e->GetRange(),
            XlMessageBoxTypeInformation);
        e->SetCancel(true);
    }
};

// Create an instance of the class
CMyBeforeDoubleClickEventObserver myDoubleClickObserver;

Requirements

Header: xlpevents.h

See Also

CXlBeforeDoubleClickEventStaticObserver Class | CXlBeforeDoubleClickEventStaticObserver Methods


CXlBeforeRightClickEvent Class

An event which is raised when the user right-clicks in a worksheet.

class CXlBeforeRightClickEvent : public CXlEvent

Overview

The event occurs when the user right-clicks in a worksheet.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlBeforeRightClickEventStaticObserver.

When observers are notified, an argument of type CXlCancellableRangeEventArgs is passed. Observers can cancel normal processing of the right-click by cancelling the event using CXlCancellableRangeEventArgs::SetCancel(false).

Requirements

Header: xlpevents.h

See Also

CXlBeforeRightClickEvent Methods | xlpevents.h | CXllApp::BeforeRightClickEvent | Events | CXlCancellableRangeEventArgs | CXlBeforeRightClickEventStaticObserver


CXlBeforeRightClickEvent Methods

The methods of the CXlBeforeRightClickEvent class are listed here.

Construction

public method CXlBeforeRightClickEvent Constructs a CXlBeforeRightClickEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlBeforeRightClickEvent Class | xlpevents.h | CXllApp::BeforeRightClickEvent | Events | CXlCancellableRangeEventArgs | CXlBeforeRightClickEventStaticObserver


CXlBeforeRightClickEvent::CXlBeforeRightClickEvent

Constructs a CXlBeforeRightClickEvent object

CXlBeforeRightClickEvent( );

Requirements

Header: xlpevents.h

See Also

CXlBeforeRightClickEvent Class | CXlBeforeRightClickEvent Methods


CXlBeforeRightClickEventStaticObserver Class

An event observer for XlBeforeRightClick, which is automatically registered and unregistered.

class CXlBeforeRightClickEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

Requirements

Header: xlpevents.h

See Also

CXlBeforeRightClickEventStaticObserver Methods | xlpevents.h | CXlBeforeRightClickEvent | Events


CXlBeforeRightClickEventStaticObserver Methods

The methods of the CXlBeforeRightClickEventStaticObserver class are listed here.

Construction

public method CXlBeforeRightClickEventStaticObserver Constructs a CXlBeforeRightClickEventStaticObserver object

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlBeforeRightClickEventStaticObserver Class | xlpevents.h | CXlBeforeRightClickEvent | Events


CXlBeforeRightClickEventStaticObserver::CXlBeforeRightClickEventStaticObserver

Constructs a CXlBeforeRightClickEventStaticObserver object

CXlBeforeRightClickEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

Requirements

Header: xlpevents.h

See Also

CXlBeforeRightClickEventStaticObserver Class | CXlBeforeRightClickEventStaticObserver Methods


CXlBeforeSaveEventArgs Class

An event argument class identifying a workbook about to be saved, which allows the event to be cancelled.

class CXlBeforeSaveEventArgs : public CXlEventArgs

Overview

This is the event argument used by the following workbook event:

  • CXlWorkbookBeforeSaveEvent

Requirements

Header: xlpevents.h

See Also

CXlBeforeSaveEventArgs Methods | xlpevents.h | Events


CXlBeforeSaveEventArgs Methods

The methods of the CXlBeforeSaveEventArgs class are listed here.

Construction

public method CXlBeforeSaveEventArgs Constructs a CXlBeforeSaveEventArgs object

Properties

public method | GetBookName | Gets the name of the workbook
public method | GetCancel | Gets the value of the event cancel flag
public method | GetSaveAsUI | Gets the value of the SaveAsUI flag
public method | SetCancel | Sets the value of the event cancel flag

Methods of CXlEventArgs

Requirements

Header: xlpevents.h

See Also

CXlBeforeSaveEventArgs Class | xlpevents.h | Events


CXlBeforeSaveEventArgs::CXlBeforeSaveEventArgs

Constructs a CXlBeforeSaveEventArgs object

CXlBeforeSaveEventArgs(
   const TCHAR* bookName,
   bool bSaveAsUI
);

Parameters

bookName

The name of the workbook for which the event is being raised.
bSaveAsUI

True if the "Save As" user interface will be used, in which case the workbook name may change.

Requirements

Header: xlpevents.h

See Also

CXlBeforeSaveEventArgs Class | CXlBeforeSaveEventArgs Methods


CXlBeforeSaveEventArgs::GetBookName

Gets the name of the workbook

const CString& GetBookName( ) const;

Return Value

Returns a reference to the name of the workbook for which the event is being raised.

Requirements

Header: xlpevents.h

See Also

CXlBeforeSaveEventArgs Class | CXlBeforeSaveEventArgs Methods


CXlBeforeSaveEventArgs::GetCancel

Gets the value of the event cancel flag

bool GetCancel( ) const;

Return Value

Returns the value of the event cancel flag. If it is true, then the event has been cancelled. If it is false, the event will occur.

Requirements

Header: xlpevents.h

See Also

CXlBeforeSaveEventArgs Class | CXlBeforeSaveEventArgs Methods


CXlBeforeSaveEventArgs::GetSaveAsUI

Gets the value of the SaveAsUI flag

bool GetSaveAsUI( ) const;

Return Value

Returns the value of the SaveAsUI flag.

Requirements

Header: xlpevents.h

See Also

CXlBeforeSaveEventArgs Class | CXlBeforeSaveEventArgs Methods


CXlBeforeSaveEventArgs::SetCancel

Sets the value of the event cancel flag

void SetCancel(
   bool cancel
);

Parameters

cancel

true to cancel the event. false to let it continue.

Remarks

This method can be used by an event observer to cancel the event being notified.

Requirements

Header: xlpevents.h

See Also

CXlBeforeSaveEventArgs Class | CXlBeforeSaveEventArgs Methods


CXlCalculateEvent Class

An event which is raised after a worksheet is calculated.

class CXlCalculateEvent : public CXlEvent

Overview

The event occurs after a worksheet is calculated.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlCalculateEventStaticObserver.

When observers are notified, an argument of type CXlWorksheetEventArgs is passed.

Requirements

Header: xlpevents.h

See Also

CXlCalculateEvent Methods | xlpevents.h | CXllApp::CalculateEvent | Events | CXlWorksheetEventArgs | CXlCalculateEventStaticObserver


CXlCalculateEvent Methods

The methods of the CXlCalculateEvent class are listed here.

Construction

public method CXlCalculateEvent Constructs a CXlCalculateEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlCalculateEvent Class | xlpevents.h | CXllApp::CalculateEvent | Events | CXlWorksheetEventArgs | CXlCalculateEventStaticObserver


CXlCalculateEvent::CXlCalculateEvent

Constructs a CXlCalculateEvent object

CXlCalculateEvent( );

Requirements

Header: xlpevents.h

See Also

CXlCalculateEvent Class | CXlCalculateEvent Methods


CXlCalculateEventStaticObserver Class

An event observer for XlCalculate, which is automatically registered and unregistered.

class CXlCalculateEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

During the XlCalculate event, after the completion of the calculation of a sheet, the object's Update method will be called.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlCalculateEventStaticObserver Methods | xlpevents.h | CXlCalculateEvent | Events


CXlCalculateEventStaticObserver Methods

The methods of the CXlCalculateEventStaticObserver class are listed here.

Construction

public method CXlCalculateEventStaticObserver Constructs a CXlCalculateEventStaticObserver object

Events

public method Update Respond to an event

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlCalculateEventStaticObserver Class | xlpevents.h | CXlCalculateEvent | Events


CXlCalculateEventStaticObserver::CXlCalculateEventStaticObserver

Constructs a CXlCalculateEventStaticObserver object

CXlCalculateEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlCalculateEventStaticObserver Class | CXlCalculateEventStaticObserver Methods


CXlCalculateEventStaticObserver::Update

Respond to an event

virtual void Update(
   CXlWorksheetEventArgs* e
);

Parameters

e

A pointer to an event arguments object is sent to the Update method.

Remarks

Derived classes should implement this function, which is the event handler for the XLL+ event model.

Example

The code below defines a class derived from CXlCalculateEventStaticObserver, implements an Update method which is called when the event occurs, and instantiates an instance of the new class.

CopyC++
// Define a class derived from CXlCalculateEventStaticObserver
class CMyCalculateEventObserver : CXlCalculateEventStaticObserver
{
public:
    // This method will be called during the XlCalculate event.
    virtual void Update(CXlWorksheetEventArgs* e)
    {
        CXllApp::XlMessageBox(_T("Calculating ") + e->GetSheetName(),
            XlMessageBoxTypeInformation);
    }
};

// Create an instance of the class
CMyCalculateEventObserver myCalculateObserver;

Requirements

Header: xlpevents.h

See Also

CXlCalculateEventStaticObserver Class | CXlCalculateEventStaticObserver Methods


CXlCancellableRangeEventArgs Class

An event argument class containing a complete worksheet name and the name of the cell range affected, which can be used to cancel the event.

class CXlCancellableRangeEventArgs : public CXlEventArgs

Overview

This is the event argument used by the following events:

  • CXlBeforeDoubleClickEvent
  • CXlBeforeRightClickEvent

Requirements

Header: xlpevents.h

See Also

CXlCancellableRangeEventArgs Methods | xlpevents.h | Events


CXlCancellableRangeEventArgs Methods

The methods of the CXlCancellableRangeEventArgs class are listed here.

Construction

public method CXlCancellableRangeEventArgs Constructs a CXlCancellableRangeEventArgs object

Properties

public method | GetCancel | Gets the value of the event cancel flag
public method | GetRange | Gets the address of a cell range
public method | GetSheetName | Gets the full name of the worksheet
public method | SetCancel | Sets the value of the event cancel flag

Methods of CXlEventArgs

Requirements

Header: xlpevents.h

See Also

CXlCancellableRangeEventArgs Class | xlpevents.h | Events


CXlCancellableRangeEventArgs::CXlCancellableRangeEventArgs

Constructs a CXlCancellableRangeEventArgs object

CXlCancellableRangeEventArgs(
   const TCHAR* sheetName,
   const TCHAR* range
);

Parameters

sheetName

The name of the worksheet for which the event is being raised.
range

The address of a cell range.

Requirements

Header: xlpevents.h

See Also

CXlCancellableRangeEventArgs Class | CXlCancellableRangeEventArgs Methods


CXlCancellableRangeEventArgs::GetCancel

Gets the value of the event cancel flag

bool GetCancel( ) const;

Return Value

Returns the value of the event cancel flag. If it is true, then the event has been cancelled. If it is false, the event will occur.

Requirements

Header: xlpevents.h

See Also

CXlCancellableRangeEventArgs Class | CXlCancellableRangeEventArgs Methods


CXlCancellableRangeEventArgs::GetRange

Gets the address of a cell range

const CString& GetRange( ) const;

Return Value

Returns a reference to the address of the cells affected by the event.

Requirements

Header: xlpevents.h

See Also

CXlCancellableRangeEventArgs Class | CXlCancellableRangeEventArgs Methods


CXlCancellableRangeEventArgs::GetSheetName

Gets the full name of the worksheet

const CString& GetSheetName( ) const;

Return Value

Returns a reference to the name of the worksheet for which the event is being raised.

Requirements

Header: xlpevents.h

See Also

CXlCancellableRangeEventArgs Class | CXlCancellableRangeEventArgs Methods


CXlCancellableRangeEventArgs::SetCancel

Sets the value of the event cancel flag

void SetCancel(
   bool cancel
);

Parameters

cancel

true to cancel the event. false to let it continue.

Remarks

This method can be used by an event observer to cancel the event being notified.

Requirements

Header: xlpevents.h

See Also

CXlCancellableRangeEventArgs Class | CXlCancellableRangeEventArgs Methods


CXlEvent<T> Class

The template class for event subjects. This class implements the Subject of the observer pattern.

class CXlEvent<T>

Overview

In the observer-based event model, CXlEvent is the base class for all event subjects.

An observer of type CXlEventObserver<T> is added to the set of listeners for an event by calling CXlEvent::Register. It can be removed by calling CXlEvent::Unregister.

When CXlEvent::NotifyObservers(T*) is invoked, the argument of type T* (where T is a class derived from CXlEventArgs) will be passed to the Update(T*) method of each observer.

Deriving a class from CXlEvent<T>

A class derived from CXlEventObserver should implement a concrete constructor. The class may optionally implement CXlEvent::BeforeFirstRegister() and CXlEvent::AfterLastUnregister(), which are called before the first observer is registered, and after the last observer is unregistered, respectively.

Event classes

The table below lists the concrete event classes derived from CXlEvent.

Class | Description
CXllOpenEvent | Occurs when the XLL is opened, after OnXllOpenEx().
CXllCloseEvent | Occurs when the XLL is closed, before OnXllClose().
CXlRegisterFunctionsEvent | Occurs before the XLL's add-in functions are registered.
CXlNewWorkbookEvent | Occurs when a new workbook is created.
CXlSelectionChangeEvent | Occurs when Excel's active cell selection is changed.
CXlBeforeDoubleClickEvent | Occurs when the user double-clicks in a worksheet.
CXlBeforeRightClickEvent | Occurs when the user right-clicks in a worksheet.
CXlSheetActivateEvent | Occurs when a worksheet is activated.
CXlSheetDeactivateEvent | Occurs when a worksheet is deactivated.
CXlCalculateEvent | Occurs just after Excel has finished calculating a worksheet.
CXlSheetChangeEvent | Occurs when a cell is changed in a worksheet.
CXlWorkbookOpenEvent | Occurs when a workbook is opened.
CXlWorkbookActivateEvent | Occurs when a workbook is activated.
CXlWorkbookDeactivateEvent | Occurs when a workbook is deactivated.
CXlWorkbookBeforeCloseEvent | Occurs when a workbook is about to be closed, and allows the event to be cancelled.
CXlWorkbookBeforeSaveEvent | Occurs when a workbook is about to be saved, and allows the event to be cancelled.
CXlWorkbookNewSheetEvent | Occurs when a new worksheet is added to a workbook.

Requirements

Header: xlpevents.h

See Also

CXlEvent<T> Methods | xlpevents.h | Events


CXlEvent<T> Methods

The methods of the CXlEvent<T> class are listed here.

Construction

public method CXlEvent Constructs a CXlEvent object

Registration

public method | Register | Add an observer (listener) to an event
public method | Unregister | Remove a registered observer (listener)

Notification

public method NotifyObservers Notify all observers

State

public method | AfterLastUnregister | Handle change in observed state
public method | BeforeFirstRegister | Handle change in observed state

Requirements

Header: xlpevents.h

See Also

CXlEvent<T> Class | xlpevents.h | Events


CXlEvent<T>::AfterLastUnregister

Handle change in observed state

virtual void AfterLastUnregister( );

Remarks

This method will be called after the last observer is unregistered, i.e. when the state of the event switches from "observed" to "unobserved". The default implementation of this method does nothing.

Requirements

Header: xlpevents.h

See Also

CXlEvent<T> Class | CXlEvent<T> Methods


CXlEvent<T>::BeforeFirstRegister

Handle change in observed state

virtual void BeforeFirstRegister( );

Remarks

This method will be called before the first observer is registered, i.e. when the state of the event switches from "unobserved" to "observed". The default implementation of this method does nothing.

Requirements

Header: xlpevents.h

See Also

CXlEvent<T> Class | CXlEvent<T> Methods


CXlEvent<T>::CXlEvent

Constructs a CXlEvent object

CXlEvent( );

Requirements

Header: xlpevents.h

See Also

CXlEvent<T> Class | CXlEvent<T> Methods


CXlEvent<T>::NotifyObservers

Notify all observers

void NotifyObservers(
   T* e
);

Parameters

e

A pointer to an event of the appropriate type, which will be passed to the CXlEventObserver::Update method of each observer.

Requirements

Header: xlpevents.h

See Also

CXlEvent<T> Class | CXlEvent<T> Methods


CXlEvent<T>::Register

Add an observer (listener) to an event

void Register(
   CXlEventObserver<T>* observer
);

Parameters

observer

A pointer to an observer of events of the appropriate type. The observer will receive updates when CXlEvent::NotifyObservers() is called.

Remarks

Note that the lifetime of the observer is entirely under the observer's control; the event does not "own" the observer, and it does not destroy the observer when the observer is unregistered. It is the responsibility of the developer to ensure that the lifetime of the observer is greater than its period of registration.

Requirements

Header: xlpevents.h

See Also

CXlEvent<T> Class | CXlEvent<T> Methods


CXlEvent<T>::Unregister

Remove a registered observer (listener)

void Unregister(
   CXlEventObserver<T>* observer
);

Parameters

observer

A pointer to an observer of events of the appropriate type, which was previously registered using CXlEvent::Register(). The observer will no longer receive updates when CXlEvent::NotifyObservers() is called.

Remarks

Note that the lifetime of the observer is entirely under the observer's control; the event does not "own" the observer, and it does not destroy the observer when the observer is unregistered. It is the repsonsibility of the developer to ensure that the lifetime of the observer is greater than its period of registration.

Requirements

Header: xlpevents.h

See Also

CXlEvent<T> Class | CXlEvent<T> Methods


CXlEventArgs Class

The base class for the arguments passed with any event.

class CXlEventArgs

Overview

In the observer-based event model, CXlEventArgs is the base class for all event argument classes.

Requirements

Header: xlpevents.h

See Also

CXlEventArgs Methods | xlpevents.h | Events


CXlEventArgs Methods

The methods of the CXlEventArgs class are listed here.

Construction

public method CXlEventArgs Constructs a CXlEventArgs object

Requirements

Header: xlpevents.h

See Also

CXlEventArgs Class | xlpevents.h | Events


CXlEventArgs::CXlEventArgs

Constructs a CXlEventArgs object

CXlEventArgs( );

Requirements

Header: xlpevents.h

See Also

CXlEventArgs Class | CXlEventArgs Methods


CXlEventObserver<T> Class

The template class for event observers. This class implements the Observer of the observer pattern.

class CXlEventObserver<T>

Overview

In the observer-based event model, CXlEventObserver is the base class for all event observers (or listeners). An argument of type T* (where T is a class derived from CXlEventArgs) will be passed to the Update() method.

An observer is added to the set of listeners for an event by calling CXlEvent::Register. It can be removed by calling CXlEvent::Unregister.

Deriving a class from CXlEventObserver<T>

A class derived from CXlEventObserver should implement the abstract virtual function Update(). This method will be called whenever the event which is being observed occurs.

Requirements

Header: xlpevents.h

See Also

CXlEventObserver<T> Methods | xlpevents.h | Events


CXlEventObserver<T> Methods

The methods of the CXlEventObserver<T> class are listed here.

Construction

public method CXlEventObserver Constructs a CXlEventObserver object

Events

public method Update Respond to an event

Requirements

Header: xlpevents.h

See Also

CXlEventObserver<T> Class | xlpevents.h | Events


CXlEventObserver<T>::CXlEventObserver

Constructs a CXlEventObserver object

CXlEventObserver( );

Requirements

Header: xlpevents.h

See Also

CXlEventObserver<T> Class | CXlEventObserver<T> Methods


CXlEventObserver<T>::Update

Respond to an event

virtual void Update(
   T* e
);

Parameters

e

A pointer to an event arguments object of type T is sent to the Update method.

Remarks

Derived classes should implement this function, which is the event handler for the XLL+ event model.

Requirements

Header: xlpevents.h

See Also

CXlEventObserver<T> Class | CXlEventObserver<T> Methods


CXllCloseEvent Class

An event which is raised when the XLL is closed.

class CXllCloseEvent : public CXlEvent

Overview

The event occurs when the XLL is closed, before CXllApp::OnXllClose().

Observers can be registered explicitly at any time during the life of the XLL, or automatically by creating an instance of CXllCloseEventStaticObserver.

Requirements

Header: xlpevents.h

See Also

CXllCloseEvent Methods | xlpevents.h | CXllApp::XllCloseEvent | Events | CXlEventArgs | CXllCloseEventStaticObserver


CXllCloseEvent Methods

The methods of the CXllCloseEvent class are listed here.

Construction

public method CXllCloseEvent Constructs a CXllCloseEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXllCloseEvent Class | xlpevents.h | CXllApp::XllCloseEvent | Events | CXlEventArgs | CXllCloseEventStaticObserver


CXllCloseEvent::CXllCloseEvent

Constructs a CXllCloseEvent object

CXllCloseEvent( );

Requirements

Header: xlpevents.h

See Also

CXllCloseEvent Class | CXllCloseEvent Methods


CXllCloseEventStaticObserver Class

An event observer for XllClose, which is automatically registered and unregistered.

class CXllCloseEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

During the XllClose event, the object's Update method will be called.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXllCloseEventStaticObserver Methods | xlpevents.h | CXllCloseEvent | Events


CXllCloseEventStaticObserver Methods

The methods of the CXllCloseEventStaticObserver class are listed here.

Construction

public method CXllCloseEventStaticObserver Constructs a CXllCloseEventStaticObserver object

Events

public method Update Respond to an event

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXllCloseEventStaticObserver Class | xlpevents.h | CXllCloseEvent | Events


CXllCloseEventStaticObserver::CXllCloseEventStaticObserver

Constructs a CXllCloseEventStaticObserver object

CXllCloseEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXllCloseEventStaticObserver Class | CXllCloseEventStaticObserver Methods


CXllCloseEventStaticObserver::Update

Respond to an event

virtual void Update(
   CXlEventArgs* e
);

Parameters

e

A pointer to an event arguments object is sent to the Update method.

Remarks

Derived classes should implement this function, which is the event handler for the XLL+ event model.

Example

The code below defines a class derived from CXllCloseEventStaticObserver, implements an Update method which is called when the event occurs, and instantiates an instance of the new class.

CopyC++
// Define a class derived from CXllCloseEventStaticObserver
class CMyCloseEventObserver : CXllCloseEventStaticObserver
{
public:
    // This method will be called during the XllClose event.
    virtual void Update(CXlEventArgs* e)
    {
        CXllApp::XlMessageBox(_T("Hello from XllClose"),
            XlMessageBoxTypeInformation);
    }
};

// Create an instance of the class
CMyCloseEventObserver myCloseObserver;

Requirements

Header: xlpevents.h

See Also

CXllCloseEventStaticObserver Class | CXllCloseEventStaticObserver Methods


CXllOpenEvent Class

An event which is raised when the XLL is opened.

class CXllOpenEvent : public CXlEvent

Overview

The event occurs when the XLL is opened, after CXllApp::OnXllOpenEx().

Observers should register for this event early in the life of the XLL. Registration can be done explicitly during CXllApp::InitInstance, or automatically by creating an instance of CXllOpenEventStaticObserver.

When observers are notified, an argument of type CXllOpenEventArgs is passed.

Requirements

Header: xlpevents.h

See Also

CXllOpenEvent Methods | xlpevents.h | CXllApp::XllOpenEvent | Events | CXllOpenEventArgs | CXllOpenEventStaticObserver


CXllOpenEvent Methods

The methods of the CXllOpenEvent class are listed here.

Construction

public method CXllOpenEvent Constructs a CXllOpenEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXllOpenEvent Class | xlpevents.h | CXllApp::XllOpenEvent | Events | CXllOpenEventArgs | CXllOpenEventStaticObserver


CXllOpenEvent::CXllOpenEvent

Constructs a CXllOpenEvent object

CXllOpenEvent( );

Requirements

Header: xlpevents.h

See Also

CXllOpenEvent Class | CXllOpenEvent Methods


CXllOpenEventArgs Class

The event argument class passed by the XllOpen event, which can be used to cancel the event.

class CXllOpenEventArgs : public CXlEventArgs

Overview

This is the event argument used by the following event:

  • CXlOpenEvent

Requirements

Header: xlpevents.h

See Also

CXllOpenEventArgs Methods | xlpevents.h | Events


CXllOpenEventArgs Methods

The methods of the CXllOpenEventArgs class are listed here.

Construction

public method CXllOpenEventArgs Constructs a CXllOpenEventArgs object

Properties

public method | GetCancel | Gets the value of the event cancel flag
public method | SetCancel | Sets the value of the event cancel flag

Methods of CXlEventArgs

Requirements

Header: xlpevents.h

See Also

CXllOpenEventArgs Class | xlpevents.h | Events


CXllOpenEventArgs::CXllOpenEventArgs

Constructs a CXllOpenEventArgs object

CXllOpenEventArgs( );

Requirements

Header: xlpevents.h

See Also

CXllOpenEventArgs Class | CXllOpenEventArgs Methods


CXllOpenEventArgs::GetCancel

Gets the value of the event cancel flag

bool GetCancel( ) const;

Return Value

Returns the value of the event cancel flag. If it is true, then the event has been cancelled. If it is false, the event will occur.

Requirements

Header: xlpevents.h

See Also

CXllOpenEventArgs Class | CXllOpenEventArgs Methods


CXllOpenEventArgs::SetCancel

Sets the value of the event cancel flag

void SetCancel(
   bool cancel
);

Parameters

cancel

true to cancel the event. false to let it continue.

Remarks

This method can be used by an event observer to cancel the event being notified.

Requirements

Header: xlpevents.h

See Also

CXllOpenEventArgs Class | CXllOpenEventArgs Methods


CXllOpenEventStaticObserver Class

An event observer for XllOpen, which is automatically registered and unregistered.

class CXllOpenEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

During the XllOpen event, the object's Update method will be called.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXllOpenEventStaticObserver Methods | xlpevents.h | CXllOpenEvent | Events


CXllOpenEventStaticObserver Methods

The methods of the CXllOpenEventStaticObserver class are listed here.

Construction

public method CXllOpenEventStaticObserver Constructs a CXllOpenEventStaticObserver object

Events

public method Update Respond to an event

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXllOpenEventStaticObserver Class | xlpevents.h | CXllOpenEvent | Events


CXllOpenEventStaticObserver::CXllOpenEventStaticObserver

Constructs a CXllOpenEventStaticObserver object

CXllOpenEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXllOpenEventStaticObserver Class | CXllOpenEventStaticObserver Methods


CXllOpenEventStaticObserver::Update

Respond to an event

virtual void Update(
   CXllOpenEventArgs* e
);

Parameters

e

A pointer to an event arguments object is sent to the Update method.

Remarks

Derived classes should implement this function, which is the event handler for the XLL+ event model.

Example

The code below defines a class derived from CXllOpenEventStaticObserver, implements an Update method which is called when the event occurs, and instantiates an instance of the new class.

Note that this particular Update method uses CXllOpenEventArgs::SetCancel to cancel the open event for the XLL.

CopyC++
// Define a class derived from CXllOpenEventStaticObserver
class CMyOpenEventObserver : CXllOpenEventStaticObserver
{
public:
    // This method will be called during the XllOpen event.
    virtual void Update(CXllOpenEventArgs* e)
    {
        CXllApp::XlMessageBox(
            _T("The event observer will now cancel the XllOpen event"),
            XlMessageBoxTypeInformation);
        e->SetCancel(true);
    }
};

// Create an instance of the class
CMyOpenEventObserver myOpenObserver;

Requirements

Header: xlpevents.h

See Also

CXllOpenEventStaticObserver Class | CXllOpenEventStaticObserver Methods


CXlNewWorkbookEvent Class

An event which is raised when a new workbook is created.

class CXlNewWorkbookEvent : public CXlEvent

Overview

The event occurs when a new workbook is created.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlNewWorkbookEventStaticObserver.

When observers are notified, an argument of type CXlWorkbookEventArgs is passed.

Requirements

Header: xlpevents.h

See Also

CXlNewWorkbookEvent Methods | xlpevents.h | CXllApp::NewWorkbookEvent | Events | CXlWorkbookEventArgs | CXlNewWorkbookEventStaticObserver


CXlNewWorkbookEvent Methods

The methods of the CXlNewWorkbookEvent class are listed here.

Construction

public method CXlNewWorkbookEvent Constructs a CXlNewWorkbookEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlNewWorkbookEvent Class | xlpevents.h | CXllApp::NewWorkbookEvent | Events | CXlWorkbookEventArgs | CXlNewWorkbookEventStaticObserver


CXlNewWorkbookEvent::CXlNewWorkbookEvent

Constructs a CXlNewWorkbookEvent object

CXlNewWorkbookEvent( );

Requirements

Header: xlpevents.h

See Also

CXlNewWorkbookEvent Class | CXlNewWorkbookEvent Methods


CXlNewWorkbookEventStaticObserver Class

An event observer for XlNewWorkbook, which is automatically registered and unregistered.

class CXlNewWorkbookEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

During the XlNewWorkbook event, the object's Update method will be called.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlNewWorkbookEventStaticObserver Methods | xlpevents.h | CXlNewWorkbookEvent | Events


CXlNewWorkbookEventStaticObserver Methods

The methods of the CXlNewWorkbookEventStaticObserver class are listed here.

Construction

public method CXlNewWorkbookEventStaticObserver Constructs a CXlNewWorkbookEventStaticObserver object

Events

public method Update Respond to an event

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlNewWorkbookEventStaticObserver Class | xlpevents.h | CXlNewWorkbookEvent | Events


CXlNewWorkbookEventStaticObserver::CXlNewWorkbookEventStaticObserver

Constructs a CXlNewWorkbookEventStaticObserver object

CXlNewWorkbookEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlNewWorkbookEventStaticObserver Class | CXlNewWorkbookEventStaticObserver Methods


CXlNewWorkbookEventStaticObserver::Update

Respond to an event

virtual void Update(
   CXlWorkbookEventArgs* e
);

Parameters

e

A pointer to an event arguments object is sent to the Update method.

Remarks

Derived classes should implement this function, which is the event handler for the XLL+ event model.

Example

The code below defines a class derived from CXlNewWorkbookEventStaticObserver, implements an Update method which is called when the event occurs, and instantiates an instance of the new class.

CopyC++
// Define a class derived from CXlNewWorkbookEventStaticObserver
class CMyNewWorkbookEventObserver : CXlNewWorkbookEventStaticObserver
{
public:
    // This method will be called during the XlNewWorkbook event.
    virtual void Update(CXlWorkbookEventArgs* e)
    {
        CXllApp::XlMessageBox(_T("Creating ") + e->GetBookName(),
            XlMessageBoxTypeInformation);
    }
};

// Create an instance of the class
CMyNewWorkbookEventObserver myNewWorkbookObserver;

Requirements

Header: xlpevents.h

See Also

CXlNewWorkbookEventStaticObserver Class | CXlNewWorkbookEventStaticObserver Methods


CXlRangeEventArgs Class

An event argument class containing a complete worksheet name and the name of the cell range affected.

class CXlRangeEventArgs : public CXlEventArgs

Overview

This is the event argument used by the following events:

  • CXlSelectionChangeEvent
  • CXlSheetChangeEvent

Requirements

Header: xlpevents.h

See Also

CXlRangeEventArgs Methods | xlpevents.h | Events


CXlRangeEventArgs Methods

The methods of the CXlRangeEventArgs class are listed here.

Construction

public method CXlRangeEventArgs Constructs a CXlRangeEventArgs object

Properties

public method | GetRange | Gets the address of a cell range
public method | GetSheetName | Gets the full name of the worksheet

Methods of CXlEventArgs

Requirements

Header: xlpevents.h

See Also

CXlRangeEventArgs Class | xlpevents.h | Events


CXlRangeEventArgs::CXlRangeEventArgs

Constructs a CXlRangeEventArgs object

CXlRangeEventArgs(
   const TCHAR* sheetName,
   const TCHAR* range
);

Parameters

sheetName

The name of the worksheet for which the event is being raised.
range

The address of a cell range.

Requirements

Header: xlpevents.h

See Also

CXlRangeEventArgs Class | CXlRangeEventArgs Methods


CXlRangeEventArgs::GetRange

Gets the address of a cell range

const CString& GetRange( ) const;

Return Value

Returns a reference to the address of the cells affected by the event.

Requirements

Header: xlpevents.h

See Also

CXlRangeEventArgs Class | CXlRangeEventArgs Methods


CXlRangeEventArgs::GetSheetName

Gets the full name of the worksheet

const CString& GetSheetName( ) const;

Return Value

Returns a reference to the name of the worksheet for which the event is being raised.

Requirements

Header: xlpevents.h

See Also

CXlRangeEventArgs Class | CXlRangeEventArgs Methods


CXlRegisterFunctionsEvent Class

An event which is raised just before the XLL's add-in functions are registered.

class CXlRegisterFunctionsEvent : public CXlEvent

Overview

The event occurs just before the XLL's add-in functions are registered. This usually occurs when the XLL is opened, after the CXllOpenEvent.

Observers should register for this event early in the life of the XLL. Registration can be done explicitly during CXllApp::InitInstance, or automatically by creating an instance of CXlRegisterFunctionsEventStaticObserver.

Requirements

Header: xlpevents.h

See Also

CXlRegisterFunctionsEvent Methods | xlpevents.h | CXllApp::RegisterFunctionsEvent | Events | CXlEventArgs | CXlRegisterFunctionsEventStaticObserver


CXlRegisterFunctionsEvent Methods

The methods of the CXlRegisterFunctionsEvent class are listed here.

Construction

public method CXlRegisterFunctionsEvent Constructs a CXlRegisterFunctionsEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlRegisterFunctionsEvent Class | xlpevents.h | CXllApp::RegisterFunctionsEvent | Events | CXlEventArgs | CXlRegisterFunctionsEventStaticObserver


CXlRegisterFunctionsEvent::CXlRegisterFunctionsEvent

Constructs a CXlRegisterFunctionsEvent object

CXlRegisterFunctionsEvent( );

Requirements

Header: xlpevents.h

See Also

CXlRegisterFunctionsEvent Class | CXlRegisterFunctionsEvent Methods


CXlRegisterFunctionsEventStaticObserver Class

An event observer for XlRegisterFunctions, which is automatically registered and unregistered.

class CXlRegisterFunctionsEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

During the XlRegisterFunctions event, the object's Update method will be called.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlRegisterFunctionsEventStaticObserver Methods | xlpevents.h | CXlRegisterFunctionsEvent | Events


CXlRegisterFunctionsEventStaticObserver Methods

The methods of the CXlRegisterFunctionsEventStaticObserver class are listed here.

Construction

public method CXlRegisterFunctionsEventStaticObserver Constructs a CXlRegisterFunctionsEventStaticObserver object

Events

public method Update Respond to an event

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlRegisterFunctionsEventStaticObserver Class | xlpevents.h | CXlRegisterFunctionsEvent | Events


CXlRegisterFunctionsEventStaticObserver::CXlRegisterFunctionsEventStaticObserver

Constructs a CXlRegisterFunctionsEventStaticObserver object

CXlRegisterFunctionsEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlRegisterFunctionsEventStaticObserver Class | CXlRegisterFunctionsEventStaticObserver Methods


CXlRegisterFunctionsEventStaticObserver::Update

Respond to an event

virtual void Update(
   CXlEventArgs* e
);

Parameters

e

A pointer to an event arguments object is sent to the Update method.

Remarks

Derived classes should implement this function, which is the event handler for the XLL+ event model.

Example

The code below defines a class derived from CXlRegisterFunctionsEventStaticObserver, implements an Update method which is called when the event occurs, and instantiates an instance of the new class.

CopyC++
// Define a class derived from CXlRegisterFunctionsEventStaticObserver
class CMyRegisterFunctionsEventObserver : CXlRegisterFunctionsEventStaticObserver
{
public:
    // This method will be called during the XlRegisterFunctions event.
    virtual void Update(CXlEventArgs* e)
    {
        CXllApp::XlMessageBox(_T("About to register functions"),
            XlMessageBoxTypeInformation);
    }
};

// Create an instance of the class
CMyRegisterFunctionsEventObserver myObserver;

Requirements

Header: xlpevents.h

See Also

CXlRegisterFunctionsEventStaticObserver Class | CXlRegisterFunctionsEventStaticObserver Methods


CXlSelectionChangeEvent Class

An event which is raised when Excel's selection in a sheet is changed.

class CXlSelectionChangeEvent : public CXlEvent

Overview

The event occurs when Excel's active cell selection is changed.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlSelectionChangeEventStaticObserver.

When observers are notified, an argument of type CXlRangeEventArgs is passed.

Requirements

Header: xlpevents.h

See Also

CXlSelectionChangeEvent Methods | xlpevents.h | CXllApp::SelectionChangeEvent | Events | CXlRangeEventArgs | CXlSelectionChangeEventStaticObserver


CXlSelectionChangeEvent Methods

The methods of the CXlSelectionChangeEvent class are listed here.

Construction

public method CXlSelectionChangeEvent Constructs a CXlSelectionChangeEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlSelectionChangeEvent Class | xlpevents.h | CXllApp::SelectionChangeEvent | Events | CXlRangeEventArgs | CXlSelectionChangeEventStaticObserver


CXlSelectionChangeEvent::CXlSelectionChangeEvent

Constructs a CXlSelectionChangeEvent object

CXlSelectionChangeEvent( );

Requirements

Header: xlpevents.h

See Also

CXlSelectionChangeEvent Class | CXlSelectionChangeEvent Methods


CXlSelectionChangeEventStaticObserver Class

An event observer for XlSelectionChange, which is automatically registered and unregistered.

class CXlSelectionChangeEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

During the XlSelectionChange event, the object's Update method will be called.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlSelectionChangeEventStaticObserver Methods | xlpevents.h | CXlSelectionChangeEvent | Events


CXlSelectionChangeEventStaticObserver Methods

The methods of the CXlSelectionChangeEventStaticObserver class are listed here.

Construction

public method CXlSelectionChangeEventStaticObserver Constructs a CXlSelectionChangeEventStaticObserver object

Events

public method Update Respond to an event

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlSelectionChangeEventStaticObserver Class | xlpevents.h | CXlSelectionChangeEvent | Events


CXlSelectionChangeEventStaticObserver::CXlSelectionChangeEventStaticObserver

Constructs a CXlSelectionChangeEventStaticObserver object

CXlSelectionChangeEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlSelectionChangeEventStaticObserver Class | CXlSelectionChangeEventStaticObserver Methods


CXlSelectionChangeEventStaticObserver::Update

Respond to an event

virtual void Update(
   CXlRangeEventArgs* e
);

Parameters

e

A pointer to an event arguments object is sent to the Update method.

Remarks

Derived classes should implement this function, which is the event handler for the XLL+ event model.

Example

The code below defines a class derived from CXlSelectionChangeEventStaticObserver, implements an Update method which is called when the event occurs, and instantiates an instance of the new class.

CopyC++
// Define a class derived from CXlSelectionChangeEventStaticObserver
class CMySelectionChangeEventObserver : CXlSelectionChangeEventStaticObserver
{
public:
    // This method will be called during the XlSelectionChange event.
    virtual void Update(CXlRangeEventArgs* e)
    {
        CXllApp::XlMessageBox(_T("Selection changed to ") + e->GetRange(),
            XlMessageBoxTypeInformation);
    }
};

// Create an instance of the class
CMySelectionChangeEventObserver mySelectionChangeObserver;

Requirements

Header: xlpevents.h

See Also

CXlSelectionChangeEventStaticObserver Class | CXlSelectionChangeEventStaticObserver Methods


CXlSheetActivateEvent Class

An event which is raised when a worksheet is activated.

class CXlSheetActivateEvent : public CXlEvent

Overview

The event occurs when a worksheet is activated.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlSheetActivateEventStaticObserver.

When observers are notified, an argument of type CXlWorksheetEventArgs is passed.

Requirements

Header: xlpevents.h

See Also

CXlSheetActivateEvent Methods | xlpevents.h | CXllApp::SheetActivateEvent | Events | CXlWorksheetEventArgs | CXlSheetActivateEventStaticObserver


CXlSheetActivateEvent Methods

The methods of the CXlSheetActivateEvent class are listed here.

Construction

public method CXlSheetActivateEvent Constructs a CXlSheetActivateEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlSheetActivateEvent Class | xlpevents.h | CXllApp::SheetActivateEvent | Events | CXlWorksheetEventArgs | CXlSheetActivateEventStaticObserver


CXlSheetActivateEvent::CXlSheetActivateEvent

Constructs a CXlSheetActivateEvent object

CXlSheetActivateEvent( );

Requirements

Header: xlpevents.h

See Also

CXlSheetActivateEvent Class | CXlSheetActivateEvent Methods


CXlSheetActivateEventStaticObserver Class

An event observer for XlSheetActivate, which is automatically registered and unregistered.

class CXlSheetActivateEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

Requirements

Header: xlpevents.h

See Also

CXlSheetActivateEventStaticObserver Methods | xlpevents.h | CXlSheetActivateEvent | Events


CXlSheetActivateEventStaticObserver Methods

The methods of the CXlSheetActivateEventStaticObserver class are listed here.

Construction

public method CXlSheetActivateEventStaticObserver Constructs a CXlSheetActivateEventStaticObserver object

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlSheetActivateEventStaticObserver Class | xlpevents.h | CXlSheetActivateEvent | Events


CXlSheetActivateEventStaticObserver::CXlSheetActivateEventStaticObserver

Constructs a CXlSheetActivateEventStaticObserver object

CXlSheetActivateEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

Requirements

Header: xlpevents.h

See Also

CXlSheetActivateEventStaticObserver Class | CXlSheetActivateEventStaticObserver Methods


CXlSheetChangeEvent Class

An event which is raised when a cell is changed in a worksheet.

class CXlSheetChangeEvent : public CXlEvent

Overview

The event occurs when a cell is changed in a worksheet.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlSheetChangeEventStaticObserver.

When observers are notified, an argument of type CXlRangeEventArgs is passed.

Requirements

Header: xlpevents.h

See Also

CXlSheetChangeEvent Methods | xlpevents.h | CXllApp::SheetChangeEvent | Events | CXlRangeEventArgs | CXlSheetChangeEventStaticObserver


CXlSheetChangeEvent Methods

The methods of the CXlSheetChangeEvent class are listed here.

Construction

public method CXlSheetChangeEvent Constructs a CXlSheetChangeEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlSheetChangeEvent Class | xlpevents.h | CXllApp::SheetChangeEvent | Events | CXlRangeEventArgs | CXlSheetChangeEventStaticObserver


CXlSheetChangeEvent::CXlSheetChangeEvent

Constructs a CXlSheetChangeEvent object

CXlSheetChangeEvent( );

Requirements

Header: xlpevents.h

See Also

CXlSheetChangeEvent Class | CXlSheetChangeEvent Methods


CXlSheetChangeEventStaticObserver Class

An event observer for XlSheetChange, which is automatically registered and unregistered.

class CXlSheetChangeEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

Requirements

Header: xlpevents.h

See Also

CXlSheetChangeEventStaticObserver Methods | xlpevents.h | CXlSheetChangeEvent | Events


CXlSheetChangeEventStaticObserver Methods

The methods of the CXlSheetChangeEventStaticObserver class are listed here.

Construction

public method CXlSheetChangeEventStaticObserver Constructs a CXlSheetChangeEventStaticObserver object

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlSheetChangeEventStaticObserver Class | xlpevents.h | CXlSheetChangeEvent | Events


CXlSheetChangeEventStaticObserver::CXlSheetChangeEventStaticObserver

Constructs a CXlSheetChangeEventStaticObserver object

CXlSheetChangeEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

Requirements

Header: xlpevents.h

See Also

CXlSheetChangeEventStaticObserver Class | CXlSheetChangeEventStaticObserver Methods


CXlSheetDeactivateEvent Class

An event which is raised when a worksheet is deactivated.

class CXlSheetDeactivateEvent : public CXlEvent

Overview

The event occurs when a worksheet is deactivated.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlSheetDeactivateEventStaticObserver.

When observers are notified, an argument of type CXlWorksheetEventArgs is passed.

Requirements

Header: xlpevents.h

See Also

CXlSheetDeactivateEvent Methods | xlpevents.h | CXllApp::SheetDeactivateEvent | Events | CXlWorksheetEventArgs | CXlSheetDeactivateEventStaticObserver


CXlSheetDeactivateEvent Methods

The methods of the CXlSheetDeactivateEvent class are listed here.

Construction

public method CXlSheetDeactivateEvent Constructs a CXlSheetDeactivateEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlSheetDeactivateEvent Class | xlpevents.h | CXllApp::SheetDeactivateEvent | Events | CXlWorksheetEventArgs | CXlSheetDeactivateEventStaticObserver


CXlSheetDeactivateEvent::CXlSheetDeactivateEvent

Constructs a CXlSheetDeactivateEvent object

CXlSheetDeactivateEvent( );

Requirements

Header: xlpevents.h

See Also

CXlSheetDeactivateEvent Class | CXlSheetDeactivateEvent Methods


CXlSheetDeactivateEventStaticObserver Class

An event observer for XlSheetDeactivate, which is automatically registered and unregistered.

class CXlSheetDeactivateEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

Requirements

Header: xlpevents.h

See Also

CXlSheetDeactivateEventStaticObserver Methods | xlpevents.h | CXlSheetDeactivateEvent | Events


CXlSheetDeactivateEventStaticObserver Methods

The methods of the CXlSheetDeactivateEventStaticObserver class are listed here.

Construction

public method CXlSheetDeactivateEventStaticObserver Constructs a CXlSheetDeactivateEventStaticObserver object

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlSheetDeactivateEventStaticObserver Class | xlpevents.h | CXlSheetDeactivateEvent | Events


CXlSheetDeactivateEventStaticObserver::CXlSheetDeactivateEventStaticObserver

Constructs a CXlSheetDeactivateEventStaticObserver object

CXlSheetDeactivateEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

Requirements

Header: xlpevents.h

See Also

CXlSheetDeactivateEventStaticObserver Class | CXlSheetDeactivateEventStaticObserver Methods


CXlStaticEventObserver<T> Class

A helper class for event observers, which ensures safe and timely registration.

class CXlStaticEventObserver<T> : public CXlEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. The CXlStaticEventObserver<T> class can be used to safely automatically register and unregister itself.

Derived classes

The following classes are concrete implementations of CXlStaticEventObserver<T>:

  • CXllOpenEventStaticObserver
  • CXllCloseEventStaticObserver
  • CXlRegisterFunctionsEventStaticObserver
  • CXlNewWorkbookEventStaticObserver
  • CXlSelectionChangeEventStaticObserver
  • CXlBeforeDoubleClickEventStaticObserver
  • CXlBeforeRightClickEventStaticObserver
  • CXlSheetActivateEventStaticObserver
  • CXlSheetDeactivateEventStaticObserver
  • CXlCalculateEventStaticObserver
  • CXlSheetChangeEventStaticObserver
  • CXlWorkbookOpenEventStaticObserver
  • CXlWorkbookActivateEventStaticObserver
  • CXlWorkbookDeactivateEventStaticObserver
  • CXlWorkbookBeforeCloseEventStaticObserver
  • CXlWorkbookBeforeSaveEventStaticObserver

Requirements

Header: xlpevents.h

See Also

CXlStaticEventObserver<T> Methods | xlpevents.h | Events


CXlStaticEventObserver<T> Methods

The methods of the CXlStaticEventObserver<T> class are listed here.

Construction

public method CXlStaticEventObserver Constructs a CXlStaticEventObserver object

Methods of CXlEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlStaticEventObserver<T> Class | xlpevents.h | Events


CXlStaticEventObserver<T>::CXlStaticEventObserver

Constructs a CXlStaticEventObserver object

CXlStaticEventObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

Requirements

Header: xlpevents.h

See Also

CXlStaticEventObserver<T> Class | CXlStaticEventObserver<T> Methods


CXlWorkbookActivateEvent Class

An event which is raised when a workbook is activated.

class CXlWorkbookActivateEvent : public CXlEvent

Overview

The event occurs when a workbook is activated.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookActivateEventStaticObserver.

When observers are notified, an argument of type CXlWorkbookEventArgs is passed.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookActivateEvent Methods | xlpevents.h | CXllApp::WorkbookActivateEvent | Events | CXlWorkbookEventArgs | CXlWorkbookActivateEventStaticObserver


CXlWorkbookActivateEvent Methods

The methods of the CXlWorkbookActivateEvent class are listed here.

Construction

public method CXlWorkbookActivateEvent Constructs a CXlWorkbookActivateEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookActivateEvent Class | xlpevents.h | CXllApp::WorkbookActivateEvent | Events | CXlWorkbookEventArgs | CXlWorkbookActivateEventStaticObserver


CXlWorkbookActivateEvent::CXlWorkbookActivateEvent

Constructs a CXlWorkbookActivateEvent object

CXlWorkbookActivateEvent( );

Requirements

Header: xlpevents.h

See Also

CXlWorkbookActivateEvent Class | CXlWorkbookActivateEvent Methods


CXlWorkbookActivateEventStaticObserver Class

An event observer for XlWorkbookActivate, which is automatically registered and unregistered.

class CXlWorkbookActivateEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookActivateEventStaticObserver Methods | xlpevents.h | CXlWorkbookActivateEvent | Events


CXlWorkbookActivateEventStaticObserver Methods

The methods of the CXlWorkbookActivateEventStaticObserver class are listed here.

Construction

public method CXlWorkbookActivateEventStaticObserver Constructs a CXlWorkbookActivateEventStaticObserver object

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookActivateEventStaticObserver Class | xlpevents.h | CXlWorkbookActivateEvent | Events


CXlWorkbookActivateEventStaticObserver::CXlWorkbookActivateEventStaticObserver

Constructs a CXlWorkbookActivateEventStaticObserver object

CXlWorkbookActivateEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookActivateEventStaticObserver Class | CXlWorkbookActivateEventStaticObserver Methods


CXlWorkbookAfterSaveEvent Class

An event which is raised after a workbook save operation is complete, and supplies the name of the workbook as saved and a flag indicating whether the save operation was successful.

class CXlWorkbookAfterSaveEvent : public CXlEvent

Overview

The event occurs when a workbook is about to be saved, and allows the event to be cancelled.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookAfterSaveEventStaticObserver.

When observers are notified, an argument of type CXlAfterSaveEventArgs is passed. The argument contains a Success field, which indicates whether the save operation was completed successfully, and which can be retrieved using CXlAfterSaveEventArgs::GetSuccess().

Availability

Note that this event is only available when running under Excel 2010 (Excel 14) or above.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookAfterSaveEvent Methods | xlpevents.h | CXllApp::WorkbookAfterSaveEvent | Events | CXlAfterSaveEventArgs | CXlWorkbookAfterSaveEventStaticObserver


CXlWorkbookAfterSaveEvent Methods

The methods of the CXlWorkbookAfterSaveEvent class are listed here.

Construction

public method CXlWorkbookAfterSaveEvent Constructs a CXlWorkbookAfterSaveEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookAfterSaveEvent Class | xlpevents.h | CXllApp::WorkbookAfterSaveEvent | Events | CXlAfterSaveEventArgs | CXlWorkbookAfterSaveEventStaticObserver


CXlWorkbookAfterSaveEvent::CXlWorkbookAfterSaveEvent

Constructs a CXlWorkbookAfterSaveEvent object

CXlWorkbookAfterSaveEvent( );

Requirements

Header: xlpevents.h

See Also

CXlWorkbookAfterSaveEvent Class | CXlWorkbookAfterSaveEvent Methods


CXlWorkbookAfterSaveEventStaticObserver Class

An event observer for XlWorkbookAfterSave, which is automatically registered and unregistered.

class CXlWorkbookAfterSaveEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

During the XlWorkbookAfterSave event, after the book is saved, the object's Update method will be called.

See the Update method for an example of this class in use.

Availability

Note that this event is only available when running under Excel 2010 (Excel 14) or above.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookAfterSaveEventStaticObserver Methods | xlpevents.h | CXlWorkbookAfterSaveEvent | Events


CXlWorkbookAfterSaveEventStaticObserver Methods

The methods of the CXlWorkbookAfterSaveEventStaticObserver class are listed here.

Construction

public method CXlWorkbookAfterSaveEventStaticObserver Constructs a CXlWorkbookAfterSaveEventStaticObserver object

Events

public method Update Respond to an event

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookAfterSaveEventStaticObserver Class | xlpevents.h | CXlWorkbookAfterSaveEvent | Events


CXlWorkbookAfterSaveEventStaticObserver::CXlWorkbookAfterSaveEventStaticObserver

Constructs a CXlWorkbookAfterSaveEventStaticObserver object

CXlWorkbookAfterSaveEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

See the Update method for an example of this class in use.

Availability

Note that this event is only available when running under Excel 2010 (Excel 14) or above.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookAfterSaveEventStaticObserver Class | CXlWorkbookAfterSaveEventStaticObserver Methods


CXlWorkbookAfterSaveEventStaticObserver::Update

Respond to an event

virtual void Update(
   CXlAfterSaveEventArgs* e
);

Parameters

e

A pointer to an event arguments object is sent to the Update method.

Remarks

Derived classes should implement this function, which is the event handler for the XLL+ event model.

Availability

Note that this event is only available when running under Excel 2010 (Excel 14) or above.

Example

The code below defines a class derived from CXlWorkbookAfterSaveEventStaticObserver, implements an Update method which is called when the event occurs, and instantiates an instance of the new class.

CopyC++
// Define a class derived from CXlWorkbookAfterSaveEventStaticObserver
class CMyWorkbookSaveEventObserver : CXlWorkbookAfterSaveEventStaticObserver
{
public:
    // This method will be called during the XlWorkbookAfterSave event.
    virtual void Update(CXlAfterSaveEventArgs* e)
    {
        CXllApp::XlMessageBox(_T("Saved ") + e->GetBookName(),
            XlMessageBoxTypeInformation);
    }
};

// Create an instance of the class
CMyWorkbookSaveEventObserver myWorkbookSaveObserver;

Requirements

Header: xlpevents.h

See Also

CXlWorkbookAfterSaveEventStaticObserver Class | CXlWorkbookAfterSaveEventStaticObserver Methods


CXlWorkbookBeforeCloseEvent Class

An event which is raised when a workbook is about to be closed, and allows the event to be cancelled.

class CXlWorkbookBeforeCloseEvent : public CXlEvent

Overview

The event occurs when a workbook is about to be closed, and allows the event to be cancelled.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookBeforeCloseEventStaticObserver.

When observers are notified, an argument of type CXlBeforeCloseEventArgs is passed. Observers can cancel normal processing of the double-click by cancelling the event using CXlBeforeCloseEventArgs::SetCancel(false).

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeCloseEvent Methods | xlpevents.h | CXllApp::WorkbookBeforeCloseEvent | Events | CXlBeforeCloseEventArgs | CXlWorkbookBeforeCloseEventStaticObserver


CXlWorkbookBeforeCloseEvent Methods

The methods of the CXlWorkbookBeforeCloseEvent class are listed here.

Construction

public method CXlWorkbookBeforeCloseEvent Constructs a CXlWorkbookBeforeCloseEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeCloseEvent Class | xlpevents.h | CXllApp::WorkbookBeforeCloseEvent | Events | CXlBeforeCloseEventArgs | CXlWorkbookBeforeCloseEventStaticObserver


CXlWorkbookBeforeCloseEvent::CXlWorkbookBeforeCloseEvent

Constructs a CXlWorkbookBeforeCloseEvent object

CXlWorkbookBeforeCloseEvent( );

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeCloseEvent Class | CXlWorkbookBeforeCloseEvent Methods


CXlWorkbookBeforeCloseEventStaticObserver Class

An event observer for XlWorkbookBeforeClose, which is automatically registered and unregistered.

class CXlWorkbookBeforeCloseEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

During the XlWorkbookBeforeClose event, before the book is closed, the object's Update method will be called.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeCloseEventStaticObserver Methods | xlpevents.h | CXlWorkbookBeforeCloseEvent | Events


CXlWorkbookBeforeCloseEventStaticObserver Methods

The methods of the CXlWorkbookBeforeCloseEventStaticObserver class are listed here.

Construction

public method CXlWorkbookBeforeCloseEventStaticObserver Constructs a CXlWorkbookBeforeCloseEventStaticObserver object

Events

public method Update Respond to an event

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeCloseEventStaticObserver Class | xlpevents.h | CXlWorkbookBeforeCloseEvent | Events


CXlWorkbookBeforeCloseEventStaticObserver::CXlWorkbookBeforeCloseEventStaticObserver

Constructs a CXlWorkbookBeforeCloseEventStaticObserver object

CXlWorkbookBeforeCloseEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeCloseEventStaticObserver Class | CXlWorkbookBeforeCloseEventStaticObserver Methods


CXlWorkbookBeforeCloseEventStaticObserver::Update

Respond to an event

virtual void Update(
   CXlBeforeCloseEventArgs* e
);

Parameters

e

A pointer to an event arguments object is sent to the Update method.

Remarks

Derived classes should implement this function, which is the event handler for the XLL+ event model.

Example

The code below defines a class derived from CXlWorkbookBeforeCloseEventStaticObserver, implements an Update method which is called when the event occurs, and instantiates an instance of the new class.

Note that this particular Update method uses CXlBeforeCloseEventArgs::SetCancel to cancel the event, and prevent the workbook from being closed.

CopyC++
// Define a class derived from CXlWorkbookBeforeCloseEventStaticObserver
class CMyWorkbookCloseEventObserver : CXlWorkbookBeforeCloseEventStaticObserver
{
public:
    // This method will be called during the XlWorkbookBeforeClose event.
    virtual void Update(CXlBeforeCloseEventArgs* e)
    {
        CXllApp::XlMessageBox(_T("Closing ") + e->GetBookName(),
            XlMessageBoxTypeInformation);
        e->SetCancel(true);
    }
};

// Create an instance of the class
CMyWorkbookCloseEventObserver myWorkbookCloseObserver;

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeCloseEventStaticObserver Class | CXlWorkbookBeforeCloseEventStaticObserver Methods


CXlWorkbookBeforeSaveEvent Class

An event which is raised when a workbook is about to be saved, and allows the event to be cancelled.

class CXlWorkbookBeforeSaveEvent : public CXlEvent

Overview

The event occurs when a workbook is about to be saved, and allows the event to be cancelled.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookBeforeSaveEventStaticObserver.

When observers are notified, an argument of type CXlBeforeSaveEventArgs is passed. Observers can cancel normal processing of the double-click by cancelling the event using CXlBeforeSaveEventArgs::SetCancel(false).

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeSaveEvent Methods | xlpevents.h | CXllApp::WorkbookBeforeSaveEvent | Events | CXlBeforeSaveEventArgs | CXlWorkbookBeforeSaveEventStaticObserver


CXlWorkbookBeforeSaveEvent Methods

The methods of the CXlWorkbookBeforeSaveEvent class are listed here.

Construction

public method CXlWorkbookBeforeSaveEvent Constructs a CXlWorkbookBeforeSaveEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeSaveEvent Class | xlpevents.h | CXllApp::WorkbookBeforeSaveEvent | Events | CXlBeforeSaveEventArgs | CXlWorkbookBeforeSaveEventStaticObserver


CXlWorkbookBeforeSaveEvent::CXlWorkbookBeforeSaveEvent

Constructs a CXlWorkbookBeforeSaveEvent object

CXlWorkbookBeforeSaveEvent( );

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeSaveEvent Class | CXlWorkbookBeforeSaveEvent Methods


CXlWorkbookBeforeSaveEventStaticObserver Class

An event observer for XlWorkbookBeforeSave, which is automatically registered and unregistered.

class CXlWorkbookBeforeSaveEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

During the XlWorkbookBeforeSave event, before the book is saved, the object's Update method will be called.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeSaveEventStaticObserver Methods | xlpevents.h | CXlWorkbookBeforeSaveEvent | Events


CXlWorkbookBeforeSaveEventStaticObserver Methods

The methods of the CXlWorkbookBeforeSaveEventStaticObserver class are listed here.

Construction

public method CXlWorkbookBeforeSaveEventStaticObserver Constructs a CXlWorkbookBeforeSaveEventStaticObserver object

Events

public method Update Respond to an event

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeSaveEventStaticObserver Class | xlpevents.h | CXlWorkbookBeforeSaveEvent | Events


CXlWorkbookBeforeSaveEventStaticObserver::CXlWorkbookBeforeSaveEventStaticObserver

Constructs a CXlWorkbookBeforeSaveEventStaticObserver object

CXlWorkbookBeforeSaveEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeSaveEventStaticObserver Class | CXlWorkbookBeforeSaveEventStaticObserver Methods


CXlWorkbookBeforeSaveEventStaticObserver::Update

Respond to an event

virtual void Update(
   CXlBeforeSaveEventArgs* e
);

Parameters

e

A pointer to an event arguments object is sent to the Update method.

Remarks

Derived classes should implement this function, which is the event handler for the XLL+ event model.

Example

The code below defines a class derived from CXlWorkbookBeforeSaveEventStaticObserver, implements an Update method which is called when the event occurs, and instantiates an instance of the new class.

Note that this particular Update method uses CXlBeforeSaveEventArgs::SetCancel to cancel the event, and prevent the workbook from being saved, unless it is being saved under a new name, using the Save As user interface.

CopyC++
// Define a class derived from CXlWorkbookBeforeSaveEventStaticObserver
class CMyWorkbookSaveEventObserver : CXlWorkbookBeforeSaveEventStaticObserver
{
public:
    // This method will be called during the XlWorkbookBeforeSave event.
    virtual void Update(CXlBeforeSaveEventArgs* e)
    {
        CXllApp::XlMessageBox(_T("Saving ") + e->GetBookName(),
            XlMessageBoxTypeInformation);
        if (!e->GetSaveAsUI())
            e->SetCancel(true);
    }
};

// Create an instance of the class
CMyWorkbookSaveEventObserver myWorkbookSaveObserver;

Requirements

Header: xlpevents.h

See Also

CXlWorkbookBeforeSaveEventStaticObserver Class | CXlWorkbookBeforeSaveEventStaticObserver Methods


CXlWorkbookDeactivateEvent Class

An event which is raised when a workbook is deactivated.

class CXlWorkbookDeactivateEvent : public CXlEvent

Overview

The event occurs when a workbook is deactivated.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookDeactivateEventStaticObserver.

When observers are notified, an argument of type CXlWorkbookEventArgs is passed.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookDeactivateEvent Methods | xlpevents.h | CXllApp::WorkbookDeactivateEvent | Events | CXlWorkbookEventArgs | CXlWorkbookDeactivateEventStaticObserver


CXlWorkbookDeactivateEvent Methods

The methods of the CXlWorkbookDeactivateEvent class are listed here.

Construction

public method CXlWorkbookDeactivateEvent Constructs a CXlWorkbookDeactivateEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookDeactivateEvent Class | xlpevents.h | CXllApp::WorkbookDeactivateEvent | Events | CXlWorkbookEventArgs | CXlWorkbookDeactivateEventStaticObserver


CXlWorkbookDeactivateEvent::CXlWorkbookDeactivateEvent

Constructs a CXlWorkbookDeactivateEvent object

CXlWorkbookDeactivateEvent( );

Requirements

Header: xlpevents.h

See Also

CXlWorkbookDeactivateEvent Class | CXlWorkbookDeactivateEvent Methods


CXlWorkbookDeactivateEventStaticObserver Class

An event observer for XlWorkbookDeactivate, which is automatically registered and unregistered.

class CXlWorkbookDeactivateEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookDeactivateEventStaticObserver Methods | xlpevents.h | CXlWorkbookDeactivateEvent | Events


CXlWorkbookDeactivateEventStaticObserver Methods

The methods of the CXlWorkbookDeactivateEventStaticObserver class are listed here.

Construction

public method CXlWorkbookDeactivateEventStaticObserver Constructs a CXlWorkbookDeactivateEventStaticObserver object

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookDeactivateEventStaticObserver Class | xlpevents.h | CXlWorkbookDeactivateEvent | Events


CXlWorkbookDeactivateEventStaticObserver::CXlWorkbookDeactivateEventStaticObserver

Constructs a CXlWorkbookDeactivateEventStaticObserver object

CXlWorkbookDeactivateEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookDeactivateEventStaticObserver Class | CXlWorkbookDeactivateEventStaticObserver Methods


CXlWorkbookEventArgs Class

An event argument class containing only a workbook name.

class CXlWorkbookEventArgs : public CXlEventArgs

Overview

This is the event argument used by the following workbook events:

  • CXlNewWorkbookEvent
  • CXlWorkbookOpenEvent
  • CXlWorkbookActivateEvent
  • CXlWorkbookDeactivateEvent

Requirements

Header: xlpevents.h

See Also

CXlWorkbookEventArgs Methods | xlpevents.h | Events


CXlWorkbookEventArgs Methods

The methods of the CXlWorkbookEventArgs class are listed here.

Construction

public method CXlWorkbookEventArgs Constructs a CXlWorkbookEventArgs object

Properties

public method GetBookName Gets the name of the workbook

Methods of CXlEventArgs

Requirements

Header: xlpevents.h

See Also

CXlWorkbookEventArgs Class | xlpevents.h | Events


CXlWorkbookEventArgs::CXlWorkbookEventArgs

Constructs a CXlWorkbookEventArgs object

CXlWorkbookEventArgs(
   const TCHAR* bookName
);

Parameters

bookName

The name of the workbook for which the event is being raised.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookEventArgs Class | CXlWorkbookEventArgs Methods


CXlWorkbookEventArgs::GetBookName

Gets the name of the workbook

const CString& GetBookName( ) const;

Return Value

Returns a reference to the name of the workbook for which the event is being raised.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookEventArgs Class | CXlWorkbookEventArgs Methods


CXlWorkbookNewSheetEvent Class

An event which is raised when a new sheet is added to a workbook.

class CXlWorkbookNewSheetEvent : public CXlEvent

Overview

The event occurs when a new sheet is added to a workbook.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookNewSheetEventStaticObserver.

When observers are notified, an argument of type CXlWorkbookNewSheetEventArgs is passed.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookNewSheetEvent Methods | xlpevents.h | CXllApp::WorkbookNewSheetEvent | Events | CXlWorkbookNewSheetEventArgs | CXlWorkbookNewSheetEventStaticObserver


CXlWorkbookNewSheetEvent Methods

The methods of the CXlWorkbookNewSheetEvent class are listed here.

Construction

public method CXlWorkbookNewSheetEvent Constructs a CXlWorkbookNewSheetEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookNewSheetEvent Class | xlpevents.h | CXllApp::WorkbookNewSheetEvent | Events | CXlWorkbookNewSheetEventArgs | CXlWorkbookNewSheetEventStaticObserver


CXlWorkbookNewSheetEvent::CXlWorkbookNewSheetEvent

Constructs a CXlWorkbookNewSheetEvent object

CXlWorkbookNewSheetEvent( );

Requirements

Header: xlpevents.h

See Also

CXlWorkbookNewSheetEvent Class | CXlWorkbookNewSheetEvent Methods


CXlWorkbookNewSheetEventArgs Class

An event argument class containing a workbook name and the name of the sheet that has been added to it.

class CXlWorkbookNewSheetEventArgs : public CXlEventArgs

Overview

This is the event argument used by the following worksheet event:

  • CXlWorkbookNewSheetEvent

Requirements

Header: xlpevents.h

See Also

CXlWorkbookNewSheetEventArgs Methods | xlpevents.h | Exceptions


CXlWorkbookNewSheetEventArgs Methods

The methods of the CXlWorkbookNewSheetEventArgs class are listed here.

Construction

public method CXlWorkbookNewSheetEventArgs Constructs a CXlWorkbookNewSheetEventArgs object

Properties

public method | GetBookName | Gets the name of the workbook
public method | GetSheetName | Gets the name of the worksheet

Methods of CXlEventArgs

Requirements

Header: xlpevents.h

See Also

CXlWorkbookNewSheetEventArgs Class | xlpevents.h | Exceptions


CXlWorkbookNewSheetEventArgs::CXlWorkbookNewSheetEventArgs

Constructs a CXlWorkbookNewSheetEventArgs object

CXlWorkbookNewSheetEventArgs(
   const TCHAR* bookName,
   const TCHAR* sheetName
);

Parameters

bookName

The name of the workbook for which the event is being raised.
sheetName

The name of the new worksheet.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookNewSheetEventArgs Class | CXlWorkbookNewSheetEventArgs Methods


CXlWorkbookNewSheetEventArgs::GetBookName

Gets the name of the workbook

const CString& GetBookName( ) const;

Return Value

Returns a reference to the name of the workbook for which the event is being raised.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookNewSheetEventArgs Class | CXlWorkbookNewSheetEventArgs Methods


CXlWorkbookNewSheetEventArgs::GetSheetName

Gets the name of the worksheet

const CString& GetSheetName( ) const;

Return Value

Returns a reference to the name of the new worksheet.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookNewSheetEventArgs Class | CXlWorkbookNewSheetEventArgs Methods


CXlWorkbookNewSheetEventStaticObserver Class

An event observer for XlWorkbookNewSheet, which is automatically registered and unregistered.

class CXlWorkbookNewSheetEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookNewSheetEventStaticObserver Methods | xlpevents.h | CXlWorkbookNewSheetEvent | Events


CXlWorkbookNewSheetEventStaticObserver Methods

The methods of the CXlWorkbookNewSheetEventStaticObserver class are listed here.

Construction

public method CXlWorkbookNewSheetEventStaticObserver Constructs a CXlWorkbookNewSheetEventStaticObserver object

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookNewSheetEventStaticObserver Class | xlpevents.h | CXlWorkbookNewSheetEvent | Events


CXlWorkbookNewSheetEventStaticObserver::CXlWorkbookNewSheetEventStaticObserver

Constructs a CXlWorkbookNewSheetEventStaticObserver object

CXlWorkbookNewSheetEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookNewSheetEventStaticObserver Class | CXlWorkbookNewSheetEventStaticObserver Methods


CXlWorkbookOpenEvent Class

An event which is raised when a workbook is opened.

class CXlWorkbookOpenEvent : public CXlEvent

Overview

The event occurs when a workbook is opened.

Observers can register for this event at any point in the life of the XLL. Registration can be done explicitly using Register, or automatically by creating an instance of CXlWorkbookOpenEventStaticObserver.

When observers are notified, an argument of type CXlWorkbookEventArgs is passed.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookOpenEvent Methods | xlpevents.h | CXllApp::WorkbookOpenEvent | Events | CXlWorkbookEventArgs | CXlWorkbookOpenEventStaticObserver


CXlWorkbookOpenEvent Methods

The methods of the CXlWorkbookOpenEvent class are listed here.

Construction

public method CXlWorkbookOpenEvent Constructs a CXlWorkbookOpenEvent object

Methods of CXlEvent<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookOpenEvent Class | xlpevents.h | CXllApp::WorkbookOpenEvent | Events | CXlWorkbookEventArgs | CXlWorkbookOpenEventStaticObserver


CXlWorkbookOpenEvent::CXlWorkbookOpenEvent

Constructs a CXlWorkbookOpenEvent object

CXlWorkbookOpenEvent( );

Requirements

Header: xlpevents.h

See Also

CXlWorkbookOpenEvent Class | CXlWorkbookOpenEvent Methods


CXlWorkbookOpenEventStaticObserver Class

An event observer for XlWorkbookOpen, which is automatically registered and unregistered.

class CXlWorkbookOpenEventStaticObserver : public CXlStaticEventObserver

Overview

It is sometimes inconvenient to register an event observer at the appropriate time. This class can be used to safely automatically register and unregister itself.

During the XlWorkbookOpen event, after the book has been opened, the object's Update method will be called.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookOpenEventStaticObserver Methods | xlpevents.h | CXlWorkbookOpenEvent | Events


CXlWorkbookOpenEventStaticObserver Methods

The methods of the CXlWorkbookOpenEventStaticObserver class are listed here.

Construction

public method CXlWorkbookOpenEventStaticObserver Constructs a CXlWorkbookOpenEventStaticObserver object

Events

public method Update Respond to an event

Methods of CXlStaticEventObserver<T>

Requirements

Header: xlpevents.h

See Also

CXlWorkbookOpenEventStaticObserver Class | xlpevents.h | CXlWorkbookOpenEvent | Events


CXlWorkbookOpenEventStaticObserver::CXlWorkbookOpenEventStaticObserver

Constructs a CXlWorkbookOpenEventStaticObserver object

CXlWorkbookOpenEventStaticObserver( );

Remarks

During construction, the observer is added to a linked list of static observers. Note that this linked list is safe to use at any time, so this class can be used for static variables.

At the appropriate time, the framework will register the observer with its event, and later will unregister it. For most events, registration occurs during XllOpen; for the XllOpen and XlRegisterFunctions events, registration occurs during InitInstance.

See the Update method for an example of this class in use.

Requirements

Header: xlpevents.h

See Also

CXlWorkbookOpenEventStaticObserver Class | CXlWorkbookOpenEventStaticObserver Methods


CXlWorkbookOpenEventStaticObserver::Update

Respond to an event

virtual void Update(
   CXlWorkbookEventArgs* e
);

Parameters

e

A pointer to an event arguments object is sent to the Update method.

Remarks

Derived classes should implement this function, which is the event handler for the XLL+ event model.

Example

The code below defines a class derived from CXlWorkbookOpenEventStaticObserver, implements an Update method which is called when the event occurs, and instantiates an instance of the new class.

CopyC++
// Define a class derived from CXlWorkbookOpenEventStaticObserver
class CMyWorkbookOpenEventObserver : CXlWorkbookOpenEventStaticObserver
{
public:
    // This method will be called during the XlWorkbookOpen event.
    virtual void Update(CXlWorkbookEventArgs* e)
    {
        CXllApp::XlMessageBox(_T("Opened ") + e->GetBookName(),
            XlMessageBoxTypeInformation);
    }
};

// Create an instance of the class
CMyWorkbookOpenEventObserver myWorkbookOpenObserver;

Requirements

Header: xlpevents.h

See Also

CXlWorkbookOpenEventStaticObserver Class | CXlWorkbookOpenEventStaticObserver Methods


CXlWorksheetEventArgs Class

An event argument class containing only a complete worksheet name.

class CXlWorksheetEventArgs : public CXlEventArgs

Overview

This is the event argument used by the following worksheet events:

  • CXlSheetActivateEvent
  • CXlSheetDeactivateEvent
  • CXlCalculateEvent

Requirements

Header: xlpevents.h

See Also

CXlWorksheetEventArgs Methods | xlpevents.h | Events


CXlWorksheetEventArgs Methods

The methods of the CXlWorksheetEventArgs class are listed here.

Construction

public method CXlWorksheetEventArgs Constructs a CXlWorksheetEventArgs object

Properties

public method GetSheetName Gets the full name of the worksheet

Methods of CXlEventArgs

Requirements

Header: xlpevents.h

See Also

CXlWorksheetEventArgs Class | xlpevents.h | Events


CXlWorksheetEventArgs::CXlWorksheetEventArgs

Constructs a CXlWorksheetEventArgs object

CXlWorksheetEventArgs(
   const TCHAR* sheetName
);

Parameters

sheetName

The name of the worksheet for which the event is being raised.

Requirements

Header: xlpevents.h

See Also

CXlWorksheetEventArgs Class | CXlWorksheetEventArgs Methods


CXlWorksheetEventArgs::GetSheetName

Gets the full name of the worksheet

const CString& GetSheetName( ) const;

Return Value

Returns a reference to the name of the worksheet for which the event is being raised.

Requirements

Header: xlpevents.h

See Also

CXlWorksheetEventArgs Class | CXlWorksheetEventArgs Methods


xlpexcept.h

Overview

xlpexcept.h contains definitions of all the exception classes used by the XLL+ run-time libraries.

The file is automatically included in the project files when the AppWizard creates the XLL+ project.

Classes

The table below lists the C++ exception classes declared in the header file.

Class | Description
CXlRuntimeException | The root exception class. All other exception classes are derived from this.
CXlConversionException | An exception thrown by the conversion operations that handle inputs from Excel.
CXlUserConversionException | An exception thrown by a user-defined extended type.
CXlOutOfRangeException | An exception thrown when an index to an array is out of range.
CXlIllegalArgumentException | An exception thrown when a parameter to a run-time function is illegal.
CXlBadOperTypeException | An exception thrown when a CXlOper argument contains data of an incorrect type.
CXlChoiceFailedException | An exception thrown by XLL+ Function Wizard-generated code, when a multiple choice argument cannot be resolved.
CXlElemTraitsNotImplemented | An exception thrown when a conversion operation encounters a data type which has not been registered.
CXlUninitializedOperException | An exception thrown when a CXlOper is used before it has been initialized.
CXlArrayTooLargeException | An exception thrown when an array is provided that is too large to be returned to Excel.
CXlEmptyArrayException | An exception thrown when an array is provided that is empty.
CXlStringTooLongException | An exception thrown when a string is provided that is too long to be returned to Excel.
CXlMemoryAllocationFailedException | An exception thrown when an attempt by the XLL+ run-time classes to allocate memory fails.
CXlApiException | An exception thrown when a call to the Excel API fails.
CXlStructuredException | An exception thrown when a C runtime exception (structured exception) is caught.
CXlErrorException | An exception which causes a specific error value to be returned to Excel.
CXlApiException | An exception thrown when a call to the Excel API fails.
CXlComException | An exception thrown when a call to the COM sub-system fails.

Macros

The table below lists the C++ macros declared in the header file.

Macro | Description
XLEXCEPTION_TRANSLATION | Defines a translation between an exception type and an Excel error value.
XLEXCEPTION_TRANSLATION_END | Marks the end of a list of XLEXCEPTION_TRANSLATION items.


CXlApiException Class

An exception thrown when a call to the Excel API fails.

class CXlApiException : public CXlRuntimeException

Overview

If a call to the Excel API fails unexpectedly, then an exception of type CXlApiException is thrown.

Requirements

Header: xlpexcept.h

See Also

CXlApiException Methods | xlpexcept.h | Exceptions


CXlApiException Methods

The methods of the CXlApiException class are listed here.

Construction

public method CXlApiException Constructs a CXlApiException object

Properties

public method | getApiCallName | Returns the name of the failed API call
public method | getResultCode | Returns the result code of the failed API call

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlApiException Class | xlpexcept.h | Exceptions


CXlApiException::CXlApiException

Constructs a CXlApiException object

CXlApiException( );
CXlApiException(
   const std::string& message
);
CXlApiException(
   const std::wstring& wmessage
);
CXlApiException(
   const char* apiCall,
   int rc
);
CXlApiException(
   const wchar_t* apiCallW,
   int rc
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.
apiCall

The name of the API call that failed.
rc

The result code returned by the API call that failed.
apiCallW

The name of the API call that failed.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlApiException Class | CXlApiException Methods


CXlApiException::getApiCallName

Returns the name of the failed API call

const std::wstring_t& getApiCallName( ) const;

Return Value

This function returns the name of the failed call to the Excel API.

Requirements

Header: xlpexcept.h

See Also

CXlApiException Class | CXlApiException Methods


CXlApiException::getResultCode

Returns the result code of the failed API call

int getResultCode( ) const;

Return Value

This function returns the result code returned by the failed call to the Excel API.

Requirements

Header: xlpexcept.h

See Also

CXlApiException Class | CXlApiException Methods


CXlArrayTooLargeException Class

An exception thrown when an array is provided that is too large to be returned to Excel.

class CXlArrayTooLargeException : public CXlRuntimeException

Overview

If an attempt is made to populate a CXlOper object with an array that is too large for the active version of Excel, then an exception of type CXlArrayTooLargeException will be thrown.

Requirements

Header: xlpexcept.h

See Also

CXlArrayTooLargeException Methods | xlpexcept.h | Exceptions


CXlArrayTooLargeException Methods

The methods of the CXlArrayTooLargeException class are listed here.

Construction

public method CXlArrayTooLargeException Constructs a CXlArrayTooLargeException object

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlArrayTooLargeException Class | xlpexcept.h | Exceptions


CXlArrayTooLargeException::CXlArrayTooLargeException

Constructs a CXlArrayTooLargeException object

CXlArrayTooLargeException( );
CXlArrayTooLargeException(
   const std::string& message
);
CXlArrayTooLargeException(
   const std::wstring& wmessage
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlArrayTooLargeException Class | CXlArrayTooLargeException Methods


CXlBadOperTypeException Class

An exception thrown when a CXlOper argument contains data of an incorrect type.

class CXlBadOperTypeException : public CXlRuntimeException

Overview

If a CXlOper object containing an unexpected data type is passed to any XLL+ run-time library function, then an exception of type CXlBadOperTypeException will be thrown.

Requirements

Header: xlpexcept.h

See Also

CXlBadOperTypeException Methods | xlpexcept.h | Exceptions


CXlBadOperTypeException Methods

The methods of the CXlBadOperTypeException class are listed here.

Construction

public method CXlBadOperTypeException Constructs a CXlBadOperTypeException object

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlBadOperTypeException Class | xlpexcept.h | Exceptions


CXlBadOperTypeException::CXlBadOperTypeException

Constructs a CXlBadOperTypeException object

CXlBadOperTypeException( );
CXlBadOperTypeException(
   const std::string& message
);
CXlBadOperTypeException(
   const std::wstring& wmessage
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlBadOperTypeException Class | CXlBadOperTypeException Methods


CXlChoiceFailedException Class

An exception thrown by XLL+ Function Wizard-generated code, when a multiple choice argument cannot be resolved.

class CXlChoiceFailedException : public CXlRuntimeException

Overview

If, during the input processing code generated by the XLL+ Function Wizard, it proves impossible to convert an input parameter that is part of a choice, then an exception of type CXlChoiceFailedException will be thrown.

Requirements

Header: xlpexcept.h

See Also

CXlChoiceFailedException Methods | xlpexcept.h | Conversion functions | Exceptions | Choices


CXlChoiceFailedException Methods

The methods of the CXlChoiceFailedException class are listed here.

Construction

public method CXlChoiceFailedException Constructs a CXlChoiceFailedException object

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlChoiceFailedException Class | xlpexcept.h | Conversion functions | Exceptions | Choices


CXlChoiceFailedException::CXlChoiceFailedException

Constructs a CXlChoiceFailedException object

CXlChoiceFailedException(
   const std::string& argName
);
CXlChoiceFailedException(
   const std::wstring& argName
);

Parameters

argName

An string containing the name of the argument that could not be converted.

Remarks

This constructor will expand the name of the failed argument into a complete localized message.

Requirements

Header: xlpexcept.h

See Also

CXlChoiceFailedException Class | CXlChoiceFailedException Methods


CXlComException Class

An exception thrown when a call to the COM sub-system fails.

class CXlComException : public CXlRuntimeException

Overview

If a call to the COM sub-system fails unexpectedly, then an exception of type CXlComException is thrown.

Requirements

Header: xlpexcept.h

See Also

CXlComException Methods | xlpexcept.h | Exceptions


CXlComException Methods

The methods of the CXlComException class are listed here.

Construction

public method CXlComException Constructs a CXlComException object

Properties

public method | getApiCallName | Returns the name of the failed API call
public method | getResultCode | Returns the result code of the failed API call

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlComException Class | xlpexcept.h | Exceptions


CXlComException::CXlComException

Constructs a CXlComException object

CXlComException( );
CXlComException(
   const std::string& message
);
CXlComException(
   const std::wstring& wmessage
);
CXlComException(
   const char* apiCall,
   HRESULT hr
);
CXlComException(
   const wchar_t* apiCallW,
   HRESULT hr
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.
apiCall

The name of the API call that failed.
hr

The result code returned by the API call that failed.
apiCallW

The name of the API call that failed.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlComException Class | CXlComException Methods


CXlComException::getApiCallName

Returns the name of the failed API call

const std::wstring_t& getApiCallName( ) const;

Return Value

This function returns the name of the failed call to the COM sub-system.

Requirements

Header: xlpexcept.h

See Also

CXlComException Class | CXlComException Methods


CXlComException::getResultCode

Returns the result code of the failed API call

HRESULT getResultCode( ) const;

Return Value

This function returns the result code returned by the failed call to the COM sub-system.

Requirements

Header: xlpexcept.h

See Also

CXlComException Class | CXlComException Methods


CXlConversionException Class

An exception thrown by the conversion operations that handle inputs from Excel.

class CXlConversionException : public CXlRuntimeException

Overview

If any of the argument conversion methods, such as XlReadScalar, XlReadVector or XlReadMatrix, fail for any reason, then an exception of type CXlConversionException is thrown.

Requirements

Header: xlpexcept.h

See Also

CXlConversionException Methods | xlpexcept.h | Conversion functions | Exceptions


CXlConversionException Methods

The methods of the CXlConversionException class are listed here.

Construction

public method CXlConversionException Constructs a CXlConversionException object

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlConversionException Class | xlpexcept.h | Conversion functions | Exceptions


CXlConversionException::CXlConversionException

Constructs a CXlConversionException object

CXlConversionException( );
CXlConversionException(
   const std::string& message
);
CXlConversionException(
   const std::wstring& wmessage
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlConversionException Class | CXlConversionException Methods


CXlElemTraitsNotImplemented Class

An exception thrown when a conversion operation encounters a data type which has not been registered.

class CXlElemTraitsNotImplemented : public CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlElemTraitsNotImplemented Methods | xlpexcept.h | Exceptions


CXlElemTraitsNotImplemented Methods

The methods of the CXlElemTraitsNotImplemented class are listed here.

Construction

public method CXlElemTraitsNotImplemented Constructs a CXlElemTraitsNotImplemented object

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlElemTraitsNotImplemented Class | xlpexcept.h | Exceptions


CXlElemTraitsNotImplemented::CXlElemTraitsNotImplemented

Constructs a CXlElemTraitsNotImplemented object

CXlElemTraitsNotImplemented( );
CXlElemTraitsNotImplemented(
   const std::string& message
);
CXlElemTraitsNotImplemented(
   const std::wstring& wmessage
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlElemTraitsNotImplemented Class | CXlElemTraitsNotImplemented Methods


CXlEmptyArrayException Class

An exception thrown when an array is provided that is empty.

class CXlEmptyArrayException : public CXlRuntimeException

Overview

If an attempt is made to populate a CXlOper object with an array that is empty, then an exception of type CXlEmptyArrayException will be thrown.

Requirements

Header: xlpexcept.h

See Also

CXlEmptyArrayException Methods | xlpexcept.h | Exceptions


CXlEmptyArrayException Methods

The methods of the CXlEmptyArrayException class are listed here.

Construction

public method CXlEmptyArrayException Constructs a CXlEmptyArrayException object

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlEmptyArrayException Class | xlpexcept.h | Exceptions


CXlEmptyArrayException::CXlEmptyArrayException

Constructs a CXlEmptyArrayException object

CXlEmptyArrayException( );
CXlEmptyArrayException(
   const std::string& message
);
CXlEmptyArrayException(
   const std::wstring& wmessage
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlEmptyArrayException Class | CXlEmptyArrayException Methods


CXlErrorException Class

An exception which causes a specific error value to be returned to Excel.

class CXlErrorException : public CXlRuntimeException

Overview

Throw an exception of type CXlErrorException to ensure that the desired error code will be returned to Excel.

The following code will return #VALUE! to Excel if x is negative.

CopyC++
if (x < 0)
    throw CXlErrorException(xlerrValue);

Requirements

Header: xlpexcept.h

See Also

CXlErrorException Methods | xlpexcept.h | Exceptions


CXlErrorException Methods

The methods of the CXlErrorException class are listed here.

Construction

public method CXlErrorException Constructs a CXlErrorException object

Properties

public method getXlErr Returns the Excel error value that will be returned to Excel

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlErrorException Class | xlpexcept.h | Exceptions


CXlErrorException::CXlErrorException

Constructs a CXlErrorException object

CXlErrorException(
   XlErrorType xlerr
);

Parameters

xlerr

An error number (see also Error Values).

Requirements

Header: xlpexcept.h

See Also

CXlErrorException Class | CXlErrorException Methods


CXlErrorException::getXlErr

Returns the Excel error value that will be returned to Excel

XlErrorType getXlErr( ) const;

Return Value

This function returns the error code that was provided to the constructor.

Requirements

Header: xlpexcept.h

See Also

CXlErrorException Class | CXlErrorException Methods


CXlIllegalArgumentException Class

An exception thrown when a parameter to a run-time function is illegal.

class CXlIllegalArgumentException : public CXlRuntimeException

Overview

If an unacceptable parameter is passed to any XLL+ run-time library function, then an exception of type CXlIllegalArgumentException will be thrown.

Requirements

Header: xlpexcept.h

See Also

CXlIllegalArgumentException Methods | xlpexcept.h | Exceptions


CXlIllegalArgumentException Methods

The methods of the CXlIllegalArgumentException class are listed here.

Construction

public method CXlIllegalArgumentException Constructs a CXlIllegalArgumentException object

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlIllegalArgumentException Class | xlpexcept.h | Exceptions


CXlIllegalArgumentException::CXlIllegalArgumentException

Constructs a CXlIllegalArgumentException object

CXlIllegalArgumentException( );
CXlIllegalArgumentException(
   const std::string& message
);
CXlIllegalArgumentException(
   const std::wstring& wmessage
);
CXlIllegalArgumentException(
   unsigned int messageTemplateId
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.
messageTemplateId

The ID of a string in the application's resource files.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlIllegalArgumentException Class | CXlIllegalArgumentException Methods


CXlMemoryAllocationFailedException Class

An exception thrown when an attempt by the XLL+ run-time classes to allocate memory fails.

class CXlMemoryAllocationFailedException : public CXlRuntimeException

Overview

If an attempt to allocate memory fails, then an exception of type CXlMemoryAllocationFailedException is thrown.

Requirements

Header: xlpexcept.h

See Also

CXlMemoryAllocationFailedException Methods | xlpexcept.h | Exceptions


CXlMemoryAllocationFailedException Methods

The methods of the CXlMemoryAllocationFailedException class are listed here.

Construction

public method CXlMemoryAllocationFailedException Constructs a CXlMemoryAllocationFailedException object

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlMemoryAllocationFailedException Class | xlpexcept.h | Exceptions


CXlMemoryAllocationFailedException::CXlMemoryAllocationFailedException

Constructs a CXlMemoryAllocationFailedException object

CXlMemoryAllocationFailedException( );
CXlMemoryAllocationFailedException(
   const std::string& message
);
CXlMemoryAllocationFailedException(
   const std::wstring& wmessage
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlMemoryAllocationFailedException Class | CXlMemoryAllocationFailedException Methods


CXlOutOfRangeException Class

An exception thrown when an index to an array is out of range.

class CXlOutOfRangeException : public CXlRuntimeException

Overview

If an attempt is made to reference an out-of-range coordinate of an array or of a CXlOper containing array, then an exception of type CXlOutOfRangeException is thrown.

Requirements

Header: xlpexcept.h

See Also

CXlOutOfRangeException Methods | xlpexcept.h | Exceptions


CXlOutOfRangeException Methods

The methods of the CXlOutOfRangeException class are listed here.

Construction

public method CXlOutOfRangeException Constructs a CXlOutOfRangeException object

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlOutOfRangeException Class | xlpexcept.h | Exceptions


CXlOutOfRangeException::CXlOutOfRangeException

Constructs a CXlOutOfRangeException object

CXlOutOfRangeException( );
CXlOutOfRangeException(
   const std::string& message
);
CXlOutOfRangeException(
   const std::wstring& wmessage
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlOutOfRangeException Class | CXlOutOfRangeException Methods


CXlRuntimeException Class

The root exception class. All other runtime exception classes are derived from this.

class CXlRuntimeException

Overview

Many of the classes and methods in the XLL+ run-time libraries throw run-time errors. For example, if an input to a function is of an unexpected type, then an exception of type CXlConversionException is thrown. If you attempt to pass an array back to Excel as the result of an add-in function, and the array is too big to be displayed in Excel, then an exception of type CXlArrayTooLargeException is thrown.

All runtime exception classes are derived from CXlRuntimeException. CXlRuntimeException is itself derived from the STL standard error type std::runtime_error.

Use the what method to get an ASCII string message describing the error. Use wwhat to get the Unicode version of the message.

Requirements

Header: xlpexcept.h

See Also

CXlRuntimeException Methods | xlpexcept.h | Exceptions


CXlRuntimeException Methods

The methods of the CXlRuntimeException class are listed here.

Construction

public method CXlRuntimeException Constructs a CXlRuntimeException object

Message

public method | twhat | Returns a string describing the exception
public method | what | Returns an ASCII string describing the exception
public method | wwhat | Returns a Unicode string describing the exception

Requirements

Header: xlpexcept.h

See Also

CXlRuntimeException Class | xlpexcept.h | Exceptions


CXlRuntimeException::CXlRuntimeException

Constructs a CXlRuntimeException object

CXlRuntimeException( );
CXlRuntimeException(
   const std::string& message
);
CXlRuntimeException(
   const std::wstring& wmessage
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.

Requirements

Header: xlpexcept.h

See Also

CXlRuntimeException Class | CXlRuntimeException Methods


CXlRuntimeException::twhat

Returns a string describing the exception

const TCHAR* twhat( ) const;

Return Value

Returns a pointer to a Unicode or ASCII string describing the exception, depending on the value of the compiler directive _UNICODE.

Requirements

Header: xlpexcept.h

See Also

CXlRuntimeException Class | CXlRuntimeException Methods


CXlRuntimeException::what

Returns an ASCII string describing the exception

const char* what( ) const;

Return Value

Returns a pointer to an ASCII string describing the exception.

Requirements

Header: xlpexcept.h

See Also

CXlRuntimeException Class | CXlRuntimeException Methods


CXlRuntimeException::wwhat

Returns a Unicode string describing the exception

const char* wwhat( ) const;

Return Value

Returns a pointer to a Unicode string describing the exception.

Requirements

Header: xlpexcept.h

See Also

CXlRuntimeException Class | CXlRuntimeException Methods


CXlStringTooLongException Class

An exception thrown when a string is provided that is too long to be returned to Excel.

class CXlStringTooLongException : public CXlRuntimeException

Overview

If an attempt is made to populate a CXlOper object with a string that is too long for the active version of Excel, then an exception of type CXlStringTooLongException will be thrown.

Requirements

Header: xlpexcept.h

See Also

CXlStringTooLongException Methods | xlpexcept.h | Exceptions


CXlStringTooLongException Methods

The methods of the CXlStringTooLongException class are listed here.

Construction

public method CXlStringTooLongException Constructs a CXlStringTooLongException object

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlStringTooLongException Class | xlpexcept.h | Exceptions


CXlStringTooLongException::CXlStringTooLongException

Constructs a CXlStringTooLongException object

CXlStringTooLongException( );
CXlStringTooLongException(
   const std::string& message
);
CXlStringTooLongException(
   const std::wstring& wmessage
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlStringTooLongException Class | CXlStringTooLongException Methods


CXlStructuredException Class

An exception thrown when a C runtime structured exception is caught.

class CXlStructuredException : public CXlRuntimeException

Overview

If the C run-time libraries throws a structured exception while an instance of CXlStructuredExceptionHandler is in scope, then an exception of type CXlStructuredException is thrown.

Requirements

Header: xlpexcept.h

See Also

CXlStructuredException Methods | xlpexcept.h | Exceptions


CXlStructuredException Methods

The methods of the CXlStructuredException class are listed here.

Construction

public method CXlStructuredException Constructs a CXlStructuredException object

Properties

public method getExceptionCode Returns the exception code of the C runtime exception

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlStructuredException Class | xlpexcept.h | Exceptions


CXlStructuredException::CXlStructuredException

Constructs a CXlStructuredException object

CXlStructuredException( );
CXlStructuredException(
   const std::string& message
);
CXlStructuredException(
   const std::wstring& wmessage
);
CXlStructuredException(
   unsigned long se
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.
se

The exception code of the C structured exception.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlStructuredException Class | CXlStructuredException Methods


CXlStructuredException::getExceptionCode

Returns the exception code of the C runtime exception

int getExceptionCode( ) const;

Return Value

This function returns the exception code raised by the C runtime library.

Requirements

Header: xlpexcept.h

See Also

CXlStructuredException Class | CXlStructuredException Methods


CXlStructuredExceptionHandler Class

A handler which catches C runtime exceptions and throws C++ exceptions.

class CXlStructuredExceptionHandler

Overview

If an instance of CXlStructuredExceptionHandler exists, then any C runtime exceptions (structured exceptions) that occur will be trapped and rethrown as C++ exceptions of type CXlStructuredException. As soon as the instance goes out of scope, this translation service will cease.

To suppress the impact of all instances of CXlStructuredExceptionHandler, globally define the pre-processor definition XLP_SUPPRESS_SEH. This will cause all the instances to have no effect. This setting can be useful for debugging.

Requirements

Header: xlpexcept.h

See Also

CXlStructuredExceptionHandler Methods | xlpexcept.h | C Runtime Exceptions | Exceptions


CXlStructuredExceptionHandler Methods

The methods of the CXlStructuredExceptionHandler class are listed here.

Construction

public method CXlStructuredExceptionHandler Constructs a CXlStructuredExceptionHandler object

Requirements

Header: xlpexcept.h

See Also

CXlStructuredExceptionHandler Class | xlpexcept.h | C Runtime Exceptions | Exceptions


CXlStructuredExceptionHandler::CXlStructuredExceptionHandler

Constructs a CXlStructuredExceptionHandler object

CXlStructuredExceptionHandler( );

Remarks

When the constructor is called, the C runtime method _set_se_translator() is used to set a private static method which will handle C runtime structured exceptions until this object goes out of scope.

Requirements

Header: xlpexcept.h

See Also

CXlStructuredExceptionHandler Class | CXlStructuredExceptionHandler Methods


CXlUninitializedOperException Class

An exception thrown when a CXlOper is used before it has been initialized.

class CXlUninitializedOperException : public CXlConversionException

Overview

If a CXlOper object which has not been initialized is encountered by a conversion function, then an exception of type CXlUninitializedOperException will be thrown.

Requirements

Header: xlpexcept.h

See Also

CXlUninitializedOperException Methods | xlpexcept.h | Conversion functions | Exceptions


CXlUninitializedOperException Methods

The methods of the CXlUninitializedOperException class are listed here.

Construction

public method CXlUninitializedOperException Constructs a CXlUninitializedOperException object

Methods of CXlConversionException

Requirements

Header: xlpexcept.h

See Also

CXlUninitializedOperException Class | xlpexcept.h | Conversion functions | Exceptions


CXlUninitializedOperException::CXlUninitializedOperException

Constructs a CXlUninitializedOperException object

CXlUninitializedOperException( );
CXlUninitializedOperException(
   const std::string& message
);
CXlUninitializedOperException(
   const std::wstring& wmessage
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlUninitializedOperException Class | CXlUninitializedOperException Methods


CXlUserConversionException Class

An exception thrown by a user-defined extended type.

class CXlUserConversionException : public CXlRuntimeException

Overview

If an implementation of a conversion class descended from CXlUserConverterBase fails, it should throw an exception of type CXlUserConversionException.

Requirements

Header: xlpexcept.h

See Also

CXlUserConversionException Methods | xlpexcept.h | Conversion functions | Extended scalar types | Exceptions


CXlUserConversionException Methods

The methods of the CXlUserConversionException class are listed here.

Construction

public method CXlUserConversionException Constructs a CXlUserConversionException object

Methods of CXlRuntimeException

Requirements

Header: xlpexcept.h

See Also

CXlUserConversionException Class | xlpexcept.h | Conversion functions | Extended scalar types | Exceptions


CXlUserConversionException::CXlUserConversionException

Constructs a CXlUserConversionException object

CXlUserConversionException( );
CXlUserConversionException(
   const std::string& message
);
CXlUserConversionException(
   const std::wstring& wmessage
);
CXlUserConversionException(
   unsigned int messageTemplateId
);

Parameters

message

An ASCII string containing a description of the error condition.
wmessage

A Unicode string containing a description of the error condition.
messageTemplateId

The ID of a string in the application's resource files.

Remarks

If no argument is provided to the constructor, then a default localized message will be used.

Requirements

Header: xlpexcept.h

See Also

CXlUserConversionException Class | CXlUserConversionException Methods


Exception macros

Exception macros are listed here.

Translation

public method | XLEXCEPTION_TRANSLATION | Declares a translation between an exception type and an Excel error value
public method | XLEXCEPTION_TRANSLATION_END | Declares the end of a list of XLEXCEPTION_TRANSLATION items

Requirements

Header: xlpexcept.h

See Also

xlpexcept.h


::XLEXCEPTION_TRANSLATION

Declares a translation between an exception type and an Excel error value

XLEXCEPTION_TRANSLATION(
   LABEL exceptionType,
   XlErrorType xlerr
);

Parameters

exceptionType

The type of exception to be translated, e.g. CXlConversionException. Note that the class name is not in quotes - it is a label, not a string.

xlerr

An Excel error value to be returned to Excel. See Error value types for a full list of error codes.

Remarks

This macro creates a XlExceptionTranslation structure, which can be used by CXllApp::ConvertTypeToError to translate an exception to an Excel error value.

If you use the XLEXCEPTION_TRANSLATION macro, you should ensure that your project has the Enable Run-time Type Info setting set to Yes (/GR). The setting can be found on the C/C++ - Language page of the project settings.

See Overriding exception-handling behavior in the User Guide for more information about this method.

Requirements

Header: xlpexcept.h

See Also

Exception macros | XLEXCEPTION_TRANSLATION_END | CXllApp::ConvertTypeToError


::XLEXCEPTION_TRANSLATION_END

Declares the end of a list of XLEXCEPTION_TRANSLATION items

XLEXCEPTION_TRANSLATION_END( );

Remarks

This macro creates a null XlExceptionTranslation structure, which is used by CXllApp::ConvertTypeToError to find the end of a list of translation items.

See Overriding exception-handling behavior in the User Guide for more information about this method.

Requirements

Header: xlpexcept.h

See Also

Exception macros | XLEXCEPTION_TRANSLATION | CXllApp::ConvertTypeToError


xlpfastit.h

Overview

xlpfastit.h contains a class CXlArrayContainer<T> and some associated iterator classes for fast iteration of large Excel arrays.

These iterators can be used to search through a CXlOper containing an array with minimum performance overhead. Compared with standard CXlOper programming, using these classes is harder work.

Classes

The table below lists the C++ object classes declared in the header file.

Class | Description
CXlArrayContainer<T> | Helps to search and iterate over CXlOper instances that contain arrays.
CXlArrayCellIterator<T> | Iterates over each of the cells in CXlOper instances that contain arrays.
CXlArrayRowIterator<T> | Iterates over the rows of CXlOper instances that contain arrays.
CXlArrayColumnIterator<T> | Iterates over the columns of CXlOper instances that contain arrays.

See Also

CXlArrayContainer<T> class | CXlArrayCellIterator<T> class | CXlArrayRowIterator<T> class | CXlArrayColumnIterator<T> class


CXlArrayCellIterator<T> Class

Iterates over each of the cells in CXlOper instances that contain arrays.

class CXlArrayCellIterator<T>

Overview

The CXlArrayCellIterator<T> class is a utility class to help you iterate across CXlOper instances that contain large arrays. The iterator traverses across all cells in the array row-wise, starting at the top row and moving to the bottom row. Within each row it traverses from left to right.

The class is normally accessed through a typedef of the container class: CXlArrayContainer<T>::cell_iterator.

These iterators can be used to iterate through a CXlOper containing an array with minimum performance overhead. Compared with standard CXlOper programming, using these classes is harder work.

Usage

Use the class with the following pattern:

    double total = 0.0;
    if (input->HasOper12())
    {
        CXlArrayContainer<XLOPER12> cont(*input);
        for (CXlArrayContainer<XLOPER12>::cell_iterator i = cont.begin(); i != cont.end(); i++)
        {
            // Look at the value in each cell
            if (i->xltype == xltypeNum)
                total += i->val.num;
        }
    }
    else if (input->HasOper4())
    {
        // Provide this section only if you wish to provide support for Excel 2003 and below
        CXlArrayContainer<XLOPER4> cont(*input);
        // ...
    }

Requirements

Header: xlpfastit.h

See Also

CXlArrayCellIterator<T> Methods | xlpfastit.h | CXlArrayContainer<T> class | CXlArrayRowIterator<T> class | CXlArrayColumnIterator<T> class


CXlArrayCellIterator<T> Methods

The methods of the CXlArrayCellIterator<T> class are listed here.

Construction

public method | CXlArrayCellIterator | Constructs a CXlArrayCellIterator object
public method | operator= | Copies a CXlArrayCellIterator object

Iteration

public method | operator+ | Creates and returns an iterator a number of positions forward from this instance
public method | operator++ | Increments an iterator by one position
public method | operator+= | Increments an iterator by a number of positions

Comparison

public method | operator!= | Compares two iterators
public method | operator== | Compares two iterators

Dereferencing

public method | operator* | Dereferences an iterator
public method | operator-> | Dereferences an iterator

Requirements

Header: xlpfastit.h

See Also

CXlArrayCellIterator<T> Class | xlpfastit.h | CXlArrayContainer<T> class | CXlArrayRowIterator<T> class | CXlArrayColumnIterator<T> class


CXlArrayCellIterator<T>::CXlArrayCellIterator

Constructs a CXlArrayCellIterator object

CXlArrayCellIterator(
   const CXlArrayContainer<T>& cont,
   size_t offset = 0
);
CXlArrayCellIterator(
   const CXlArrayCellIterator<T>& s
);
CXlArrayCellIterator( );

Parameters

cont

The container across which this iterator will traverse.
offset

The index within the array at which the iterator will start.
s

A source iterator which will be copied into the new instance.

Remarks

Constructs a new CXlArrayCellIterator object. In normal usage, almost all instances of the iterator class are created using the container methods begin() and end().

Note that iterators constructed using the parameterless constructor cannot be used until they have been set to point to a container, by using the = operator.

Requirements

Header: xlpfastit.h

See Also

CXlArrayCellIterator<T> Class | CXlArrayCellIterator<T> Methods


CXlArrayCellIterator<T>::operator!=

Compares two iterators

bool operator!=(
   const CXlArrayCellIterator<T>& other
);

Parameters

other

Another cell iterator.

Return Value

Returns false if both iterators refer to the same position within the same container; true otherwise.

Requirements

Header: xlpfastit.h

See Also

CXlArrayCellIterator<T> Class | CXlArrayCellIterator<T> Methods


CXlArrayCellIterator<T>::operator*

Dereferences an iterator

const T& operator*( );

Return Value

Returns a reference to the cell that the iterator is currently pointing to.

Requirements

Header: xlpfastit.h

See Also

CXlArrayCellIterator<T> Class | CXlArrayCellIterator<T> Methods


CXlArrayCellIterator<T>::operator+

Creates and returns an iterator a number of positions forward from this instance

CXlArrayCellIterator<T> operator+(
   size_t n
);

Parameters

n

The number of steps by which to increment the new iterator.

Return Value

Returns a reference to the new incremented iterator.

Remarks

For the debug build only, this operator will throw an exception of type CXlRuntimeException if the value of n will put the iterator out-of-range, i.e. beyond the end position.

Requirements

Header: xlpfastit.h

See Also

CXlArrayCellIterator<T> Class | CXlArrayCellIterator<T> Methods


CXlArrayCellIterator<T>::operator++

Increments an iterator by one position

CXlArrayCellIterator<T> operator++( );

Return Value

Returns a reference to the incremented iterator. For the prefix operator, the returned value is post-increment; For the postfix operator, the returned value is pre-increment.

Remarks

For the debug build only, this operator will throw an exception of type CXlRuntimeException if the increment will put the iterator out-of-range, i.e. beyond the end position.

Requirements

Header: xlpfastit.h

See Also

CXlArrayCellIterator<T> Class | CXlArrayCellIterator<T> Methods


CXlArrayCellIterator<T>::operator+=

Increments an iterator by a number of positions

void operator+=(
   size_t n
);

Parameters

n

The number of steps by which to increment the iterator.

Remarks

For the debug build only, this operator will throw an exception of type CXlRuntimeException if the value of n will put the iterator out-of-range, i.e. beyond the end position.

Requirements

Header: xlpfastit.h

See Also

CXlArrayCellIterator<T> Class | CXlArrayCellIterator<T> Methods


CXlArrayCellIterator<T>::operator=

Copies a CXlArrayCellIterator object

const CXlArrayCellIterator<T>& operator=(
   const CXlArrayCellIterator<T>& s
);

Parameters

s

A source iterator which will be copied into the new instance.

Remarks

Copies an existing CXlArrayCellIterator object.

Requirements

Header: xlpfastit.h

See Also

CXlArrayCellIterator<T> Class | CXlArrayCellIterator<T> Methods


CXlArrayCellIterator<T>::operator==

Compares two iterators

bool operator==(
   const CXlArrayCellIterator<T>& other
);

Parameters

other

Another cell iterator.

Return Value

Returns true if both iterators refer to the same position within the same container; false otherwise.

Requirements

Header: xlpfastit.h

See Also

CXlArrayCellIterator<T> Class | CXlArrayCellIterator<T> Methods


CXlArrayCellIterator<T>::operator->

Dereferences an iterator

const T* operator->( );

Return Value

Returns a pointer to the cell that the iterator is currently pointing to.

Requirements

Header: xlpfastit.h

See Also

CXlArrayCellIterator<T> Class | CXlArrayCellIterator<T> Methods


CXlArrayColumnIterator<T> Class

Iterates over the columns of CXlOper instances that contain arrays.

class CXlArrayColumnIterator<T>

Overview

The CXlArrayColumnIterator<T> class is a utility class to help you iterate across CXlOper instances that contain large arrays. The iterator traverses across each column of the array, starting at the left-most column and moving to the right-most column.

The class is normally accessed through a typedef of the container class: CXlArrayContainer<T>::col_iterator.

These iterators can be used to iterate through a CXlOper containing an array with minimum performance overhead. Compared with standard CXlOper programming, using these classes is harder work.

Usage

Use the class with the following pattern:

    double total = 0.0;
    if (input->HasOper12())
    {
        CXlArrayContainer<XLOPER12> cont(*input);
        for (CXlArrayContainer<XLOPER12>::col_iterator c = cont.begin_cols(); c != cont.end_cols(); c++)
        {
            // Look at a cell in the first row of the current column
            if (c->xltype == xltypeNum)
                total += c->val.num;
            // Look at a cell in the the second row of the current column
            if (c[1].xltype == xltypeNum)
                total += c[1].val.num;
        }
    }
    else if (input->HasOper4())
    {
        // Provide this section only if you wish to provide support for Excel 2003 and below
        CXlArrayContainer<XLOPER4> cont(*input);
        // ...
    }

Requirements

Header: xlpfastit.h

See Also

CXlArrayColumnIterator<T> Methods | xlpfastit.h | CXlArrayContainer<T> class | CXlArrayCellIterator<T> class | CXlArrayRowIterator<T> class


CXlArrayColumnIterator<T> Methods

The methods of the CXlArrayColumnIterator<T> class are listed here.

Construction

public method | CXlArrayColumnIterator | Constructs a CXlArrayColumnIterator object
public method | operator= | Copies a CXlArrayColumnIterator object

Iteration

public method | operator+ | Creates and returns an iterator a number of positions forward from this instance
public method | operator++ | Increments an iterator by one position
public method | operator+= | Increments an iterator by a number of positions

Comparison

public method | operator!= | Compares two iterators
public method | operator== | Compares two iterators

Dereferencing

public method | operator* | Dereferences an iterator
public method | operator[] | Dereferences a cell in the current column
public method | operator-> | Dereferences an iterator

Requirements

Header: xlpfastit.h

See Also

CXlArrayColumnIterator<T> Class | xlpfastit.h | CXlArrayContainer<T> class | CXlArrayCellIterator<T> class | CXlArrayRowIterator<T> class


CXlArrayColumnIterator<T>::CXlArrayColumnIterator

Constructs a CXlArrayColumnIterator object

CXlArrayColumnIterator(
   const CXlArrayContainer<T>& cont,
   size_t offset = 0
);
CXlArrayColumnIterator(
   const CXlArrayColumnIterator<T>& s
);
CXlArrayColumnIterator( );

Parameters

cont

The container across which this iterator will traverse.
offset

The zero-based index of the column within the array at which the iterator will start.
s

A source iterator which will be copied into the new instance.

Remarks

Constructs a new CXlArrayColumnIterator object. In normal usage, almost all instances of the iterator class are created using the container methods begin_cols() and end_cols().

Note that iterators constructed using the parameterless constructor cannot be used until they have been set to point to a container, by using the = operator.

Requirements

Header: xlpfastit.h

See Also

CXlArrayColumnIterator<T> Class | CXlArrayColumnIterator<T> Methods


CXlArrayColumnIterator<T>::operator!=

Compares two iterators

bool operator!=(
   const CXlArrayColumnIterator<T>& other
);

Parameters

other

Another cell iterator.

Return Value

Returns false if both iterators refer to the same position within the same container; true otherwise.

Requirements

Header: xlpfastit.h

See Also

CXlArrayColumnIterator<T> Class | CXlArrayColumnIterator<T> Methods


CXlArrayColumnIterator<T>::operator*

Dereferences an iterator

const T& operator*( );

Return Value

Returns a reference to the top cell in the column that the iterator is currently pointing to.

Requirements

Header: xlpfastit.h

See Also

CXlArrayColumnIterator<T> Class | CXlArrayColumnIterator<T> Methods


CXlArrayColumnIterator<T>::operator[]

Dereferences a cell in the current column

const T& operator[](
   size_t n
);

Parameters

n

The zero-based index of the row whose value is to be dereferenced.

Return Value

Returns a reference to cell in row n (where n is a zero-based index) of the column that the iterator is currently pointing to.

In the debug build only, an exception of type CXlRuntimeException will be thrown if n is out-of-range.

Requirements

Header: xlpfastit.h

See Also

CXlArrayColumnIterator<T> Class | CXlArrayColumnIterator<T> Methods


CXlArrayColumnIterator<T>::operator+

Creates and returns an iterator a number of positions forward from this instance

CXlArrayColumnIterator<T> operator+(
   size_t n
);

Parameters

n

The number of steps by which to increment the new iterator.

Return Value

Returns a reference to the new incremented iterator.

Remarks

For the debug build only, this operator will throw an exception of type CXlRuntimeException if the value of n will put the iterator out-of-range, i.e. beyond the end position.

Requirements

Header: xlpfastit.h

See Also

CXlArrayColumnIterator<T> Class | CXlArrayColumnIterator<T> Methods


CXlArrayColumnIterator<T>::operator++

Increments an iterator by one position

CXlArrayColumnIterator<T> operator++( );

Return Value

Returns a reference to the incremented iterator. For the prefix operator, the returned value is post-increment; For the postfix operator, the returned value is pre-increment.

Remarks

For the debug build only, this operator will throw an exception of type CXlRuntimeException if the increment will put the iterator out-of-range, i.e. beyond the end position.

Requirements

Header: xlpfastit.h

See Also

CXlArrayColumnIterator<T> Class | CXlArrayColumnIterator<T> Methods


CXlArrayColumnIterator<T>::operator+=

Increments an iterator by a number of positions

void operator+=(
   size_t n
);

Parameters

n

The number of steps by which to increment the iterator.

Remarks

For the debug build only, this operator will throw an exception of type CXlRuntimeException if the value of n will put the iterator out-of-range, i.e. beyond the end position.

Requirements

Header: xlpfastit.h

See Also

CXlArrayColumnIterator<T> Class | CXlArrayColumnIterator<T> Methods


CXlArrayColumnIterator<T>::operator=

Copies a CXlArrayColumnIterator object

const CXlArrayColumnIterator<T>& operator=(
   const CXlArrayColumnIterator<T>& s
);

Parameters

s

A source iterator which will be copied into the new instance.

Remarks

Copies an existing CXlArrayColumnIterator object.

Requirements

Header: xlpfastit.h

See Also

CXlArrayColumnIterator<T> Class | CXlArrayColumnIterator<T> Methods


CXlArrayColumnIterator<T>::operator==

Compares two iterators

bool operator==(
   const CXlArrayColumnIterator<T>& other
);

Parameters

other

Another cell iterator.

Return Value

Returns true if both iterators refer to the same position within the same container; false otherwise.

Requirements

Header: xlpfastit.h

See Also

CXlArrayColumnIterator<T> Class | CXlArrayColumnIterator<T> Methods


CXlArrayColumnIterator<T>::operator->

Dereferences an iterator

const T* operator->( );

Return Value

Returns a pointer to the top most cell in the column that the iterator is currently pointing to.

Requirements

Header: xlpfastit.h

See Also

CXlArrayColumnIterator<T> Class | CXlArrayColumnIterator<T> Methods


CXlArrayContainer<T> Class

Helps to search and iterate over CXlOper instances that contain arrays.

class CXlArrayContainer<T>

Overview

The CXlArrayContainer<T> class is a utility class to help you inspect CXlOper instances that contain large arrays. Three types of read-only forward-only iterators are provided to work with the container class. They can be accessed most easily through typedef's, as shown in the example code in Usage below.

typedef | Class | Description
cell_iterator | CXlArrayCellIterator<T> | Forward-only iterator which traverses across all cells in the array.
row_iterator | CXlArrayRowIterator<T> | Forward-only iterator which traverses across each row in the array.
col_iterator | CXlArrayColumnIterator<T> | Forward-only iterator which traverses across all columns in the array.

These iterators can be used to iterate through a CXlOper containing an array with minimum performance overhead. Compared with standard CXlOper programming, using these classes is harder work.

Usage

Use the class with the following pattern:

    double total = 0.0;
    if (input->HasOper12())
    {
        CXlArrayContainer<XLOPER12> cont(*input);
        for (CXlArrayContainer<XLOPER12>::cell_iterator i = cont.begin(); i != cont.end(); i++)
        {
            // Look at the value in each cell
            if (i->xltype == xltypeNum)
                total += i->val.num;
        }
        for (CXlArrayContainer<XLOPER12>::row_iterator r = cont.begin_rows(); r != cont.end_rows(); r++)
        {
            // Look at a cell in the first column of the current row
            if (r->xltype == xltypeNum)
                total += r->val.num;
            // Look at a cell in the third column of the current row
            if (r[2].xltype == xltypeNum)
                total += r[2].val.num;
        }
        for (CXlArrayContainer<XLOPER12>::col_iterator c = cont.begin_cols(); c != cont.end_cols(); c++)
        {
            // Look at a cell in the first row of the current column
            if (c->xltype == xltypeNum)
                total += c->val.num;
            // Look at a cell in the the second row of the current column
            if (c[1].xltype == xltypeNum)
                total += c[1].val.num;
        }
    }
    else if (input->HasOper4())
    {
        // Provide this section only if you wish to provide support for Excel 2003 and below
        CXlArrayContainer<XLOPER4> cont(*input);
        // ...
    }

Requirements

Header: xlpfastit.h

See Also

CXlArrayContainer<T> Methods | xlpfastit.h | CXlArrayCellIterator<T> class | CXlArrayRowIterator<T> class | CXlArrayColumnIterator<T> class


CXlArrayContainer<T> Methods

The methods of the CXlArrayContainer<T> class are listed here.

Construction

public method CXlArrayContainer Constructs a CXlArrayContainer object

Accessors

public method at Returns a reference to the cell at the requested position or coordinates

Iterators

public method | begin | Get a cell iterator for the start of the array
public method | begin_cols | Get a column iterator for the start of the array
public method | begin_rows | Get a row iterator for the start of the array
public method | end | Get a cell iterator for the end of the array
public method | end_cols | Get a column iterator for the end of the array
public method | end_rows | Get a row iterator for the end of the array

Requirements

Header: xlpfastit.h

See Also

CXlArrayContainer<T> Class | xlpfastit.h | CXlArrayCellIterator<T> class | CXlArrayRowIterator<T> class | CXlArrayColumnIterator<T> class


CXlArrayContainer<T>::at

Returns a reference to the cell at the requested position or coordinates

const T& at(
   size_t n
);
const T& at(
   size_t r,
   size_t c
);

Parameters

n

Zero-based position of cell within array, counting row-wise.
r

Zero-based ordinal of row within array.
c

Zero-based ordinal of column within array.

Return Value

Returns a reference to the contained cell if within range. In the debug build only, throws an exception if the coordinates or position are out of range.

Requirements

Header: xlpfastit.h

See Also

CXlArrayContainer<T> Class | CXlArrayContainer<T> Methods


CXlArrayContainer<T>::begin

Get a cell iterator for the start of the array

CXlArrayContainer<T>::cell_iterator begin( );

Return Value

Returns a new cell iterator, pointing to the start of the array.

The iterator will be of type CXlArrayCellIterator<T>.

Requirements

Header: xlpfastit.h

See Also

CXlArrayContainer<T> Class | CXlArrayContainer<T> Methods


CXlArrayContainer<T>::begin_cols

Get a column iterator for the start of the array

CXlArrayContainer<T>::col_iterator begin_cols( );

Return Value

Returns a new column iterator, pointing to the start of the array.

The iterator will be of type CXlArrayColumnIterator<T>.

Requirements

Header: xlpfastit.h

See Also

CXlArrayContainer<T> Class | CXlArrayContainer<T> Methods


CXlArrayContainer<T>::begin_rows

Get a row iterator for the start of the array

CXlArrayContainer<T>::row_iterator begin_rows( );

Return Value

Returns a new row iterator, pointing to the start of the array.

The iterator will be of type CXlArrayRowIterator<T>.

Requirements

Header: xlpfastit.h

See Also

CXlArrayContainer<T> Class | CXlArrayContainer<T> Methods


CXlArrayContainer<T>::CXlArrayContainer

Constructs a CXlArrayContainer object

CXlArrayContainer(
   const CXlOper& xloArray
);

Parameters

xloArray

A CXlOper instance that contains an array or a value type (number, string, error or boolean).

Remarks

Constructs a CXlArrayContainer object, which can then be used to create iterators for its contained cells.

In the debug build only, an exception of type CXlRuntimeException will be thrown if xloArray does not contain data of type T.

In all builds an exception of type CXlRuntimeException will be thrown if xloArray does not contain either an array (not a reference) or a single value (of type number, string, error or boolean).

Requirements

Header: xlpfastit.h

See Also

CXlArrayContainer<T> Class | CXlArrayContainer<T> Methods


CXlArrayContainer<T>::end

Get a cell iterator for the end of the array

CXlArrayContainer<T>::cell_iterator end( );

Return Value

Returns a new cell iterator, pointing to just beyond the end of the array.

The iterator will be of type CXlArrayCellIterator<T>.

Requirements

Header: xlpfastit.h

See Also

CXlArrayContainer<T> Class | CXlArrayContainer<T> Methods


CXlArrayContainer<T>::end_cols

Get a column iterator for the end of the array

CXlArrayContainer<T>::col_iterator end_cols( );

Return Value

Returns a new column iterator, pointing to just beyond the end of the array.

The iterator will be of type CXlArrayColumnIterator<T>.

Requirements

Header: xlpfastit.h

See Also

CXlArrayContainer<T> Class | CXlArrayContainer<T> Methods


CXlArrayContainer<T>::end_rows

Get a row iterator for the end of the array

CXlArrayContainer<T>::row_iterator end_rows( );

Return Value

Returns a new row iterator, pointing to just beyond the end of the array.

The iterator will be of type CXlArrayRowIterator<T>.

Requirements

Header: xlpfastit.h

See Also

CXlArrayContainer<T> Class | CXlArrayContainer<T> Methods


CXlArrayRowIterator<T> Class

Iterates over the rows of CXlOper instances that contain arrays.

class CXlArrayRowIterator<T>

Overview

The CXlArrayRowIterator<T> class is a utility class to help you iterate across CXlOper instances that contain large arrays. The iterator traverses across each row of the array, starting at the top row and moving to the bottom row.

The class is normally accessed through a typedef of the container class: CXlArrayContainer<T>::row_iterator.

These iterators can be used to iterate through a CXlOper containing an array with minimum performance overhead. Compared with standard CXlOper programming, using these classes is harder work.

Usage

Use the class with the following pattern:

    double total = 0.0;
    if (input->HasOper12())
    {
        CXlArrayContainer<XLOPER12> cont(*input);
        for (CXlArrayContainer<XLOPER12>::row_iterator r = cont.begin_rows(); r != cont.end_rows(); r++)
        {
            // Look at a cell in the first column of the current row
            if (r->xltype == xltypeNum)
                total += r->val.num;
            // Look at a cell in the third column of the current row
            if (r[2].xltype == xltypeNum)
                total += r[2].val.num;
        }
    }
    else if (input->HasOper4())
    {
        // Provide this section only if you wish to provide support for Excel 2003 and below
        CXlArrayContainer<XLOPER4> cont(*input);
        // ...
    }

Requirements

Header: xlpfastit.h

See Also

CXlArrayRowIterator<T> Methods | xlpfastit.h | CXlArrayContainer<T> class | CXlArrayCellIterator<T> class | CXlArrayColumnIterator<T> class


CXlArrayRowIterator<T> Methods

The methods of the CXlArrayRowIterator<T> class are listed here.

Construction

public method | CXlArrayRowIterator | Constructs a CXlArrayRowIterator object
public method | operator= | Copies a CXlArrayRowIterator object

Iteration

public method | operator+ | Creates and returns an iterator a number of positions forward from this instance
public method | operator++ | Increments an iterator by one position
public method | operator+= | Increments an iterator by a number of positions

Comparison

public method | operator!= | Compares two iterators
public method | operator== | Compares two iterators

Dereferencing

public method | operator* | Dereferences an iterator
public method | operator[] | Dereferences a cell in the current row
public method | operator-> | Dereferences an iterator

Requirements

Header: xlpfastit.h

See Also

CXlArrayRowIterator<T> Class | xlpfastit.h | CXlArrayContainer<T> class | CXlArrayCellIterator<T> class | CXlArrayColumnIterator<T> class


CXlArrayRowIterator<T>::CXlArrayRowIterator

Constructs a CXlArrayRowIterator object

CXlArrayRowIterator(
   const CXlArrayContainer<T>& cont,
   size_t offset = 0
);
CXlArrayRowIterator(
   const CXlArrayRowIterator<T>& s
);
CXlArrayRowIterator( );

Parameters

cont

The container across which this iterator will traverse.
offset

The zero-based index of the row within the array at which the iterator will start.
s

A source iterator which will be copied into the new instance.

Remarks

Constructs a new CXlArrayRowIterator object. In normal usage, almost all instances of the iterator class are created using the container methods begin_rows() and end_rows().

Note that iterators constructed using the parameterless constructor cannot be used until they have been set to point to a container, by using the = operator.

Requirements

Header: xlpfastit.h

See Also

CXlArrayRowIterator<T> Class | CXlArrayRowIterator<T> Methods


CXlArrayRowIterator<T>::operator!=

Compares two iterators

bool operator!=(
   const CXlArrayRowIterator<T>& other
);

Parameters

other

Another cell iterator.

Return Value

Returns false if both iterators refer to the same position within the same container; true otherwise.

Requirements

Header: xlpfastit.h

See Also

CXlArrayRowIterator<T> Class | CXlArrayRowIterator<T> Methods


CXlArrayRowIterator<T>::operator*

Dereferences an iterator

const T& operator*( );

Return Value

Returns a reference to the left-most cell in the row that the iterator is currently pointing to.

Requirements

Header: xlpfastit.h

See Also

CXlArrayRowIterator<T> Class | CXlArrayRowIterator<T> Methods


CXlArrayRowIterator<T>::operator[]

Dereferences a cell in the current row

const T& operator[](
   size_t n
);

Parameters

n

The zero-based index of the column whose value is to be dereferenced.

Return Value

Returns a reference to cell in column n (where n is a zero-based index) of the row that the iterator is currently pointing to.

In the debug build only, an exception of type CXlRuntimeException will be thrown if n is out-of-range.

Requirements

Header: xlpfastit.h

See Also

CXlArrayRowIterator<T> Class | CXlArrayRowIterator<T> Methods


CXlArrayRowIterator<T>::operator+

Creates and returns an iterator a number of positions forward from this instance

CXlArrayRowIterator<T> operator+(
   size_t n
);

Parameters

n

The number of steps by which to increment the new iterator.

Return Value

Returns a reference to the new incremented iterator.

Remarks

For the debug build only, this operator will throw an exception of type CXlRuntimeException if the value of n will put the iterator out-of-range, i.e. beyond the end position.

Requirements

Header: xlpfastit.h

See Also

CXlArrayRowIterator<T> Class | CXlArrayRowIterator<T> Methods


CXlArrayRowIterator<T>::operator++

Increments an iterator by one position

CXlArrayRowIterator<T> operator++( );

Return Value

Returns a reference to the incremented iterator. For the prefix operator, the returned value is post-increment; For the postfix operator, the returned value is pre-increment.

Remarks

For the debug build only, this operator will throw an exception of type CXlRuntimeException if the increment will put the iterator out-of-range, i.e. beyond the end position.

Requirements

Header: xlpfastit.h

See Also

CXlArrayRowIterator<T> Class | CXlArrayRowIterator<T> Methods


CXlArrayRowIterator<T>::operator+=

Increments an iterator by a number of positions

void operator+=(
   size_t n
);

Parameters

n

The number of steps by which to increment the iterator.

Remarks

For the debug build only, this operator will throw an exception of type CXlRuntimeException if the value of n will put the iterator out-of-range, i.e. beyond the end position.

Requirements

Header: xlpfastit.h

See Also

CXlArrayRowIterator<T> Class | CXlArrayRowIterator<T> Methods


CXlArrayRowIterator<T>::operator=

Copies a CXlArrayRowIterator object

const CXlArrayRowIterator<T>& operator=(
   const CXlArrayRowIterator<T>& s
);

Parameters

s

A source iterator which will be copied into the new instance.

Remarks

Copies an existing CXlArrayRowIterator object.

Requirements

Header: xlpfastit.h

See Also

CXlArrayRowIterator<T> Class | CXlArrayRowIterator<T> Methods


CXlArrayRowIterator<T>::operator==

Compares two iterators

bool operator==(
   const CXlArrayRowIterator<T>& other
);

Parameters

other

Another cell iterator.

Return Value

Returns true if both iterators refer to the same position within the same container; false otherwise.

Requirements

Header: xlpfastit.h

See Also

CXlArrayRowIterator<T> Class | CXlArrayRowIterator<T> Methods


CXlArrayRowIterator<T>::operator->

Dereferences an iterator

const T* operator->( );

Return Value

Returns a pointer to the left-most cell in the row that the iterator is currently pointing to.

Requirements

Header: xlpfastit.h

See Also

CXlArrayRowIterator<T> Class | CXlArrayRowIterator<T> Methods


xlpfunctionfilter.h

Overview

xlpfunctionfilter.h contains classes which allow the developer to control which add-in functions are made available to users and which are not. Filtering can be managed on an opt-in basis or an opt-out basis. Filtering can be controlled at development-time (by using a function extension to make entries in the source code) or at run-time (by supplying a configuration file that is loaded by the add-in).

Opt-in
Only functions that have been registered to be published will be made available to the user; all other functions will be suppressed. Adding this option to an existing add-in will suppress all it's add-in functions; the developer must then add some code to register some or all of the functions in the add-in.
Opt-out
All functions will be made available except those which have been chosen to be suppressed. Adding this option to an existing add-in will have no impact. The developer must then add some code to suppress some or all of the functions in the add-in.

The main class, CXllFunctionFilter, maintains a list of functions and a flag which determines whether or not they are to be published.

A pair of simple helper classes, CXllFunctionFilterOptIn and CXllFunctionFilterOptOut, can be used to statically register functions to be published (under an opt-out policy) or suppressed (under an opt-in policy). These classes are used by the code generator of the function extension.

Two function extensions are supplied: FunctionFilterOptIn and FunctionFilterOptOut. These can be used to include and exclude functions via the XLL+ Function Wizard, either singly or en-masse.

A utility class CXllFunctionFilterLoader is used to load and read the configuration file, if a run-time strategy is used.

Finally, three event handling classes provide the wiring that lets all this processing happen without the use of any additional developer-supplied code.

Classes

The table below lists the classes declared in the header file.

Class | Description
CXllFunctionFilter | A registry of add-in functions, and instructions as to whether they should be published or suppressed.
CXllFunctionFilterOptIn | Statically registers a single function to be published.
CXllFunctionFilterOptOut | Statically registers a single function to be suppressed.
CXllFunctionFilterLoader | Loads a configuration file, and applies the contents to the registry.
CXllFunctionFilterEventHandlerOptIn | A static event handler which implements an opt-in policy by running CXllFunctionFilter::Apply(true) during the RegisterFunctions event.
CXllFunctionFilterEventHandlerOptOut | A static event handler which implements an opt-out policy by running CXllFunctionFilter::Apply(false) during the RegisterFunctions event.
CXllFunctionFilterEventHandlerFromFile | A static event handler that loads and intereprets a configuration file at run-time and applies it during the RegisterFunctions event.

See Also

Publishing and suppressing add-in functions (User Guide)


CXllFunctionFilter Class

A registry whch contains a list of functions, each with a flag which determines whether or not the function is to be published or suppressed.

class CXllFunctionFilter

Overview

The CXllFunctionFilter class can be used to store a list of add-in functions, along with instructions as to whether they should be published (made available to the user) at run-time, or suppressed at run-time.

This behavior allows developers to finely control which functions are made available to users at run-time, without having to maintain multiple versions of source code.

Using the class

See the following examples for instructions on how to use the class:

PubDevIn sample
Publish at development-time sample (opt-in). This project shows how to control the list of functions published, so that only functions specifically marked are made available to the user; all the unmarked functions are available only to the developer.
PubDevOut sample
Publish at development-time sample (opt-out). This project shows how to control the list of functions published, so that only functions specifically marked are hidden from the user; all the unmarked functions are made available to the user.
PublishRT sample
Publish at run-time sample. A configuration file controls which functions are published.

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilter Methods | xlpfunctionfilter.h | CXllFunctionFilterOptIn class | CXllFunctionFilterOptOut class | CXllFunctionFilterLoader class | CXllFunctionFilterEventHandlerOptIn class | CXllFunctionFilterEventHandlerOptOut class | CXllFunctionFilterEventHandlerFromFile class | Publishing and suppressing add-in functions (User Guide) | Publish at development-time sample (opt-in) | Publish at development-time sample (opt-out) | Publish at run-time sample


CXllFunctionFilter Methods

The methods of the CXllFunctionFilter class are listed here.

Singleton

Instance Return the single instance of CXllFunctionFilter

Operations

Apply | Applies the list of registered functions to the global XLL Add-ins function list, causing them to be removed freom the global list, or left in place
Publish | Registers the named function for publishing or suppressing

Construction

public method CXllFunctionFilter Constructs a CXllFunctionFilter object

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilter Class | xlpfunctionfilter.h | CXllFunctionFilterOptIn class | CXllFunctionFilterOptOut class | CXllFunctionFilterLoader class | CXllFunctionFilterEventHandlerOptIn class | CXllFunctionFilterEventHandlerOptOut class | CXllFunctionFilterEventHandlerFromFile class | Publishing and suppressing add-in functions (User Guide) | Publish at development-time sample (opt-in) | Publish at development-time sample (opt-out) | Publish at run-time sample


CXllFunctionFilter::Apply

Applies the list of registered functions to the global XLL Add-ins function list, causing them to be removed freom the global list, or left in place

static void Apply(
   CXllApp& app,
   bool removeUnpublished
);

Parameters

app

A reference to the global application instance.
removeUnpublished

If true, then an opt-in policy is implemented - all functions are removed from the list of published functions, except those specifically registered.

If false, then an opt-out policy is implemented - only registered functions are removed from the list of published functions.

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilter Class | CXllFunctionFilter Methods


CXllFunctionFilter::CXllFunctionFilter

Constructs a CXllFunctionFilter object

CXllFunctionFilter( );

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilter Class | CXllFunctionFilter Methods


CXllFunctionFilter::Instance

Return the single instance of CXllFunctionFilter

static CXllFunctionFilter* Instance( );

Return Value

Returns the single instance of CXllFunctionFilter.

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilter Class | CXllFunctionFilter Methods


CXllFunctionFilter::Publish

Registers the named function for publishing or suppressing

static void Publish(
   const char* fnName,
   bool published
);
static void Publish(
   const wchar_t* fnName,
   bool published
);

Parameters

fnName

The name of the function which is to be published or suppressed.
published

If true, the function will be published. If false the function will be suppressed.

Remarks

The function specified will be added to the function filter's registry. The actual publishing or supression will occur when Apply() is called.

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilter Class | CXllFunctionFilter Methods


CXllFunctionFilterEventHandlerFromFile Class

An automatically registered event observer for XlRegisterFunctions, which loads and applies a function filter configuration file.

class CXllFunctionFilterEventHandlerFromFile : public CXlRegisterFunctionsEventStaticObserver

Overview

This event observer should be declared at global scope as a static instance, as below:

CopyC++
CXllFunctionFilterEventHandlerFromFile theFunctionFilter(CXllFunctionFilterLoader::EXPLICIT);

During the XlRegisterFunctions event, the object's Update method will be called. As a result, the specified configuration file will be located, loaded and parsed and then applied to the function filter registry, CXllFunctionFilter. The actual work of loading and parsing the file is performed by CXllFunctionFilterLoader.

Configuration file

The configuration file will be parsed in one of two ways.

If the loadType specified in the constructor is CXllFunctionFilterLoader::OPT_IN or CXllFunctionFilterLoader::OPT_OUT then the file should contain a list of function names, each on a single line. Blank lines are ignored.

If the loadType is CXllFunctionFilterLoader::EXPLICIT then the file should contain a list of function names and actions, each on a single line. Each line should contain a pair of items, separated by white space: first a function name, and second a boolean value, which can be 1, 0, true or false. If the boolean value is 1 or true, then the function in that line is published. If the boolean value is 0 or false, then the function in that line is suppressed. Blank lines are ignored.

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterEventHandlerFromFile Methods | xlpfunctionfilter.h | CXllFunctionFilter class | CXllFunctionFilterLoader class | CXlRegisterFunctionsEvent | Publishing and suppressing add-in functions (User Guide)


CXllFunctionFilterEventHandlerFromFile Methods

The methods of the CXllFunctionFilterEventHandlerFromFile class are listed here.

Construction

public method CXllFunctionFilterEventHandlerFromFile Constructs a CXllFunctionFilterEventHandlerFromFile object

Methods of CXlRegisterFunctionsEventStaticObserver

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterEventHandlerFromFile Class | xlpfunctionfilter.h | CXllFunctionFilter class | CXllFunctionFilterLoader class | CXlRegisterFunctionsEvent | Publishing and suppressing add-in functions (User Guide)


CXllFunctionFilterEventHandlerFromFile::CXllFunctionFilterEventHandlerFromFile

Constructs a CXllFunctionFilterEventHandlerFromFile object

CXllFunctionFilterEventHandlerFromFile(
   CXllFunctionFilterLoader::LoadTypes loadType = CXllFunctionFilterLoader::OPT_IN,
   bool bPropagateError = true
);

Parameters

loadType

The strategy to be applied to the contents of the file. For details of the effect see the note "Configuration file" in the CXllFunctionFilterEventHandlerFromFile class documentation.

bPropagateError

If this is true, then any errors will be reported to the user, and the add-in will not be loaded. If this is false, then errors will be ignored.

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterEventHandlerFromFile Class | CXllFunctionFilterEventHandlerFromFile Methods


CXllFunctionFilterEventHandlerOptIn Class

An automatically registered event observer for XlRegisterFunctions, which applies a function filter using the opt-in policy.

class CXllFunctionFilterEventHandlerOptIn : public CXlRegisterFunctionsEventStaticObserver

Overview

This event observer should be declared at global scope as a static instance, as below:

CopyC++
CXllFunctionFilterEventHandlerOptIn theFunctionFilter;

During the XlRegisterFunctions event, the object's Update method will be called. As a result, an opt-in policy will be appied to the function filter (CXllFunctionFilter), using the following:

CopyC++
CXllFunctionFilter::Apply(*CXllApp::Instance(), true);

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterEventHandlerOptIn Methods | xlpfunctionfilter.h | CXllFunctionFilter class | CXllFunctionFilterEventHandlerOptOut class | CXlRegisterFunctionsEvent | Publishing and suppressing add-in functions (User Guide)


CXllFunctionFilterEventHandlerOptIn Methods

The methods of the CXllFunctionFilterEventHandlerOptIn class are listed here.

Construction

public method CXllFunctionFilterEventHandlerOptIn Constructs a CXllFunctionFilterEventHandlerOptIn object

Methods of CXlRegisterFunctionsEventStaticObserver

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterEventHandlerOptIn Class | xlpfunctionfilter.h | CXllFunctionFilter class | CXllFunctionFilterEventHandlerOptOut class | CXlRegisterFunctionsEvent | Publishing and suppressing add-in functions (User Guide)


CXllFunctionFilterEventHandlerOptIn::CXllFunctionFilterEventHandlerOptIn

Constructs a CXllFunctionFilterEventHandlerOptIn object

CXllFunctionFilterEventHandlerOptIn( );

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterEventHandlerOptIn Class | CXllFunctionFilterEventHandlerOptIn Methods


CXllFunctionFilterEventHandlerOptOut Class

An automatically registered event observer for XlRegisterFunctions, which applies a function filter using the opt-out policy.

class CXllFunctionFilterEventHandlerOptOut : public CXlRegisterFunctionsEventStaticObserver

Overview

This event observer should be declared at global scope as a static instance, as below:

CopyC++
CXllFunctionFilterEventHandlerOptOut theFunctionFilter;

During the XlRegisterFunctions event, the object's Update method will be called. As a result, an opt-in policy will be appied to the function filter (CXllFunctionFilter), using the following:

CopyC++
CXllFunctionFilter::Apply(*CXllApp::Instance(), false);

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterEventHandlerOptOut Methods | xlpfunctionfilter.h | CXllFunctionFilter class | CXllFunctionFilterEventHandlerOptIn class | CXlRegisterFunctionsEvent | Publishing and suppressing add-in functions (User Guide)


CXllFunctionFilterEventHandlerOptOut Methods

The methods of the CXllFunctionFilterEventHandlerOptOut class are listed here.

Construction

public method CXllFunctionFilterEventHandlerOptOut Constructs a CXllFunctionFilterEventHandlerOptOut object

Methods of CXlRegisterFunctionsEventStaticObserver

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterEventHandlerOptOut Class | xlpfunctionfilter.h | CXllFunctionFilter class | CXllFunctionFilterEventHandlerOptIn class | CXlRegisterFunctionsEvent | Publishing and suppressing add-in functions (User Guide)


CXllFunctionFilterEventHandlerOptOut::CXllFunctionFilterEventHandlerOptOut

Constructs a CXllFunctionFilterEventHandlerOptOut object

CXllFunctionFilterEventHandlerOptOut( );

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterEventHandlerOptOut Class | CXllFunctionFilterEventHandlerOptOut Methods


CXllFunctionFilterLoader Class

Loads a configuration file, and applies the contents to the function filter registry.

class CXllFunctionFilterLoader

Overview

The CXllFinder class is a utility class to help you load configuration files which will be applied to the CXllFunctionFilter function filter registry. This enables control of the function filter at run-time.

Note that this method of control can be altered by users; if you want to keep the function filter under the control of the developer, then you should use the FunctionFilterOptIn or FunctionFilterOptOut function extensions.

Usage

The CXllFunctionFilterLoader class is usually instantiated and used by the event handler class CXllFunctionFilterEventHandlerFromFile. It is not normally used directly by the developer.

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterLoader Methods | xlpfunctionfilter.h | CXllFunctionFilter class | Publishing and suppressing add-in functions (User Guide)


CXllFunctionFilterLoader Methods

The methods of the CXllFunctionFilterLoader class are listed here.

Operations

LoadTextFile Loads the specified text file, parses the contents and applies them to the function filter

Construction

public method CXllFunctionFilterLoader Constructs a CXllFunctionFilterLoader object

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterLoader Class | xlpfunctionfilter.h | CXllFunctionFilter class | Publishing and suppressing add-in functions (User Guide)


CXllFunctionFilterLoader::CXllFunctionFilterLoader

Constructs a CXllFunctionFilterLoader object

CXllFunctionFilterLoader( );

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterLoader Class | CXllFunctionFilterLoader Methods


CXllFunctionFilterLoader::LoadTextFile

Loads the specified text file, parses the contents and applies them to the function filter

static bool LoadTextFile(
   char* path,
   CXllFunctionFilterLoader::LoadTypes loadType = CXllFunctionFilterLoader::OPT_IN
);

Parameters

path

The fully qualified path to the configuration file to be loaded.
loadType

The strategy to be applied to the contents of the file: either CXllFunctionFilterLoader::OPT_IN, CXllFunctionFilterLoader::OPT_OUT or CXllFunctionFilterLoader::EXPLICIT.

For details of the effect see the note "Configuration file" in the CXllFunctionFilterEventHandlerFromFile class documentation.

Return Value

Returns true if the file was successfully loaded and applied. Returns false if the file could not be loaded.

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterLoader Class | CXllFunctionFilterLoader Methods


CXllFunctionFilterOptIn Class

Adds a function to the function filter registry.

class CXllFunctionFilterOptIn

Overview

Use a static instance of this class to add a function's name to the function filter registry CXllFunctionFilter. The constructor calls CXllFunctionFilter::Publish(fnName, true). This means that the function will be included in the list of functions published under an opt-in policy, i.e. when all functions are suppressed except those listed in the registry.

The class has no effect under an opt-out policy.

Instances of this class are automatically generated by the FunctionFilterOptOut function extension.

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterOptIn Methods | xlpfunctionfilter.h | CXllFunctionFilter class | Publishing and suppressing add-in functions (User Guide)


CXllFunctionFilterOptIn Methods

The methods of the CXllFunctionFilterOptIn class are listed here.

Construction

public method CXllFunctionFilterOptIn Constructs a CXllFunctionFilterOptIn object

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterOptIn Class | xlpfunctionfilter.h | CXllFunctionFilter class | Publishing and suppressing add-in functions (User Guide)


CXllFunctionFilterOptIn::CXllFunctionFilterOptIn

Constructs a CXllFunctionFilterOptIn object

CXllFunctionFilterOptIn(
   const char* fnName
);
CXllFunctionFilterOptIn(
   const wchar_t* fnName
);

Parameters

fnName

The name of the function which is to be published.
fnName

The name of the function which is to be published.

Remarks

This constructor causes the named function to be added to the list of functions that will be published under an opt-in policy.

The constructor has no effect under an opt-out policy.

Instances of this constructor are automatically generated by the FunctionFilterOptOut function extension.

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterOptIn Class | CXllFunctionFilterOptIn Methods


CXllFunctionFilterOptOut Class

Adds a function to the function filter registry.

class CXllFunctionFilterOptOut

Overview

Use a static instance of this class to add a function's name to the function filter registry CXllFunctionFilter. The constructor calls CXllFunctionFilter::Publish(fnName, false). This means that the function will be included in the list of functions suppressed under an opt-out strategy, i.e. when all functions are included except those listed in the registry.

The class has no effect under an opt-in policy.

Instances of this class are automatically generated by the FunctionFilterOptOut function extension.

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterOptOut Methods | xlpfunctionfilter.h | CXllFunctionFilter class | Publishing and suppressing add-in functions (User Guide)


CXllFunctionFilterOptOut Methods

The methods of the CXllFunctionFilterOptOut class are listed here.

Construction

public method CXllFunctionFilterOptOut Constructs a CXllFunctionFilterOptOut object

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterOptOut Class | xlpfunctionfilter.h | CXllFunctionFilter class | Publishing and suppressing add-in functions (User Guide)


CXllFunctionFilterOptOut::CXllFunctionFilterOptOut

Constructs a CXllFunctionFilterOptOut object

CXllFunctionFilterOptOut(
   const char* fnName
);
CXllFunctionFilterOptOut(
   const wchar_t* fnName
);

Parameters

fnName

The name of the function which is to be published.
fnName

The name of the function which is to be published.

Remarks

This constructor causes the named function to be added to the list of functions that will be suppressed under an opt-out policy.

The constructor has no effect under an opt-in policy.

Instances of this constructor are automatically generated by the FunctionFilterOptOut function extension.

Requirements

Header: xlpfunctionfilter.h

See Also

CXllFunctionFilterOptOut Class | CXllFunctionFilterOptOut Methods


xlpribbon.h

Overview

xlpribbon.h contains definitions of the classes and enumerations that implement the XLL+ ribbon event model.

The file is #included in the main header file when the AppWizard creates the XLL+ project, if the Ribbon option is checked in the AppWizard.

Classes

The table below lists the core classes declared in the header file.

Class | Description
CRibbonEvtParams | Contains the parameters passed with a ribbon event.

Enumerations

The table below lists the enumerations declared in the header file.

Enumeration | Description
RibbonCallbackTypes | A list of the various callback types that can raise a ribbon event.

See Also

The Ribbon (User Guide) | Ribbon reference


CRibbonEvtParams Class

Contains the parameters passed with a ribbon event.

class CRibbonEvtParams

Overview

The CRibbonEvtParams class contains the paraneters passed by the ribbon when a ribbon event occurs. All the contents of the class are read-only, and can be retrieved with property getter functions.

Requirements

Header: xlpribbon.h

See Also

CRibbonEvtParams Methods | xlpribbon.h | CXllApp::OnRibbonEvent | The Ribbon (User Guide) | Ribbon reference | RibbonCallbackTypes enumeration


CRibbonEvtParams Methods

The methods of the CRibbonEvtParams class are listed here.

Construction

public method CRibbonEvtParams Constructs a new instance of CRibbonEvtParams

Properties

public method | GetCallback | Returns the type of callback which raised this event
public method | GetId | Returns the id of the control which raised this event
public method | GetIndex | Returns the index of the item for which the control raised this event
public method | GetPressed | Returns the pressed state of the control which raised this event
public method | GetSelectedId | Returns the id of the selected item within the control which raised this event
public method | GetTag | Returns the tag of the control which raised this event
public method | GetText | Returns the current text of the control which raised this event

Requirements

Header: xlpribbon.h

See Also

CRibbonEvtParams Class | xlpribbon.h | CXllApp::OnRibbonEvent | The Ribbon (User Guide) | Ribbon reference | RibbonCallbackTypes enumeration


CRibbonEvtParams::CRibbonEvtParams

Constructs a new instance of CRibbonEvtParams

CRibbonEvtParams(
   RibbonCallbackTypes callback,
   LPCTSTR pszId,
   LPCTSTR pszTag,
   long lIndex,
   LPCTSTR pszText,
   LPCTSTR pszSelectedId,
   bool bPressed
);

Parameters

callback

The type of callback that raised the event. See RibbonCallbackTypes for a list of callback types.

pszId

The unique id of a control.
pszTag

The tag of a control.
lIndex

The index of an item within a control.
pszText

The current text of an edit or combobox control.
pszSelectedId

The id of the selected item of the control.
bPressed

The pressed state of the control.

Remarks

This method is used by the framework, and should not normally be called by your code.

Requirements

Header: xlpribbon.h

See Also

CRibbonEvtParams Class | CRibbonEvtParams Methods


CRibbonEvtParams::GetCallback

Returns the type of callback which raised this event

RibbonCallbackTypes GetCallback( );

Remarks

See RibbonCallbackTypes for a list of callback types.

Requirements

Header: xlpribbon.h

See Also

CRibbonEvtParams Class | CRibbonEvtParams Methods


CRibbonEvtParams::GetId

Returns the id of the control which raised this event

const CString& GetId( );

Remarks

See CXllApp::OnRibbonEvent for a list of which callback types pass a value for Id.

Requirements

Header: xlpribbon.h

See Also

CRibbonEvtParams Class | CRibbonEvtParams Methods


CRibbonEvtParams::GetIndex

Returns the index of the item for which the control raised this event

long GetIndex( );

Remarks

See CXllApp::OnRibbonEvent for a list of which callback types pass a value for Index. If no value is available, then -1 will be returned.

Requirements

Header: xlpribbon.h

See Also

CRibbonEvtParams Class | CRibbonEvtParams Methods


CRibbonEvtParams::GetPressed

Returns the pressed state of the control which raised this event

bool GetPressed( );

Remarks

Returns true if the control is currently pressed (or checked) and false if it is currently not pressed. See CXllApp::OnRibbonEvent for a list of which callback types pass a value for Pressed.

Requirements

Header: xlpribbon.h

See Also

CRibbonEvtParams Class | CRibbonEvtParams Methods


CRibbonEvtParams::GetSelectedId

Returns the id of the selected item within the control which raised this event

const CString& GetSelectedId( );

Remarks

See CXllApp::OnRibbonEvent for a list of which callback types pass a value for SelectedId. If no value is available, then -1 will be returned.

Requirements

Header: xlpribbon.h

See Also

CRibbonEvtParams Class | CRibbonEvtParams Methods


CRibbonEvtParams::GetTag

Returns the tag of the control which raised this event

const CString& GetTag( );

Remarks

See CXllApp::OnRibbonEvent for a list of which callback types pass a value for Tag. If no tag attribute has been specified for a control, then the method will return an empty string.

Requirements

Header: xlpribbon.h

See Also

CRibbonEvtParams Class | CRibbonEvtParams Methods


CRibbonEvtParams::GetText

Returns the current text of the control which raised this event

const CString& GetText( );

Remarks

See CXllApp::OnRibbonEvent for a list of which callback types pass a value for Text.

Requirements

Header: xlpribbon.h

See Also

CRibbonEvtParams Class | CRibbonEvtParams Methods


Enumerations

The enumerations declared in xlpribbon.h are listed below.

RibbonCallbackTypes

Requirements

Header: xlpribbon.h

See Also

xlpribbon.h


RibbonCallbackTypes Enumeration

The various types of callback that can raise a ribbon event.

enum RibbonCallbackTypes

Members

RIBBONCALLBACK_ONACTION | 1 | The user has clicked a button or a menu or has selected an item from a gallery or dropdown.
RIBBONCALLBACK_GETDESCRIPTION | 2 | The ribbon is asking for the description of a control.
RIBBONCALLBACK_GETENABLED | 3 | The ribbon is asking for the enabled state of a control.
RIBBONCALLBACK_GETIMAGE | 4 | The ribbon is asking for the ID or file name of an image to be displayed by a control.
RIBBONCALLBACK_GETIMAGEMSO | 5 | The ribbon is asking for the ID of a standard Office image to be displayed by a control.
RIBBONCALLBACK_GETLABEL | 6 | The ribbon is asking for the label of a control.
RIBBONCALLBACK_GETKEYTIP | 7 | The ribbon is asking for the keytip of a control.
RIBBONCALLBACK_GETSIZE | 8 | The ribbon is asking for the size of a control.
RIBBONCALLBACK_GETSCREENTIP | 9 | The ribbon is asking for the screentip of a control.
RIBBONCALLBACK_GETSUPERTIP | 10 | The ribbon is asking for the supertip of a control.
RIBBONCALLBACK_GETVISIBLE | 11 | The ribbon is asking whether a control is currently visible.
RIBBONCALLBACK_GETSHOWIMAGE | 12 | The ribbon is asking whether the image of a control should be shown.
RIBBONCALLBACK_GETSHOWLABEL | 13 | The ribbon is asking whether the label of a control should be shown.
RIBBONCALLBACK_GETPRESSED | 14 | The ribbon is asking for the pressed state of a control.
RIBBONCALLBACK_GETITEMCOUNT | 15 | The ribbon is asking how many items are contained within a control.
RIBBONCALLBACK_GETITEMHEIGHT | 16 | The ribbon is asking for the height of all the items within a control.
RIBBONCALLBACK_GETITEMID | 17 | The ribbon is asking for the id of the item whose index is passed.
RIBBONCALLBACK_GETITEMIMAGE | 18 | The ribbon is asking for the image id or file name for the item whose index is passed.
RIBBONCALLBACK_GETITEMLABEL | 19 | The ribbon is asking for the label of the item whose index is passed.
RIBBONCALLBACK_GETITEMSCREENTIP | 20 | The ribbon is asking for the screen tip of the item whose index is passed.
RIBBONCALLBACK_GETITEMSUPERTIP | 21 | The ribbon is asking for the supertip of the item whose index is passed.
RIBBONCALLBACK_GETITEMWIDTH | 22 | The ribbon is asking for the width of the item whose index is passed.
RIBBONCALLBACK_GETTEXT | 23 | The ribbon is asking for the current text of the control.
RIBBONCALLBACK_ONCHANGE | 24 | The ribbon is notifying the add-in that a text field has been changed by the user.
RIBBONCALLBACK_LOADIMAGE | 25 | The ribbon is asking for the screen tip of the item whose index is passed. This callback is never passed on to CXllApp::OnRibbonEvent().
RIBBONCALLBACK_ONLOAD | 26 | The ribbon is notifying the add-in that the ribbon controls have been loaded. This callback is never passed on to CXllApp::OnRibbonEvent().
RIBBONCALLBACK_GETSELECTEDITEMID | 27 | The ribbon is asking for the id of the currently selected item of a control.
RIBBONCALLBACK_GETSELECTEDITEMINDEX | 28 | The ribbon is asking for the index of the currently selected item of a control.
RIBBONCALLBACK_GETCONTENT | 29 | The ribbon is asking for the current content of a dynamic menu.
RIBBONCALLBACK_GETTITLE | 30 | The ribbon is asking for the title of a menu separator.

Requirements

Header: xlpribbon.h

See Also

xlpribbon.h | CXllApp::OnRibbonEvent | The Ribbon (User Guide) | Ribbon reference


xlpshared.h

Overview

xlpshared.h contain classes that allow you to safely share data between threads.

Classes

Class | Description
CXlLockable | An object that can be locked by one thread to exclude other threads until it is unlocked.
CXlLock | represents a lock applied to a CXlLockable object.

See Also

Ensuring global data is thread-safe


CXlLock Class

An object which applies a lock to a CXlLockable and whose lifetime controls the duration of the lock.

class CXlLock

Overview

The CXlLock class can be used to lock an object for thread-safe access.

The most convenient way to lock a CXlLockable object is by creating a CXlLock object. CXlLock calls CXlLockable::Lock() when it is constructed, and calls CXlLockable::Unlock() when it is destroyed.

A typical usage is shown below.

CopyC++
CXlLockable sharedObject;
void UseSharedObject()
{
    CXlLock lock(sharedObject, true);
    // Do something with the sharedObject
    // On exit from this function, the CXlLock instance will
    // be destroyed, and sharedObject will be unlocked
}

Requirements

Header: xlpshared.h

See Also

CXlLock Methods | xlpshared.h | Ensuring global data is thread-safe | CXlLockable


CXlLock Methods

The methods of the CXlLock class are listed here.

Construction

public method CXlLock Constructs a CXlLock object and optionally locks the target CXlLockable object

Public methods

public method | IsLocked | Returns whether the lock has been applied
public method | Lock | Locks a shared object
public method | Unlock | Unlocks a shared object

Requirements

Header: xlpshared.h

See Also

CXlLock Class | xlpshared.h | Ensuring global data is thread-safe | CXlLockable


CXlLock::CXlLock

Constructs a CXlLock object and optionally locks the target CXlLockable object

CXlLock(
   CXlLockable& lockable,
   bool initialLock = false
);

Parameters

lockable

A reference to the CXlLockable object to which this lock will be applied.

initialLock

If this parameter is true, then the lock will be applied immediately. If the target CXlLockable is already locked, then the thread calling this constructor will wait until it has been unlocked.

If initialLock is false, then the lock will not be applied until the Lock() method is called.

Remarks

This method constructs a CXlLock object.

Requirements

Header: xlpshared.h

See Also

CXlLock Class | CXlLock Methods


CXlLock::IsLocked

Returns whether the lock has been applied

bool IsLocked( ) const;

Return Value

Returns true if the lock has been applied; returns false if the lock has not yet been applied.

Requirements

Header: xlpshared.h

See Also

CXlLock Class | CXlLock Methods


CXlLock::Lock

Locks a shared object

bool Lock( );

Return Value

Returns true if the target CXlLockable has been initialized; returns false if the CXlLockable has no been prepared for use. A return value of false indicates a fatal error.

Requirements

Header: xlpshared.h

See Also

CXlLock Class | CXlLock Methods


CXlLock::Unlock

Unlocks a shared object

void Unlock( );

Remarks

This method unlocks an object previously locked using Lock(). Each call to Lock() from a particular thread requires a matching call to Unlock() before the object becomes available to other threads.

Requirements

Header: xlpshared.h

See Also

CXlLock Class | CXlLock Methods


CXlLockable Class

An object that can be locked by one thread to exclude other threads until it is unlocked.

class CXlLockable

Overview

The CXlLockable class can be used to lock an object for thread-safe access.

The object methods Lock an Unlock are used to control access to the object. Once a thread has successfully locked the object, the same thread may apply further locks without restriction. When an equal number of unlocks are applied, the object becomes available for other threads to use.

If a thread calls Lock while the object is already locked by another thread, then the first thread will wait until the object is unlocked.

CXlLock

The most convenient way to lock the object is by using a CXlLock object. CXlLock calls CXlLockable::Lock() when it is constructed, and calls CXlLockable::Unlock() when it is destroyed.

A typical usage is shown below.

CopyC++
CXlLockable sharedObject;
void UseSharedObject()
{
    CXlLock lock(sharedObject, true);
    // Do something with the sharedObject
    // On exit from this function, the CXlLock instance will
    // be destroyed, and sharedObject will be unlocked
}

Implementation

The CXlLocakable class is implemented as a thin layer on top of the Windows CRITICALSECTION object. The API calls for each of the class methods are listed below.

Method | API call
Constructor | InitializeCriticalSection
Destructor | DeleteCriticalSection
Lock | EnterCriticalSection
Unlock | LeaveCriticalSection

Requirements

Header: xlpshared.h

See Also

CXlLockable Methods | xlpshared.h | Ensuring global data is thread-safe | CXlLock


CXlLockable Methods

The methods of the CXlLockable class are listed here.

Construction

public method CXlLockable Constructs a CXlLockable object without locking it

Public methods

public method | Lock | Locks a shared object
public method | Unlock | Unlocks a shared object

Requirements

Header: xlpshared.h

See Also

CXlLockable Class | xlpshared.h | Ensuring global data is thread-safe | CXlLock


CXlLockable::CXlLockable

Constructs a CXlLockable object without locking it

CXlLockable( );

Remarks

This method constructs a CXlLockable object. It will not be locked until the Lock() method has been called.

Requirements

Header: xlpshared.h

See Also

CXlLockable Class | CXlLockable Methods


CXlLockable::Lock

Locks a shared object

bool Lock( );

Return Value

Returns true if the CXlLockable has been initialized; returns false if the CXlLockable has no been prepared for use. A return value of false indicates a fatal error.

Requirements

Header: xlpshared.h

See Also

CXlLockable Class | CXlLockable Methods


CXlLockable::Unlock

Unlocks a shared object

void Unlock( );

Remarks

This method unlocks an object previously locked using Lock(). Each call to Lock() from a particular thread requires a matching call to Unlock() before the object becomes available to other threads.

Requirements

Header: xlpshared.h

See Also

CXlLockable Class | CXlLockable Methods


xlpstatehelpers.h

Overview

xlpstatehelpers.h contains classes which control and maintain Excel's state across macro operations.

All the classes follow a similar pattern. They each save the state of an Excel property when they are constructed, and restore it when they are destroyed. They can thus be instantiated as local variables before operations that may change the state of the property, and the state will be restored at the end of the function, when the object goes out of scope.

Classes

The table below lists the classes declared in the header file.

Class | Description
CXlSuspendAutoRecalculation | Sets Calculation to Manual, and restores it to its previous value on destruction.
CXlSuspendEcho | Suspends update of Excel's display, and restores it on destruction of all instances.
CXlSuspendError | Suspends the display of Excel's alert dialogs, and restores it on destruction of all instances.
CXlActiveCellRestorer | Saves and restores the active cell in a worksheet.
CXlActiveSheetRestorer | Saves and restores the active sheet in a workbook.
CXlActiveBookRestorer | Saves and restores the active workbook in an application.


CXlActiveBookRestorer Class

Saves and restores the active workbook.

class CXlActiveBookRestorer

Overview

Use this class to restore the active workbook after operations that may change the active workbook.

On construction, the object will save the name of the active workbook, and on destruction, it will attempt to select the active workbook.

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveBookRestorer Methods | xlpstatehelpers.h


CXlActiveBookRestorer Methods

The methods of the CXlActiveBookRestorer class are listed here.

Construction

public method CXlActiveBookRestorer Constructs a CXlActiveBookRestorer object

Operations

public method | Restore | Restores the active workbook.
public method | Save | Saves the active workbook.

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveBookRestorer Class | xlpstatehelpers.h


CXlActiveBookRestorer::CXlActiveBookRestorer

Constructs a CXlActiveBookRestorer object

CXlActiveBookRestorer(
   bool saveNow = true
);

Parameters

saveNow

If set to false, then this object will not save the active book, nor will it restore it on destruction unless Save has been called in the meantime.

If true, then the object will save the active book during construction, and will restore it at destruction.

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveBookRestorer Class | CXlActiveBookRestorer Methods


CXlActiveBookRestorer::Restore

Restores the active workbook.

void Restore( );

Remarks

This method is called during destruction, if Save was previously called.

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveBookRestorer Class | CXlActiveBookRestorer Methods


CXlActiveBookRestorer::Save

Saves the active workbook.

void Save( );

Remarks

This method is called during construction (if the saveNow parameter is set to true, or is omitted).

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveBookRestorer Class | CXlActiveBookRestorer Methods


CXlActiveCellRestorer Class

Saves and restores the active cell in a worksheet.

class CXlActiveCellRestorer

Overview

Use this class to restore the active cell of a worksheet after operations that may change the active cell.

On construction, the object will save the active cell, and on destruction, it will restore the active cell.

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveCellRestorer Methods | xlpstatehelpers.h


CXlActiveCellRestorer Methods

The methods of the CXlActiveCellRestorer class are listed here.

Construction

public method CXlActiveCellRestorer Constructs a CXlActiveCellRestorer object

Operations

public method | Restore | Restores the active cell of the active worksheet.
public method | Save | Saves the active cell of the active worksheet.

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveCellRestorer Class | xlpstatehelpers.h


CXlActiveCellRestorer::CXlActiveCellRestorer

Constructs a CXlActiveCellRestorer object

CXlActiveCellRestorer(
   bool saveNow = true
);

Parameters

saveNow

If set to false, then this object will not save the active cell, nor will it restore it on destruction unless Save has been called in the meantime.

If true, then the object will save the active cell during construction, and will restore it at destruction.

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveCellRestorer Class | CXlActiveCellRestorer Methods


CXlActiveCellRestorer::Restore

Restores the active cell of the active worksheet.

void Restore( );

Remarks

This method is called during destruction, if Save was previously called.

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveCellRestorer Class | CXlActiveCellRestorer Methods


CXlActiveCellRestorer::Save

Saves the active cell of the active worksheet.

void Save( );

Remarks

This method is called during construction (if the saveNow parameter is set to true, or is omitted).

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveCellRestorer Class | CXlActiveCellRestorer Methods


CXlActiveSheetRestorer Class

Saves and restores the active cell in a worksheet.

class CXlActiveSheetRestorer

Overview

Use this class to restore the active sheet of a workbook after operations that may change the active sheet.

On construction, the object will save the active sheet, and on destruction, it will restore the active sheet.

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveSheetRestorer Methods | xlpstatehelpers.h


CXlActiveSheetRestorer Methods

The methods of the CXlActiveSheetRestorer class are listed here.

Construction

public method CXlActiveSheetRestorer Constructs a CXlActiveSheetRestorer object

Operations

public method | Restore | Restores the active sheet of the workbook.
public method | Save | Saves the active sheet of the workbook.

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveSheetRestorer Class | xlpstatehelpers.h


CXlActiveSheetRestorer::CXlActiveSheetRestorer

Constructs a CXlActiveSheetRestorer object

CXlActiveSheetRestorer(
   bool saveNow = true
);
CXlActiveSheetRestorer(
   const char* workbookName,
   bool saveNow = true
);
CXlActiveSheetRestorer(
   const wchar_t* workbookName,
   bool saveNow = true
);

Parameters

saveNow

If set to false, then this object will not save the active sheet, nor will it restore it on destruction unless Save has been called in the meantime.

If true, then the object will save the active sheet during construction, and will restore it at destruction.
workbookName

The name of the workbook whose state is to be saved and restored. If omitted, then the name of the active workbook will be used.

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveSheetRestorer Class | CXlActiveSheetRestorer Methods


CXlActiveSheetRestorer::Restore

Restores the active sheet of the workbook.

void Restore( );

Remarks

This method is called during destruction, if Save was previously called.

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveSheetRestorer Class | CXlActiveSheetRestorer Methods


CXlActiveSheetRestorer::Save

Saves the active sheet of the workbook.

void Save( );

Remarks

This method is called during construction (if the saveNow parameter is set to true, or is omitted).

Requirements

Header: xlpstatehelpers.h

See Also

CXlActiveSheetRestorer Class | CXlActiveSheetRestorer Methods


CXlSuspendAutoRecalculation Class

Sets Calculation to Manual, and restores it to its previous value on destruction.

class CXlSuspendAutoRecalculation

Overview

Use this class to switch off automatic recalculation before making multiple changes to a workbook, and to switch calculation back to automatic when the changes are complete.

Requirements

Header: xlpstatehelpers.h

See Also

CXlSuspendAutoRecalculation Methods | xlpstatehelpers.h


CXlSuspendAutoRecalculation Methods

The methods of the CXlSuspendAutoRecalculation class are listed here.

Construction

public method CXlSuspendAutoRecalculation Constructs a CXlSuspendAutoRecalculation object

Operations

public method | Restore | Sets Excel's calculation mode to manual, and saves the current calculation mode.
public method | Save | Sets Excel's calculation mode to manual, and saves the current calculation mode.

Requirements

Header: xlpstatehelpers.h

See Also

CXlSuspendAutoRecalculation Class | xlpstatehelpers.h


CXlSuspendAutoRecalculation::CXlSuspendAutoRecalculation

Constructs a CXlSuspendAutoRecalculation object

CXlSuspendAutoRecalculation(
   bool suspend = true
);

Parameters

suspend

If set to false, then this object will not change the calculation mode, nor will it restore it on destruction unless Save has been called in the meantime.

If true, then the object will set Excel's calculation mode to manual (if necessary) during construction, and will restore it at destruction.

Requirements

Header: xlpstatehelpers.h

See Also

CXlSuspendAutoRecalculation Class | CXlSuspendAutoRecalculation Methods


CXlSuspendAutoRecalculation::Restore

Sets Excel's calculation mode to manual, and saves the current calculation mode.

void Restore( );

Remarks

This method is called during destruction, if Save was previously called.

Requirements

Header: xlpstatehelpers.h

See Also

CXlSuspendAutoRecalculation Class | CXlSuspendAutoRecalculation Methods


CXlSuspendAutoRecalculation::Save

Sets Excel's calculation mode to manual, and saves the current calculation mode.

void Save( );

Remarks

This method is called during construction (if the suspend parameter is set to true, or is omitted).

Requirements

Header: xlpstatehelpers.h

See Also

CXlSuspendAutoRecalculation Class | CXlSuspendAutoRecalculation Methods


CXlSuspendEcho Class

Sets Echo to false, and restores it to true when all instances are destroyed.

class CXlSuspendEcho

Overview

Use this class to switch off screen updating during macro operations. Screen updating will be restored when the object is destroyed.

If more than one instance of CXlSuspendEcho exists, then screen updating will only be restored when the last one goes out of scope. It is thus possible to declare a local instance of CXlSuspendEcho in one function, and another one in a function called by the first function. In this case the second instance will effectively be ignored, and screen updating will only be restored when the outermost instance is destroyed.

Requirements

Header: xlpstatehelpers.h

See Also

CXlSuspendEcho Methods | xlpstatehelpers.h


CXlSuspendEcho Methods

The methods of the CXlSuspendEcho class are listed here.

Construction

public method CXlSuspendEcho Constructs a CXlSuspendEcho object

Requirements

Header: xlpstatehelpers.h

See Also

CXlSuspendEcho Class | xlpstatehelpers.h


CXlSuspendEcho::CXlSuspendEcho

Constructs a CXlSuspendEcho object

CXlSuspendEcho(
   bool suspend = true
);

Parameters

suspend

If set to false, then this object will not affect the echo setting.

If true, then the object will set Excel's echo mode to false (if necessary) during construction, and will restore it at destruction, if all other instances of CXlSuspendEcho have been destroyed.

Requirements

Header: xlpstatehelpers.h

See Also

CXlSuspendEcho Class | CXlSuspendEcho Methods


CXlSuspendError Class

Sets Error to false, and restores it to true when all instances are destroyed. Error is the equivalent of Application.DisplayAlerts in VBA.

class CXlSuspendError

Overview

Use this class to switch off the display of alert dialogs during macro operations. Alerts will be restored when the object is destroyed.

If more than one instance of CXlSuspendError exists, then alerts will only be restored when the last one goes out of scope. It is thus possible to declare a local instance of CXlSuspendError in one function, and another one in a function called by the first function. In this case the second instance will effectively be ignored, and screen updating will only be restored when the outermost instance is destroyed.

Requirements

Header: xlpstatehelpers.h

See Also

CXlSuspendError Methods | xlpstatehelpers.h


CXlSuspendError Methods

The methods of the CXlSuspendError class are listed here.

Construction

public method CXlSuspendError Constructs a CXlSuspendError object

Requirements

Header: xlpstatehelpers.h

See Also

CXlSuspendError Class | xlpstatehelpers.h


CXlSuspendError::CXlSuspendError

Constructs a CXlSuspendError object

CXlSuspendError(
   bool suspend = true
);

Parameters

suspend

If set to false, then this object will not affect the error setting.

If true, then the object will set Excel's error mode to false (if necessary) during construction, and will restore it at destruction, if all other instances of CXlSuspendError have been destroyed.

Requirements

Header: xlpstatehelpers.h

See Also

CXlSuspendError Class | CXlSuspendError Methods


xlpstringarg.h

Overview

xlpstringarg.h contains a class that handles string arguments passed from Excel.

For details on how to use the class see CXlStringArg Object overview

The file is automatically included when the AppWizard creates the XLL+ project.

Classes

Class | Description
CXlStringArg | A class which holds string arguments passed by Excel.

See Also

CXlStringArg object | String arguments


CXlStringArg Class

Holds a string argument passed from Excel.

class CXlStringArg

Overview

A CXlStringArg represents a string passed to an add-in function by Excel.

If your add-in is designed to support both Excel 2007 and earlier versions of Excel, then you cannot tell in advance whether the string will be an ANSI string (Excel 2003 and below) or a Unicode string (Excel 2007 and above).

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Methods | xlpstringarg.h | CString


CXlStringArg Methods

The methods of the CXlStringArg class are listed here.

Construction

public method CXlStringArg Constructs a CXlStringArg object

Assignment operators

public method operator = Assigns a new value to the CXlArgString

Accessors

public method | GetCharPtr | Gets a pointer to a read-only character buffer
public method | GetCharPtrA | Gets a pointer to a read-only narrow character buffer
public method | GetCharPtrW | Gets a pointer to a read-only wide character buffer
public method | GetStlString | Gets an STL string
public method | GetStlStringA | Gets an STL ANSI string
public method | GetStlStringW | Gets an STL wide string
public method | GetString | Gets a string value
public method | GetStringA | Gets an ANSI string value
public method | GetStringW | Gets a Unicode string value

Output casting operators

public method | operator bool | Returns true if the string is not null, false is the string is null
public method | operator const char* | Returns a pointer to a read-only text buffer
public method | operator const wchar_t* | Returns a pointer to a read-only text buffer

State

public method | HasNarrowString | Returns whether the object contains an ANSI string
public method | HasWideString | Returns whether the object contains a Unicode string

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | xlpstringarg.h | CString


CXlStringArg::CXlStringArg

Constructs a CXlStringArg object

CXlStringArg( );
CXlStringArg(
   const wchar_t* wptr
);
CXlStringArg(
   const char* sptr
);
CXlStringArg(
   const CXlStringArg& source
);

Parameters

wptr

Pointer to a Unicode (wide) string.
sptr

Pointer to an ANSI (narrow) string.
source

An existing CXlStringArg object, which will be copied.

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods


CXlStringArg::GetCharPtr

Gets a pointer to a read-only character buffer

const TCHAR* GetCharPtr( ) const;

Return Value

Returns a pointer to a character buffer. The character size depends on whether the Unicode build settings are used. In Unicode builds, TCHAR is defined as wchar_t. In standard builds, TCHAR is defined as char.

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods | CXlStringArg::GetCharPtrA() | CXlStringArg::GetCharPtrW()


CXlStringArg::GetCharPtrA

Gets a pointer to a read-only narrow character buffer

const char* GetCharPtrA( ) const;

Return Value

Returns a pointer to a read-only character buffer. The character size will always be char (8-bit).

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods | CXlStringArg::GetCharPtr() | CXlStringArg::GetCharPtrW()


CXlStringArg::GetCharPtrW

Gets a pointer to a read-only wide character buffer

const wchar_t* GetCharPtrW( ) const;

Return Value

Returns a pointer to a read-only Unicode character buffer. The character size will always be wchar_t (16-bit).

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods | CXlStringArg::GetCharPtr() | CXlStringArg::GetCharPtrA()


CXlStringArg::GetStlString

Gets an STL string

std::tstring GetStlString( ) const;

Return Value

Returns an STL string type. The character size depends on whether the Unicode build settings are used. In Unicode builds, std::tstring is equivalent to std::wstring. In standard builds, std::tstring is equivalent to std::string.

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods | CXlStringArg::GetStlStringA() | CXlStringArg::GetStlStringW()


CXlStringArg::GetStlStringA

Gets an STL ANSI string

std::string GetStlStringA( ) const;

Return Value

Returns an STL string type. The character size will always be char (8-bit).

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods | CXlStringArg::GetStlString() | CXlStringArg::GetStlStringW()


CXlStringArg::GetStlStringW

Gets an STL wide string

std::wstring GetStlStringW( ) const;

Return Value

Returns an STL string type. The character size will always be wchar_t (16-bit).

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods | CXlStringArg::GetStlString() | CXlStringArg::GetStlStringA()


CXlStringArg::GetString

Gets a string value

CString GetString( ) const;

Return Value

Returns a string object. The character size depends on whether the Unicode build settings are used. In Unicode builds, CString is equivalent to CStringW. In standard builds, CString is equivalent to CStringA.

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods | CXlStringArg::GetStringA() | CXlStringArg::GetStringW()


CXlStringArg::GetStringA

Gets an ANSI string value

CStringA GetStringA( ) const;

Return Value

Returns a string object. The character size is always char (8-bit).

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods | CXlStringArg::GetString() | CXlStringArg::GetStringW()


CXlStringArg::GetStringW

Gets a Unicode string value

CStringW GetStringW( ) const;

Return Value

Returns a string object. The character size is always wchar_t (16-bit).

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods | CXlStringArg::GetString() | CXlStringArg::GetStringA()


CXlStringArg::HasNarrowString

Returns whether the object contains an ANSI string

bool HasNarrowString( ) const;

Return Value

This function returns true if the object currently contains an ANSI string.

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods


CXlStringArg::HasWideString

Returns whether the object contains a Unicode string

bool HasWideString( ) const;

Return Value

This function returns true if the object currently contains a Unicode string.

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods


CXlStringArg::operator =

Assigns a new value to the CXlArgString

const CXlStringArg& operator =(
   const CXlStringArg& source
);
const CXlStringArg& operator =(
   std::string& str
);
const CXlStringArg& operator =(
   std::wstring& wstr
);
const CXlStringArg& operator =(
   const char* psz
);
const CXlStringArg& operator =(
   const wchar_t* wpsz
);

Parameters

source

An initialised CXlStringArg, whose contents will be copied to this object.

str

A reference to an STL string.

wstr

A reference to an STL wide string.

psz

A pointer to an array of ANSI characters.

wpsz

A pointer to an array of Unicode characters.

Remarks

These operators assign a new value to CXlStringArg object. If the item already contains data, then it will be appropriately cleared before the assignment.

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods


CXlStringArg::operator bool

Returns true if the string is not null, false is the string is null

operator bool( ) const;

Return Value

This function returns a boolean value indicating whether the string is not null or null. It allows the CXlStringArg object to be used in C++ boolean constructs in the same way as string pointers:

CopyC++
CXlStringArg s;
const char* t = s ? s : "Default";

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods


CXlStringArg::operator const char*

Returns a pointer to a read-only text buffer

operator const char*( ) const;

Return Value

This function returns a pointer to a read-only buffer containing an 8-bit (char) string version of the CXlStringArg's value.

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods


CXlStringArg::operator const wchar_t*

Returns a pointer to a read-only text buffer

operator const wchar_t*( ) const;

Return Value

This function returns a pointer to a read-only buffer containing a 16-bit (wchar_t) string version of the CXlStringArg's value.

Requirements

Header: xlpstringarg.h

See Also

CXlStringArg Class | CXlStringArg Methods


xlserialize.h

Overview

xlserialize.h contains classes that allow you to convert Excel argument and result types to and from a byte array.

This behavior is useful for several reasons:

  1. Cacheing results. The byte array can be used as an efficient key to a map. This means you can very easily cache the results of an add-in function in a map keyed by its inputs. The CXlOperCache class implements this behavior.
  2. Persistence. A byte array can be saved to file explicitly, or can be saved as binary data with any worksheet. You can use the CXllApp::SaveBinaryData() method with CXlSerialData to save hidden data in worksheets.
  3. Messaging. The byte array can be passed along pipes or other simple channels, between threads, processes or machines.

Classes

Class | Description
CXlOStream | A stream wrapper that allows the output of Excel native types to STL output streams.
CXlOStrStream | A class that converts Excel native types to in-memory byte arrays.
CXlIStream | A stream wrapper that allows the input of Excel native types from STL input streams.
CXlIStrStream | A class that reads Excel native types from in-memory byte arrays.
CXlSerialData | A byte array containing native and Excel data types.
CXlInputKey | A specialised instance of serialized data, which contains all the inputs to an add-in function, as a byte array.
CXlOperCache | A data store holding the results of functions, keyed by the values of all inputs.
CXlCacheBinding | A connection between a function and a cache that automatically updates the cache as the function exits.

See Also

CXlSerialData object | CXlInputKey object | CXlOperCache object | xldialog.h | Cache sample | Serialize sample


CXlCacheBinding<C> Class

Sets up a connection between a cache and an add-in function.

class CXlCacheBinding<C>

Overview

The CXlCacheBinding template class sets up a connection between a cache and an add-in function. If a record matching the current function's arguments if not found, then the CXlCacheBinding object puts the result of the function into the cache automatically when the function exits.

This behavior removes the need for the programmer to call CXlOperCache::Add(), and makes it possible for the XLL+ Function Wizard to control cacheing completely.

The class is implemented inline in xlserialize.h

Sample applications

You can find a sample using the CXlOperCache class below:

  • AvgOpt sample

Requirements

Header: xlserialize.h

See Also

CXlCacheBinding<C> Methods | xlserialize.h | CXlOperCache class | CXlInputKey class | CXlSerialData class | Cache sample


CXlCacheBinding<C> Methods

The methods of the CXlCacheBinding<C> class are listed here.

Construction

public method | ~CXlCacheBinding | Destroys a CXlOperCache object
public method | CXlCacheBinding | Constructs a CXlOperCache object

Operations

public method | Find | Searches the cache for the result of a previous calculation
public method | Ret | Returns a pointer to the stored result

Requirements

Header: xlserialize.h

See Also

CXlCacheBinding<C> Class | xlserialize.h | CXlOperCache class | CXlInputKey class | CXlSerialData class | Cache sample


CXlCacheBinding<C>::~CXlCacheBinding

Destroys a CXlOperCache object

~CXlCacheBinding( );

Remarks

When an active CXlCacheBinding object is destroyed, the m_bAdd flag is checked. If it is true, then the contents of the CXlOper::RetVal() buffer is put into the cache just before the function exits. If the CXlCacheBinding::Ret() method has been called, then m_bAdd will be false, and the cache will not be updated.

Requirements

Header: xlserialize.h

See Also

CXlCacheBinding<C> Class | CXlCacheBinding<C> Methods


CXlCacheBinding<C>::CXlCacheBinding

Constructs a CXlOperCache object

CXlCacheBinding(
   C& cache,
   CXlOper& xloResult,
   const char* pszFnName,
   void* pvFirstArg,
   bool bPrefixFn = false
);

Parameters

cache

A reference to a cache object. If the cache object is not descended from CXlOperCache, then it is expected to support the Find() and Add() methods.

xloResult

This CXlOper object will be populated by the cached result, if a matching record for the key is found in the cache.
pszFnName

Name of add-in function whose arguments are being converted to a byte array.
pvFirstArg

Address of the first argument to the add-in function. This pointer is used to traverse the argument stack, using the add-in function's registered definition to interpret the items in the stack.
bPrefixFn

If true, the name of the function will be prefixed to the byte array. This is useful if a single cache is used for more than one add-in function. If false, then the function is not prefixed. This is appropriate if each add-in function uses its own cache.

Remarks

This method constructs an active CXlCacheBinding object. There should never be more than one active CXlCacheBinding object in the immediate scope of any one add-in function.

Requirements

Header: xlserialize.h

See Also

CXlCacheBinding<C> Class | CXlCacheBinding<C> Methods


CXlCacheBinding<C>::Find

Searches the cache for the result of a previous calculation

bool Find( ) const;

Return Value

Returns true if a matching record is found, in which case the CXlOper passed in the constructor is populated with a copy of the stored result. Returns false if no record is found that matches the supplied key; in this case, the referenced CXlOper is unchanged.

Requirements

Header: xlserialize.h

See Also

CXlCacheBinding<C> Class | CXlCacheBinding<C> Methods


CXlCacheBinding<C>::Ret

Returns a pointer to the stored result

LPXLOPER Ret( );

Remarks

This method returns a pointer to the result stored in the cache, in a form ready to be returned to Excel. It can be used in place of CXlOper::Ret().

Requirements

Header: xlserialize.h

See Also

CXlCacheBinding<C> Class | CXlCacheBinding<C> Methods


CXlInputKey Class

Converts all of an add-in function's arguments to and from a single continuous byte array.

class CXlInputKey : public CXlSerialData

Overview

The CXlInputKey class can be used to convert all of an add-in function's arguments to and from a single continuous byte array.

The byte array can than be used as an efficient key to a map. This means you can very easily cache the results of an add-in function in a map keyed by its inputs. The CXlOperCache class uses the CXlInputKey class for this purpose.

Requirements

Header: xlserialize.h

See Also

CXlInputKey Methods | xlserialize.h | CXlOperCache class | CXlSerialData class | CXlCacheBinding class<C> | Cache sample


CXlInputKey Methods

The methods of the CXlInputKey class are listed here.

Construction

public method CXlInputKey Constructs a CXlInputKey object

Assignment operators

public method operator = Assigns a new value to the byte array

Methods of CXlSerialData

Requirements

Header: xlserialize.h

See Also

CXlInputKey Class | xlserialize.h | CXlOperCache class | CXlSerialData class | CXlCacheBinding class<C> | Cache sample


CXlInputKey::CXlInputKey

Constructs a CXlInputKey object

CXlInputKey( );
CXlInputKey(
   const char* pszFnName,
   void* pvFirstArg,
   bool bPrefixFn = false,
   int nOmitArgs = 0
);
CXlInputKey(
   void* pvData,
   size_t cbData
);
CXlInputKey(
   const CXlInputKey& srcKey
);

Parameters

pszFnName

Name of add-in function whose arguments are being converted to a byte array.
pvFirstArg

Address of the first argument to the add-in function. This pointer is used to traverse the argument stack, using the add-in function's registered definition to interpret the items in the stack.
bPrefixFn

If true, the name of the function will be prefixed to the byte array. This is useful if a single cache is used for more than one add-in function. If false, then the function is not prefixed. This is appropriate if each add-in function uses its own cache.
nOmitArgs

If non-zero, this instructs the serializer to omit the last nOmitArgs arguments in the list.
pvData

A pointer to an array of bytes, of size cbData.
cbData

A pointer to an array of bytes, of size cbData.
srcKey

An object to be deep copied.

Remarks

This method constructs a CXlInputKey object.

Requirements

Header: xlserialize.h

See Also

CXlInputKey Class | CXlInputKey Methods


CXlInputKey::operator =

Assigns a new value to the byte array

const CXlInputKey& operator =(
   const CXlInputKey& srcKey
);

Parameters

srcKey

A CXlInputKey object that will be deep-copied to *this.

Requirements

Header: xlserialize.h

See Also

CXlInputKey Class | CXlInputKey Methods


CXlIStream Class

Serializes data from STL streams to native Excel data.

class CXlIStream

Overview

The CXlIStream class reads serializes data from STL streams to native Excel data. You can find an example of its use in the Serialize sample.

Requirements

Header: xlserialize.h

See Also

CXlIStream Methods | xlserialize.h | CXlIStrStream class | CXlOStream class | CXlOStrStream class | CXlOperCache class | CXlInputKey class | CXlSerialData class | Serialize sample


CXlIStream Methods

The methods of the CXlIStream class are listed here.

Construction

public method CXlIStream Constructs a CXlIStream object

Input operators

public method operator >> Reads a serialized value from the input stream

Input methods

public method ReadByteArray Reads a byte array from the input stream

Requirements

Header: xlserialize.h

See Also

CXlIStream Class | xlserialize.h | CXlIStrStream class | CXlOStream class | CXlOStrStream class | CXlOperCache class | CXlInputKey class | CXlSerialData class | Serialize sample


CXlIStream::CXlIStream

Constructs a CXlIStream object

CXlIStream(
   std::istream& inner
);

Parameters

inner

An initialized, open STL input stream.

Remarks

This method constructs a CXlIStream object, which will read serialized data from the inner istream.

Requirements

Header: xlserialize.h

See Also

CXlIStream Class | CXlIStream Methods


CXlIStream::operator >>

Reads a serialized value from the input stream

CXlIStream& operator >>(
   double& dval
);
CXlIStream& operator >>(
   short int& sval
);
CXlIStream& operator >>(
   unsigned short& usval
);
CXlIStream& operator >>(
   int& ival
);
CXlIStream& operator >>(
   long& lval
);
CXlIStream& operator >>(
   bool& bval
);
CXlIStream& operator >>(
   std::string& strval
);
CXlIStream& operator >>(
   CString& cstrval
);
CXlIStream& operator >>(
   CXlOper& xloval
);
CXlIStream& operator >>(
   COper& opval
);
CXlIStream& operator >>(
   CXlArray& xlaval
);

Parameters

dval

A reference to a numeric value which will be read from the input stream.
sval

A reference to a numeric value which will be read from the input stream.
usval

A reference to a numeric value which will be read from the input stream.
ival

A reference to a numeric value which will be read from the input stream.
lval

A reference to a numeric value which will be read from the input stream.
bval

A reference to a boolean value which will be read from the input stream.
strval

A reference to a string which will be read from the input stream.
cstrval

A reference to a string which will be read from the input stream.
xloval

A reference to a CXlOper object which will be read from the input stream.
opval

A reference to a COper object which will be read from the input stream.
xlaval

A reference to a CXlArray object which will be read from the input stream.

Requirements

Header: xlserialize.h

See Also

CXlIStream Class | CXlIStream Methods


CXlIStream::ReadByteArray

Reads a byte array from the input stream

size_t ReadByteArray(
   char*& byteArray
);

Parameters

byteArray

A reference to a pointer which will be set to a new array of characters, containing the stored byte array. The array will be of the size returned by the function.

Return Value

The function returns the number if bytes in the restored byte array, or 0 if the function failed.

Remarks

If the function succeeds, and byteArray is set to a non-null value, it must be released after use:

CopyC++
if (byteArray)
    delete[] byteArray;

Requirements

Header: xlserialize.h

See Also

CXlIStream Class | CXlIStream Methods | CXlOStream::WriteByteArray


CXlIStrStream Class

Serializes data from STL memory streams to native Excel data.

class CXlIStrStream : public CXlIStream

Overview

The CXlIStrStream class is a specialized class derived from CXlIStream. It contains its own inner stream, which is of type std::istrstream, i.e. a stream that controls an array bytes in of memory. The class thus represents both the conversion method for data to be deserialized and also the byte array from which the data is deserialized.

Requirements

Header: xlserialize.h

See Also

CXlIStrStream Methods | xlserialize.h | CXlIStream class | CXlOStrStream class | CXlOStream class | CXlOperCache class | CXlInputKey class | CXlSerialData class | Serialize sample


CXlIStrStream Methods

The methods of the CXlIStrStream class are listed here.

Construction

public method CXlIStrStream Constructs a CXlIStrStream object

Methods of CXlIStream

Requirements

Header: xlserialize.h

See Also

CXlIStrStream Class | xlserialize.h | CXlIStream class | CXlOStrStream class | CXlOStream class | CXlOperCache class | CXlInputKey class | CXlSerialData class | Serialize sample


CXlIStrStream::CXlIStrStream

Constructs a CXlIStrStream object

CXlIStrStream(
   void* p,
   size_t cb
);

Parameters

p

A pointer to a byte array (of size cb) which contains serialized data.
cb

The size of a byte array which contains serialized data.

Remarks

This method constructs a CXlIStrStream object, which will read serialized data from its inner istrstream.

Requirements

Header: xlserialize.h

See Also

CXlIStrStream Class | CXlIStrStream Methods


CXlOperCache Class

Stores the results of any add-in function in a map keyed by the collection of all inputs to the add-in function.

class CXlOperCache

Overview

The CXlOperCache class can be used to store the results of any add-in function in a map keyed by the collection of all inputs to the add-in function.

This behavior can greatly improve add-in function performance, since functions are calculated only once for any given set of inputs, however many times they are requested. Since Excel often asks the same question many times, recalculating cells whose inuts have not changed, the impact of a cache on the performance of a relatively expensive add-in function can be considerable.

Using the cache

You can make your add-in function use the cache in one easy step with the XLL+ Function Wizard: when you create the function, check the Cache results feature on the Features tab.

Code will be generated in the wrapper functions which inspects the cache and returns if a result is found. Just before the function exits, the cache will be updated automatically with the function's return value.

Persistence

You can save the cache to disk when the XLL closes and restore it each time the XLL is opened.

You should implement the OnXllOpenEx() and OnXllClose() overrideable methods of the application class, to restore and save the cache.

The code below shows how to do this:

CopyC++
BOOL CAvgOptApp::OnXllOpenEx()
{
    // Restore cache
    if (CXlOperCache::GetUserCacheFilePath(m_strCacheFile))
        m_cache.Restore(m_strCacheFile);

    return TRUE;
}

void CAvgOptApp::OnXllClose()
{
    m_cache.Save(m_strCacheFile);
}

Sample applications

You can find a sample using the CXlCacheBinding class below:

  • AvgOpt sample

Requirements

Header: xlserialize.h

See Also

CXlOperCache Methods | xlserialize.h | CXlCacheBinding class<C> | CXlInputKey class | CXlSerialData class | Cache sample | Function property: CacheResults


CXlOperCache Methods

The methods of the CXlOperCache class are listed here.

Construction

public method CXlOperCache Constructs a CXlOperCache object

Operations

public method | Add | Adds a result to the cache, with a key composed of all the arguments to the function
public method | Clear | Clears the entire contents of the cache
public method | Find | Searches the cache for the result of a previous calculation
public method | Set | Sets a result in the cache, with a key composed of all the arguments to the function

Cache size methods

public method | GetMaxSize | Returns the number of records in the cache
public method | ReduceSize | Reduces cache size by removing records from the cache that have not been recently used
public method | SetMaxSize | Returns the number of records in the cache

Persistence

 | GetUserCacheFilePath | Get the default location for the cache file
public method | Restore | Restore the contents of the cache from a file
public method | Save | Save the contents of the cache to a file

Requirements

Header: xlserialize.h

See Also

CXlOperCache Class | xlserialize.h | CXlCacheBinding class<C> | CXlInputKey class | CXlSerialData class | Cache sample | Function property: CacheResults


CXlOperCache::Add

Adds a result to the cache, with a key composed of all the arguments to the function

void Add(
   const CXlInputKey& key,
   const CXlOper& xloResult
);

Parameters

key

A populated CXlInputKey object, constructed from the arguments of the current add-in function (optionally including the function name).
xloResult

The result of the calculation, which may contain a value, an error, an array or any other value type.

Requirements

Header: xlserialize.h

See Also

CXlOperCache Class | CXlOperCache Methods


CXlOperCache::Clear

Clears the entire contents of the cache

void Clear( );

Remarks

This function clears the entire contents of the cache.

Requirements

Header: xlserialize.h

See Also

CXlOperCache Class | CXlOperCache Methods


CXlOperCache::CXlOperCache

Constructs a CXlOperCache object

CXlOperCache( );

Remarks

This method constructs an empty CXlOperCache object.

Requirements

Header: xlserialize.h

See Also

CXlOperCache Class | CXlOperCache Methods


CXlOperCache::Find

Searches the cache for the result of a previous calculation

bool Find(
   const CXlInputKey& key,
   CXlOper& xloResult
) const;

Parameters

key

A populated CXlInputKey object, constructed from the arguments of the current add-in function (optionally including the function name).
xloResult

This CXlOper object will be populated by the cached result, if a matching record for the key is found in the cache.

Return Value

Returns true if a matching record is found, in which case xloResult is populated with a copy of the stored result. Returns false if no record is found that matches the supplied key; in this case, xloResult is unchanged.

Requirements

Header: xlserialize.h

See Also

CXlOperCache Class | CXlOperCache Methods


CXlOperCache::GetMaxSize

Returns the number of records in the cache

size_t GetMaxSize( ) const;

Return Value

This method returns the number of records currently in the cache.

Requirements

Header: xlserialize.h

See Also

CXlOperCache Class | CXlOperCache Methods


CXlOperCache::GetUserCacheFilePath

Get the default location for the cache file

static bool GetUserCacheFilePath(
   CString& strPath
);

Parameters

strPath

If the function succeeds, this will contain the full path to the cache file.

Return Value

The fuction returns true if the operation was successful, or false it fails for any reason.

Remarks

This method is implemented inline in xlserialize.h so that it can easily be used as the basis for your own more sophisiticated implementations, such as a shared cache.

The standard implementation constructs a path %TMP%\[Add-in name].dat, e.g. %TMP%\MyAddin.dat, and expands it to a complete file path. This location allows the user read, create and write access to the file under almost all security configurations.

Requirements

Header: xlserialize.h

See Also

CXlOperCache Class | CXlOperCache Methods


CXlOperCache::ReduceSize

Reduces cache size by removing records from the cache that have not been recently used

virtual void ReduceSize( );

Remarks

This method is called just before the cache is added to and after the maximum cache size is changed.

The default implementation does nothing. If the method is implemented by a child class it should reduce cache size by removing records that have not been recently used.

Requirements

Header: xlserialize.h

See Also

CXlOperCache Class | CXlOperCache Methods


CXlOperCache::Restore

Restore the contents of the cache from a file

bool Restore(
   const CString& fileName
);

Parameters

fileName

The full path of a file. The file should have been written using CXlOperCache::Save.

Return Value

The fuction returns true if the operation was successful, or false it fails for any reason.

Note that the function is deemed to have succeeded if the file cannot be found.

Remarks

This method is implemented inline in xlserialize.h so that it can easily be used as the basis for your own more sophisiticated implementations, such as a shared cache.

Example

You can save the cache to disk when the XLL closes and restore it each time the XLL is opened.

You should implement the OnXllOpenEx() and OnXllClose() overrideable methods of the application class, to restore and save the cache.

The code below shows how to do this:

CopyC++
CAvgOptApp : public CXllApp {
    ...
    CString m_strCacheFile;
    ...
};

BOOL CAvgOptApp::OnXllOpenEx()
{
    // Restore cache
    if (CXlOperCache::GetUserCacheFilePath(m_strCacheFile))
        m_cache.Restore(m_strCacheFile);

    return TRUE;
}

void CAvgOptApp::OnXllClose()
{
    m_cache.Save(m_strCacheFile);
}

Requirements

Header: xlserialize.h

See Also

CXlOperCache Class | CXlOperCache Methods


CXlOperCache::Save

Save the contents of the cache to a file

bool Save(
   const CString& fileName
) const;

Parameters

fileName

The full path of a file. The file will be completely overwritten.

Return Value

The fuction returns true if the operation was successful, or false it fails for any reason.

Remarks

This method is implemented inline in xlserialize.h so that it can easily be used as the basis for your own more sophisiticated implementations, such as a shared cache.

Example

You can save the cache to disk when the XLL closes and restore it each time the XLL is opened.

You should implement the OnXllOpenEx() and OnXllClose() overrideable methods of the application class, to restore and save the cache.

The code below shows how to do this:

CopyC++
CAvgOptApp : public CXllApp {
    ...
    CString m_strCacheFile;
    ...
};

BOOL CAvgOptApp::OnXllOpenEx()
{
    // Restore cache
    if (CXlOperCache::GetUserCacheFilePath(m_strCacheFile))
        m_cache.Restore(m_strCacheFile);

    return TRUE;
}

void CAvgOptApp::OnXllClose()
{
    m_cache.Save(m_strCacheFile);
}

Requirements

Header: xlserialize.h

See Also

CXlOperCache Class | CXlOperCache Methods


CXlOperCache::Set

Sets a result in the cache, with a key composed of all the arguments to the function

void Set(
   const CXlInputKey& key,
   const CXlOper& xloResult
);

Parameters

key

A populated CXlInputKey object, constructed from the arguments of the current add-in function (optionally including the function name).
xloResult

The result of the calculation, which may contain a value, an error, an array or any other value type.

Requirements

Header: xlserialize.h

See Also

CXlOperCache Class | CXlOperCache Methods


CXlOperCache::SetMaxSize

Returns the number of records in the cache

size_t SetMaxSize(
   size_t newValue
);

Parameters

newValue

The new cache size.

Return Value

This method returns the number of records currently in the cache.

Remarks

This method changes the cache's maximum size and then calls ReduceSize() so that any excess records can be removed.

Requirements

Header: xlserialize.h

See Also

CXlOperCache Class | CXlOperCache Methods


CXlOStream Class

Serializes data native Excel data to STL streams.

class CXlOStream

Overview

The CXlOStream class serializes native Excel data to STL streams. You can find an example of its use in the Serialize sample.

Requirements

Header: xlserialize.h

See Also

CXlOStream Methods | xlserialize.h | CXlOStrStream class | CXlIStrStream class | CXlIStream class | CXlOperCache class | CXlInputKey class | CXlSerialData class | Serialize sample


CXlOStream Methods

The methods of the CXlOStream class are listed here.

Construction

public method CXlOStream Constructs a CXlOStream object

Output operators

public method operator << Writes a serialized value to the output stream

Data operations

public method | read_args | Serializes the arguments passed to an add-in function
public method | read_args_from_template | Serializes the arguments passed to an add-in function

Output methods

public method WriteByteArray Writes a byte array to the output stream

Requirements

Header: xlserialize.h

See Also

CXlOStream Class | xlserialize.h | CXlOStrStream class | CXlIStrStream class | CXlIStream class | CXlOperCache class | CXlInputKey class | CXlSerialData class | Serialize sample


CXlOStream::CXlOStream

Constructs a CXlOStream object

CXlOStream(
   std::ostream& inner
);

Parameters

inner

An initialized, open STL output stream.

Remarks

This method constructs a CXlOStream object, which will save serialized data to the inner ostream.

Requirements

Header: xlserialize.h

See Also

CXlOStream Class | CXlOStream Methods


CXlOStream::operator <<

Writes a serialized value to the output stream

CXlOStream& operator <<(
   double dval
);
CXlOStream& operator <<(
   short int sval
);
CXlOStream& operator <<(
   unsigned short usval
);
CXlOStream& operator <<(
   int ival
);
CXlOStream& operator <<(
   long lval
);
CXlOStream& operator <<(
   bool bval
);
CXlOStream& operator <<(
   const std::string& strval
);
CXlOStream& operator <<(
   const CString& cstrval
);
CXlOStream& operator <<(
   const char* pszval
);
CXlOStream& operator <<(
   const XLOPER* pxloval
);
CXlOStream& operator <<(
   const OPER* popval
);
CXlOStream& operator <<(
   const XLARRAY* pxlaval
);

Parameters

dval

A numeric value which will be written to the output stream.
sval

A numeric value which will be written to the output stream.
usval

A numeric value which will be written to the output stream.
ival

A numeric value which will be written to the output stream.
lval

A numeric value which will be written to the output stream.
bval

A boolean value which will be written to the output stream.
strval

A string value which will be written to the output stream.
cstrval

A string value which will be written to the output stream.
pszval

A string value which will be written to the output stream.
pxloval

A pointer to an XLOPER structure or CXlOper object which will be written to the output stream.
popval

A pointer to an OPER structure or COper object which will be written to the output stream.
pxlaval

A pointer to an XLARRAY structure or CXlArray object which will be written to the output stream.

Requirements

Header: xlserialize.h

See Also

CXlOStream Class | CXlOStream Methods


CXlOStream::read_args

Serializes the arguments passed to an add-in function

bool read_args(
   const char* fn_name,
   void* first_arg,
   int omit_args
);

Parameters

fn_name

The name of the add-in function being called.
first_arg

A pointer to the first argument passed to the function. (Further arguments will follow the first, according to the standard argument-packing pattern for __stdcall functions.)
omit_args

The index of the first argument which should be omitted from the serialization. If omit_args is -1, then it is ignored, and all passed arguments are serialized.

Return Value

Remarks

This function serializes the arguments passed by Excel to an add-in function, optionally omitting some terminal arguments.

The function looks up the definition of the function as it was declared and registered, and acquires the list of argument types (the signature) of the function. It uses the signature string to read sequentially through the arguments in the stack.

Requirements

Header: xlserialize.h

See Also

CXlOStream Class | CXlOStream Methods


CXlOStream::read_args_from_template

Serializes the arguments passed to an add-in function

bool read_args_from_template(
   void* first_arg,
   const char* arg_template,
   int omit_args
);

Parameters

first_arg

A pointer to the first argument passed to the function. (Further arguments will follow the first, according to the standard argument-packing pattern for __stdcall functions.)
arg_template

The function's argument string, which represents the data types of each of its arguments. This string is stored with the function definition when the argument is registered.
omit_args

The index of the first argument which should be omitted from the serialization. If omit_args is -1, then it is ignored, and all passed arguments are serialized.

Return Value

Remarks

This function serializes the arguments passed by Excel to an add-in function, optionally omitting some terminal arguments. The function uses the signature string to read sequentially through the arguments in the stack.

Requirements

Header: xlserialize.h

See Also

CXlOStream Class | CXlOStream Methods


CXlOStream::WriteByteArray

Writes a byte array to the output stream

void WriteByteArray(
   size_t len,
   char* byteArray
);

Parameters

len

The number of bytes contained in the byte array.

byteArray

A pointer to a byte array of size len.

Requirements

Header: xlserialize.h

See Also

CXlOStream Class | CXlOStream Methods | CXlIStream::ReadByteArray


CXlOStrStream Class

Serializes data native Excel data to STL memory streams.

class CXlOStrStream : public CXlOStream

Overview

The CXlOStrStream class is a specialized class derived from CXlOStream. It contains its own inner stream, which is of type std::ostrstream, i.e. a stream that controls an array bytes in of memory. The class thus represents both the conversion method for data to be serialized and also the byte array to which the data is serialized.

Requirements

Header: xlserialize.h

See Also

CXlOStrStream Methods | xlserialize.h | CXlOStream class | CXlIStrStream class | CXlIStream class | CXlOperCache class | CXlInputKey class | CXlSerialData class | Serialize sample


CXlOStrStream Methods

The methods of the CXlOStrStream class are listed here.

Construction

public method CXlOStrStream Constructs a CXlOStrStream object

Inspection functions

public method | pcount | Returns the size of the byte array to which data has been serialized
public method | str | Returns a pointer to the byte array to which data has been serialized

Methods of CXlOStream

Requirements

Header: xlserialize.h

See Also

CXlOStrStream Class | xlserialize.h | CXlOStream class | CXlIStrStream class | CXlIStream class | CXlOperCache class | CXlInputKey class | CXlSerialData class | Serialize sample


CXlOStrStream::CXlOStrStream

Constructs a CXlOStrStream object

CXlOStrStream( );

Remarks

This method constructs a CXlOStrStream object, which will save serialized data to its inner ostrstream.

Requirements

Header: xlserialize.h

See Also

CXlOStrStream Class | CXlOStrStream Methods


CXlOStrStream::pcount

Returns the size of the byte array to which data has been serialized

size_t pcount( );

Return Value

Remarks

This function returns the size of the byte array to which data has been serialized by the object.

A pointer to the array is returned by the str() function.

Requirements

Header: xlserialize.h

See Also

CXlOStrStream Class | CXlOStrStream Methods


CXlOStrStream::str

Returns a pointer to the byte array to which data has been serialized

char* str( );

Return Value

Remarks

This function returns a pointer to the start of the byte array.

The length of the array is returned by the pcount() function.

Requirements

Header: xlserialize.h

See Also

CXlOStrStream Class | CXlOStrStream Methods


CXlSerialData Class

Can be used to convert Excel data-types to and from a byte array.

class CXlSerialData

Overview

The CXlSerialData class can be used to convert Excel data-types to and from a byte array.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Methods | xlserialize.h | CXlOperCache class | CXlInputKey class | Cache sample


CXlSerialData Methods

The methods of the CXlSerialData class are listed here.

Construction

public method CXlSerialData Constructs a CXlSerialData object

Assignment operators

public method operator = Assigns a new value to the byte array

Data operations

public method | Attach | Attaches the supplied data to the object, replacing any current contents
public method | Clear | Clears all data
public method | Detach | Detaches the current data from the object
public method | MoveFrom | Detaches the data from another object and attaches it to this object
public method | Set | Copies the supplied data into the object, replacing any current contents

Operations

public method | CopyXlOper | Serializes a single CXlOper
public method | GetXlOper | Deserializes a single CXlOper
public method | ReadArgList | Serializes a sequence of arguments from the stack, using an argument template to define the arguments
public method | ReadArgs | Serializes a sequence of arguments from the stack, using the function name to define the arguments

Accessor methods

public method | GetCount | Returns the size of the byte array
public method | GetData | Returns a pointer to the internal byte array
public method | GetDataBuffer | Returns a character pointer to the internal byte array
public method | IsGood | Returns the state of the byte array

Memory management

Alloc | Allocates memory for a byte array
Destroy | Deallocates memory for a byte array

Comparison methods & operators

public method | Compare | Compares the object with another
public method | operator != | Compares the object with another
public method | operator < | Compares the object with another
public method | operator <= | Compares the object with another
public method | operator = | Compares the object with another
public method | operator > | Compares the object with another
public method | operator >= | Compares the object with another

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | xlserialize.h | CXlOperCache class | CXlInputKey class | Cache sample


CXlSerialData::Alloc

Allocates memory for a byte array

static void* Alloc(
   size_t cbData
) const;

Parameters

cbData

Number of bytes required.

Return Value

Returns a pointer to the allocated memory.

Remarks

This static function allocates memory for a byte array. This allocator should be used for any memory that will be attached to an object using the Attach() method. Unless the buffer is later attached to another object, it should be deallocated using the CXlSerialData::Destroy() static method.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::Attach

Attaches the supplied data to the object, replacing any current contents

void Attach(
   void* pvData,
   size_t cbData
) const;

Parameters

pvData

A pointer to an array of bytes, of size cbData.
cbData

Size of array of bytes.

Remarks

This function removes the current contents and replace them with a reference to the supplied data buffer. The buffer must have been allocated using the CXlSerialData::Alloc() static method.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::Clear

Clears all data

void Clear( );

Remarks

This function clears the byte array from the object and releases all memory.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::Compare

Compares the object with another

int Compare(
   const CXlSerialData& that
) const;

Parameters

that

A CXlSerialData object that will be compared to *this.

Return Value

This function compares the current object with another and returns -1, 0 or 1 depending on their order.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::CopyXlOper

Serializes a single CXlOper

void CopyXlOper(
   const CXlOper& xlo
);

Parameters

xlo

A CXlOper object containing one or more values which will be serialized to the new CXlSerialData object. If the CXlOper was passed as a Reference argument from Excel, you must call CXlOper::Coerce() before saving it.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::CXlSerialData

Constructs a CXlSerialData object

CXlSerialData( );
CXlSerialData(
   const char* pszFnName,
   void* pvFirstArg,
   bool bPrefixFn,
   int omitArgs
);
CXlSerialData(
   void* pvData,
   size_t cbData
);
CXlSerialData(
   const CXlSerialData& srcKey
);
CXlSerialData(
   const CXlOper& xlo
);

Parameters

pszFnName

Name of add-in function whose arguments are being converted to a byte array.
pvFirstArg

Address of the first argument to the add-in function. This pointer is used to traverse the argument stack, using the add-in function's registered definition to interpret the items in the stack.
bPrefixFn

If true, the name of the function will be prefixed to the byte array. This is useful if a single cache is used for more than one add-in function. If false, then the function is not prefixed. This is appropriate if each add-in function uses its own cache.
omitArgs

If non-zero, this instructs the serializer to omit the last nOmitArgs arguments in the list.
pvData

A pointer to an array of bytes, of size cbData.
cbData

Size of array of bytes.
srcKey

An object to be deep copied.
xlo

A CXlOper object containing one or more values which will be serialized to the new CXlSerialData object. If the CXlOper was passed as an argument from Excel, you must call CXlOper::Coerce() before saving it.

Remarks

This method constructs a CXlSerialData object.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::Destroy

Deallocates memory for a byte array

static void Destroy(
   void* pvData,
   size_t cbData
) const;

Parameters

pvData

A pointer to an array of bytes, of size cbData, which was allocated using Alloc().
cbData

Number of bytes in buffer.

Return Value

This static function deallocates memory used for a byte array. This deallocator should be used for any memory that has been detached from an object using the Detach() method.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::Detach

Detaches the current data from the object

void Detach(
   void*& pvData,
   size_t& cbData
) const;

Parameters

pvData

Reference to a pointer to an array of bytes, of size cbData.
cbData

Reference to size of byte array.

Remarks

This function detaches the current contents. Unless the buffer is later attached to another object, it should be deallocated using the CXlSerialData::Destroy() static method.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::GetCount

Returns the size of the byte array

size_t GetCount( ) const;

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::GetData

Returns a pointer to the internal byte array

void* GetData( ) const;

Remarks

This function returns a typeless pointer the internal data buffer. It is the preferred route for gaining direct read access to the buffer.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::GetDataBuffer

Returns a character pointer to the internal byte array

char* GetDataBuffer( );

Remarks

This function returns a pointer the internal data buffer, cast as an array of characters. It is the preferred route for gaining direct write access to the buffer.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::GetXlOper

Deserializes a single CXlOper

void GetXlOper(
   CXlOper& xlo
) const;

Parameters

xlo

A CXlOper object which will be overwritten with the values deserialized from the CXlSerialData object.

Remarks

This method can be used to deserialize a single CXlOper from a byte array which was originally constructed from a CXlOper or by using CXlSerialData::CopyXlOper().

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::IsGood

Returns the state of the byte array

bool IsGood( ) const;

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::MoveFrom

Detaches the data from another object and attaches it to this object

void MoveFrom(
   CXlSerialData& that
) const;

Parameters

that

Reference to an object whose memory will be transfered to *this.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::operator !=

Compares the object with another

bool operator !=(
   const CXlSerialData& that
) const;

Parameters

that

A CXlSerialData object that will be compared to *this.

Return Value

The operator returns false if the current object is identical to that, and true otherwise.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::operator <

Compares the object with another

bool operator <(
   const CXlSerialData& that
) const;

Parameters

that

A CXlSerialData object that will be compared to *this.

Return Value

The operator returns true if the current object is sorted before that, and false otherwise.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::operator <=

Compares the object with another

bool operator <=(
   const CXlSerialData& that
) const;

Parameters

that

A CXlSerialData object that will be compared to *this.

Return Value

The operator returns true if the current object is sorted equal to or before that, and false otherwise.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::operator =

Assigns a new value to the byte array

const CXlSerialData& operator =(
   const CXlSerialData& srcKey
);

Parameters

srcKey

A CXlSerialData object that will be deep-copied to *this.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::operator =

Compares the object with another

bool operator =(
   const CXlSerialData& that
) const;

Parameters

that

A CXlSerialData object that will be compared to *this.

Return Value

The operator returns true if the current object is identical to that, and false otherwise.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::operator >

Compares the object with another

bool operator >(
   const CXlSerialData& that
) const;

Parameters

that

A CXlSerialData object that will be compared to *this.

Return Value

The operator returns true if the current object is sorted after that, and false otherwise.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::operator >=

Compares the object with another

bool operator >=(
   const CXlSerialData& that
) const;

Parameters

that

A CXlSerialData object that will be compared to *this.

Return Value

The operator returns true if the current object is sorted equal to or after that, and false otherwise.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::ReadArgList

Serializes a sequence of arguments from the stack, using an argument template to define the arguments

bool ReadArgList(
   const char* pszTemplate,
   void* pvFirstArg,
   int omitArgs
);

Parameters

pszTemplate

Sequence of letters defining the argument list, excluding the return type, but optionally including '#' and '!' characters.
pvFirstArg

Address of the first argument to the add-in function. This pointer is used to traverse the argument stack, using the add-in function's registered definition to interpret the items in the stack.
omitArgs

If non-zero, this instructs the serializer to omit the last nOmitArgs arguments in the list.

Remarks

This method iterates through some or all of the arguments to an add-in function, and writes their values to a single continuous byte array. Note that the arguments are not prefixed by the name of the add-in function.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::ReadArgs

Serializes a sequence of arguments from the stack, using the function name to define the arguments

bool ReadArgs(
   const char* pszFnName,
   void* pvFirstArg,
   bool bPrefixFn,
   int omitArgs
);

Parameters

pszFnName

Name of add-in function whose arguments are being converted to a byte array.
pvFirstArg

Address of the first argument to the add-in function. This pointer is used to traverse the argument stack, using the add-in function's registered definition to interpret the items in the stack.
bPrefixFn

If true, the name of the function will be prefixed to the byte array. This is useful if a single cache is used for more than one add-in function. If false, then the function is not prefixed. This is appropriate if each add-in function uses its own cache.
omitArgs

If non-zero, this instructs the serializer to omit the last nOmitArgs arguments in the list.

Remarks

This method iterates through the arguments of an add-in function, and writes their values to a single continuous byte array, optionally prefixed by the name of the add-in function.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


CXlSerialData::Set

Copies the supplied data into the object, replacing any current contents

void Set(
   void* pvData,
   size_t cbData
) const;

Parameters

pvData

A pointer to an array of bytes, of size cbData.
cbData

Size of array of bytes.

Remarks

This function removes the current contents and replace them with a copy of the supplied data buffer.

Requirements

Header: xlserialize.h

See Also

CXlSerialData Class | CXlSerialData Methods


xltoolbar.h

Overview

xltoolbar.h contains a class that allows you to add toolbars to the Excel main application window.

For details on how to use the class see CXlToolbar Object overview

Classes

Class | Description
CXlToolbar | A run-time toolbar added to Excel's main application window.
CXlToolbarState | represents the position and visibility of an existing toolbar.

See Also

CXlToolbar object | xlmenu.h


CXlToolbar Class

Used to create run-time toolbars which are attached to the Excel main window.

class CXlToolbar

Overview

The CXlToolbar class can be used to create run-time toolbars which are attached to the Excel main window. Each toolbar can contain any number of buttons.

Note that all the methods of CXlToolbar are static. Thus, you need never instantiate an object of type CXlToolbar; instead you call each function with static scope, e.g.: CXlToolbar::AddToolbar("MyToolbar");

The toolbar should be usually be created during the CXllApp::OnXllOpenEx() event, using the AddToolbar() method. Once a toolbar has been created, tool buttons can be added using AddTool(). When the toolbar is completely set up, it can be made visible using ShowToolbar().

The toolbar should be removed during the CXllApp::OnXllClose() event, using the DeleteToolbar() method.

After Create() has been called, you can call functions to manipulate the buttons state, behavior and appearance, including: EnableTool, PressTool, SetToolBitmap, AssignToTool, and DeleteTool.

Internationalization

Many of the text arguments to CXlToolbar methods may be resource ID strings. These are loaded from the application resource file at run-time. For example, you can add a toolbar whose name is held in resource 234 in the resource file, as follows:

CXlToolbar::AddToolbar("#234");
The string will be loaded in the current user's preferred language, if available. See International support for more information.

The functions that accept and translate resource ID strings are listed below.

CXlToolbar::AddSeparator | CXlToolbar::AddTool | CXlToolbar::AddToolbar
CXlToolbar::AssignToTool | CXlToolbar::DeleteTool | CXlToolbar::DeleteToolbar
CXlToolbar::EnableTool | CXlToolbar::PressTool | CXlToolbar::SetToolBitmap
CXlToolbar::ShowToolbar |  |

Sample applications

You can find full examples of using the CXlToolbar class below:

  • Simple toolbar sample
  • Toolbar sample using bitmaps in a resource file
  • Dynamic toolbar sample

Requirements

Header: xltoolbar.h

See Also

CXlToolbar Methods | xltoolbar.h | Toolbars (User Guide) | Toolbars sample | Toolbars sample using resources | Dynamic toolbars sample


CXlToolbar Methods

The methods of the CXlToolbar class are listed here.

Toolbar functions

AddToolbar | Creates a new empty toolbar
DeleteToolbar | Deletes a toolbar
ShowToolbar | Sets the display options for a toolbar

Tool creation

AddSeparator | Adds a new separator to a toolbar
AddTool | Adds a new tool button to a toolbar
DeleteTool | Deletes the specified tool or separator from a toolbar

Tool methods

AssignToTool | Assigns a macro to a tool button
EnableTool | Sets the enabled state of a tool button
PressTool | Sets the down state of a tool button
SetToolBitmap | Assigns a bitmap to a tool button

Construction

public method CXlToolbar Constructs a CXlToolbar object

Requirements

Header: xltoolbar.h

See Also

CXlToolbar Class | xltoolbar.h | Toolbars (User Guide) | Toolbars sample | Toolbars sample using resources | Dynamic toolbars sample


CXlToolbar::AddSeparator

Adds a new separator to a toolbar

static BOOL AddSeparator(
   const TCHAR* pszToolbarName,
   short int nPosition
);
static BOOL AddSeparator(
   short int nToolbarID,
   short int nPosition
);

Parameters

pszToolbarName

The name of the toolbar.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
nPosition

The desired index of the separator within the toolbar.
nToolbarID

The unique identifier of the toolbar.

Return Value

Returns TRUE if the tool was successfully added, and FALSE if the function failed.

Remarks

Adds a separator to a toolbar.

Requirements

Header: xltoolbar.h

See Also

CXlToolbar Class | CXlToolbar Methods


CXlToolbar::AddTool

Adds a new tool button to a toolbar

static BOOL AddTool(
   const TCHAR* pszToolbarName,
   short int nPosition,
   const TCHAR* pszMacro,
   const TCHAR* pszStatusbarText,
   short int nToolID = 220,
   bool bDown = false,
   bool bEnabled = false,
   const TCHAR* pszHelpTopic = _T(""),
   const TCHAR* pszTooltipText = _T("")
);
static BOOL AddTool(
   short int nToolbarID,
   short int nPosition,
   const TCHAR* pszMacro,
   const TCHAR* pszStatusbarText,
   short int nToolID = 220,
   bool bDown = false,
   bool bEnabled = false,
   const TCHAR* pszHelpTopic = _T(""),
   const TCHAR* pszTooltipText = _T("")
);

Parameters

pszToolbarName

The name of the toolbar.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
nPosition

The desired index of the tool button within the toolbar.
pszMacro

The name of the macro function which will be run when the button is pushed.
pszStatusbarText

The text which will appear in the status bar when the toolbar is selected. This is ignored by most versions of Excel.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
nToolID

The index of the tool button's bitmap within Excel's list of built-in bitmaps.
bDown

Sets whether the tool is initially shown in the down state.
bEnabled

Sets whether the tool is initially enabled.
pszHelpTopic

The name of a help topic in the add-in's current help file.
pszTooltipText

The text which will appear when the mouse hovers over the button. Note that this text will only be visible in Excel if "Show ScreenTips on toolbars" is enabled in the "Options" tab of the Excel Tools/Customize dialog.

If omitted, then pszStatusBarText will be used.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
nToolbarID

The unique identifier of the toolbar.

Return Value

Returns TRUE if the tool was successfully added, and FALSE if the function failed.

Remarks

Adds a new tool button to a toolbar.

Requirements

Header: xltoolbar.h

See Also

CXlToolbar Class | CXlToolbar Methods


CXlToolbar::AddToolbar

Creates a new empty toolbar

static BOOL AddToolbar(
   const TCHAR* pszToolbarName
);
static BOOL AddToolbar(
   const TCHAR* pszToolbarName,
   CXlToolbarState& state
);

Parameters

pszToolbarName

The name of the toolbar, which will appear on the toolbar when it is floating, and also in the Tools/Customize dialog box.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
state

A reference to a state object, which will receive the visibility and position of the toolbar if it already exists.

Return Value

Returns TRUE if the toolbar was successfully created, and FALSE if the function failed.

Remarks

Creates a new named toolbar without tool buttons.

The second variant will destroy any existing toolbar, and store its state information in the state object. This can later be passed to ShowToolbar to restore the toolbar to its original visibility and position.

Requirements

Header: xltoolbar.h

See Also

CXlToolbar Class | CXlToolbar Methods


CXlToolbar::AssignToTool

Assigns a macro to a tool button

static BOOL AssignToTool(
   const TCHAR* pszToolbarName,
   short int nPosition,
   const TCHAR* pszMacro
);
static BOOL AssignToTool(
   short int nToolbarID,
   short int nPosition,
   const TCHAR* pszMacro
);

Parameters

pszToolbarName

The name of the toolbar.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
nPosition

The index of the tool within the toolbar.
pszMacro

The name of the macro function which will be run when the button is pushed.
nToolbarID

The unique identifier of the toolbar.

Return Value

Returns TRUE if the macro was successfully assigned to the tool, and FALSE if the function failed.

Requirements

Header: xltoolbar.h

See Also

CXlToolbar Class | CXlToolbar Methods


CXlToolbar::CXlToolbar

Constructs a CXlToolbar object

CXlToolbar( );

Requirements

Header: xltoolbar.h

See Also

CXlToolbar Class | CXlToolbar Methods


CXlToolbar::DeleteTool

Deletes the specified tool or separator from a toolbar

static BOOL DeleteTool(
   const TCHAR* pszToolbarName,
   short int nPosition
);
static BOOL DeleteTool(
   short int nToolbarID,
   short int nPosition
);

Parameters

pszToolbarName

The name of the toolbar.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
nPosition

The index of the tool or separator within the toolbar.
nToolbarID

The unique identifier of the toolbar.

Return Value

Returns TRUE if the tool was successfully deleted, and FALSE if the function failed.

Remarks

Deletes the specified tool from a toolbar.

Requirements

Header: xltoolbar.h

See Also

CXlToolbar Class | CXlToolbar Methods


CXlToolbar::DeleteToolbar

Deletes a toolbar

static void DeleteToolbar(
   const TCHAR* pszToolbarName
);

Parameters

pszToolbarName

The name of the toolbar.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.

Return Value

Returns TRUE if the toolbar was successfully deleted, and FALSE if the function failed.

Remarks

Deletes the specified toolbar.

Requirements

Header: xltoolbar.h

See Also

CXlToolbar Class | CXlToolbar Methods


CXlToolbar::EnableTool

Sets the enabled state of a tool button

static BOOL EnableTool(
   const TCHAR* pszToolbarName,
   short int nPosition,
   bool bEnabled
);
static BOOL EnableTool(
   short int nToolbarID,
   short int nPosition,
   bool bEnabled
);

Parameters

pszToolbarName

The name of the toolbar.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
nPosition

The index of the tool within the toolbar.
bEnabled

Sets whether the tool is enabled (true) or disabled (false).
nToolbarID

The unique identifier of the toolbar.

Return Value

Returns TRUE if the tool's state was successfully set, and FALSE if the function failed.

Requirements

Header: xltoolbar.h

See Also

CXlToolbar Class | CXlToolbar Methods


CXlToolbar::PressTool

Sets the down state of a tool button

static BOOL PressTool(
   const TCHAR* pszToolbarName,
   short int nPosition,
   bool bDown
);
static BOOL PressTool(
   short int nToolbarID,
   short int nPosition,
   bool bDown
);

Parameters

pszToolbarName

The name of the toolbar.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
nPosition

The index of the tool within the toolbar.
bDown

Sets whether the tool is down (true) or up (false).
nToolbarID

The unique identifier of the toolbar.

Return Value

Returns TRUE if the tool's state was successfully set, and FALSE if the function failed.

Requirements

Header: xltoolbar.h

See Also

CXlToolbar Class | CXlToolbar Methods


CXlToolbar::SetToolBitmap

Assigns a bitmap to a tool button

static BOOL SetToolBitmap(
   const TCHAR* pszToolbarName,
   short int nPosition,
   const TCHAR* pszBitmapFile
);
static BOOL SetToolBitmap(
   const TCHAR* pszToolbarName,
   short int nPosition,
   WORD idBitmap
);
static BOOL SetToolBitmap(
   const TCHAR* pszToolbarName,
   short int nPosition,
   HBITMAP hBitmap
);
static BOOL SetToolBitmap(
   short int nToolbarID,
   short int nPosition,
   const TCHAR* pszBitmapFile
);
static BOOL SetToolBitmap(
   short int nToolbarID,
   short int nPosition,
   WORD idBitmap
);
static BOOL SetToolBitmap(
   short int nToolbarID,
   short int nPosition,
   HBITMAP hBitmap
);

Parameters

pszToolbarName

The name of the toolbar.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
nPosition

The index of the tool within the toolbar.
pszBitmapFile

The full path to a bitmap file.
idBitmap

The resource ID of a bitmap held in the add-ins resource file.
hBitmap

Handle to a bitmap.
nToolbarID

The unique identifier of the toolbar.

Return Value

Returns TRUE if the bitmap was successfully loaded and assigned to the tool, and FALSE if the function failed.

Requirements

Header: xltoolbar.h

See Also

CXlToolbar Class | CXlToolbar Methods


CXlToolbar::ShowToolbar

Sets the display options for a toolbar

static BOOL ShowToolbar(
   const TCHAR* pszToolbarName,
   bool bVisible,
   int nDock = CXlToolbar::DockNone,
   long xPos = LONG_MAX,
   long yPos = LONG_MAX,
   long cWidth = LONG_MAX,
   short int nProtect = 0,
   bool bTooltips = false,
   bool bLargeButtons = false,
   bool bColorButtons = true
);
static BOOL ShowToolbar(
   short int nToolbarID,
   bool bVisible,
   int nDock = CXlToolbar::DockNone,
   long xPos = LONG_MAX,
   long yPos = LONG_MAX,
   long cWidth = LONG_MAX,
   short int nProtect = 0,
   bool bTooltips = false,
   bool bLargeButtons = false,
   bool bColorButtons = true
);
static BOOL ShowToolbar(
   const TCHAR* pszToolbarName,
   CXlToolbarState& state,
   bool bVisible,
   int nDock = CXlToolbar::DockNone,
   long xPos = LONG_MAX,
   long yPos = LONG_MAX,
   long cWidth = LONG_MAX,
   short int nProtect = 0,
   bool bTooltips = false,
   bool bLargeButtons = false,
   bool bColorButtons = true
);
static BOOL ShowToolbar(
   short int nToolbarID,
   CXlToolbarState& state,
   bool bVisible,
   int nDock = CXlToolbar::DockNone,
   long xPos = LONG_MAX,
   long yPos = LONG_MAX,
   long cWidth = LONG_MAX,
   short int nProtect = 0,
   bool bTooltips = false,
   bool bLargeButtons = false,
   bool bColorButtons = true
);

Parameters

pszToolbarName

The name of the toolbar.

This argument can contain a resource ID string. This will be replaced at run-time by a string loaded from the resource file in the current preferred language, as returned by XllGetStringLanguageID.
bVisible

True if the toolbar should be visible. False if it should not. The user can change this setting via Tools/Customize.
nDock

An integer defining the docking position of the toolbar. This should be a member of the DockTypes enumeration, as listed below.

DockTypes | Value | Position
DockTop | 1 | Top
DockLeft | 2 | Left
DockRight | 3 | Right
DockBottom | 4 | Bottom
DockNone | 5 | Floating

xPos

The x-coordinate of the position of the toolbar. A value of LONG_MAX is ignored, and the application default will be applied.
yPos

The y-coordinate of the position of the toolbar. A value of LONG_MAX is ignored, and the application default will be applied.
cWidth

The preferred width of the toolbar. A value of LONG_MAX is ignored, and the application default will be applied.
nProtect

An integer defining the accessibility of the toolbar.
bTooltips

Sets whether tool-tips are displayed when the mouse is over the toolbar.
bLargeButtons

Sets whether the toolbar is displayed with extra-large buttons.
bColorButtons

Sets whether the toolbar is displayed in color (true) or monochrome (false).
nToolbarID

The unique identifier of the toolbar.
state

A reference to a state object, which should contain the visibility and position of the toolbar the last time it existed. The state object should have been populated by a call to AddToolbar.

Return Value

Returns TRUE if the toolbar was successfully created, and FALSE if the function failed.

Requirements

Header: xltoolbar.h

See Also

CXlToolbar Class | CXlToolbar Methods


CXlToolbarState Class

Used to persist the state of a toolbar after the toolbar is destroyed.

class CXlToolbarState

Overview

The CXlToolbarState class contains information about the position, visibility and existence of a toolbar. It can be used to persist the state of a toolbar after the toolbar is destroyed. It is thus possible to restore the toolbar to exactly the state the user left it in.

Declare a CXlToolbarState object in local scope before calling CXlToolbar::AddToolbar. Then pass it as an argument to CXlToolbar::AddToolbar and CXlToolbar::ShowToolbar. If the toolbar already exists, AddToolbar will destroy it, and store its state in the CXlToolbarState object. ShowToolbar will use the information in the CXlToolbarState (if valid) to override your instructions about the toolbar's visibility and location.

Data Members

Member | Description
m_bValid | If true, the rest of the members are valid. If false, the object's data is invalid and should be ignored.
m_bVisible | Is the toolbar visible?
m_nPosition | Docking position of the toolbar. If valid, this will be a member of the CXlToolbar::DockTypes enumeration.
m_x | Position of left edge of toolbar within its docking area.
m_y | Position of top edge of toolbar within its docking area.
m_cx | Width of toolbar
m_cy | Height of toolbar

Requirements

Header: xltoolbar.h

See Also

CXlToolbarState Methods | xltoolbar.h | Toolbars (User Guide) | CXlToolbar class


CXlToolbarState Methods

The methods of the CXlToolbarState class are listed here.

Public methods

public method Clear Clears all state data

Persistence

public method | FromString | Unpacks all data members from a string
public method | ToString | Packs all data members into a string

Construction

public method CXlToolbarState Constructs a CXlToolbarState object

Requirements

Header: xltoolbar.h

See Also

CXlToolbarState Class | xltoolbar.h | Toolbars (User Guide) | CXlToolbar class


CXlToolbarState::Clear

Clears all state data

void Clear( );

Remarks

After this call, the state will be be invalid (i.e. m_bValid will be false).

Requirements

Header: xltoolbar.h

See Also

CXlToolbarState Class | CXlToolbarState Methods


CXlToolbarState::CXlToolbarState

Constructs a CXlToolbarState object

CXlToolbarState( );

Requirements

Header: xltoolbar.h

See Also

CXlToolbarState Class | CXlToolbarState Methods


CXlToolbarState::FromString

Unpacks all data members from a string

bool FromString(
   const TCHAR* pch
);

Parameters

pch

A string containing all the data members, as produced by ToString.

Return Value

Returns true if the string was valid. Returns false if the string was not valid, in which case m_bValid is set to false.

Requirements

Header: xltoolbar.h

See Also

CXlToolbarState Class | CXlToolbarState Methods


CXlToolbarState::ToString

Packs all data members into a string

CString ToString( ) const;

Remarks

The packed string can be read using FromString.

Requirements

Header: xltoolbar.h

See Also

CXlToolbarState Class | CXlToolbarState Methods


xlvaluelistconstraint.h

Overview

xlvaluelistconstraint.h contains two classes. CXlValueListConstraint is used to define a constraint on an input value, such that it must be a member of a specific set of values. CXlValueListWriter converts a set of values and names to a single wide-character string.

Classes

The table below lists the classes declared in the header file.

Class | Description
CXlValueListConstraint | A set of values that constrain an input value.
CXlValueListWriter | Converts a list of enumerated integer values and names into a string list.


CXlValueListConstraint<INT_T> Class

Defines a constraint on an integral input value, such that it must be a member of a specific set of values.

class CXlValueListConstraint<INT_T>

Overview

This class is used to restrict the values of an input value. The object contains a list of integer values. During validation, the Validate method is called. If the input does not match any of the items in the list, then a CXlRuntimeException is raised, and the function exits.

The template argument for the constraint object should match the type of the argument being validated. For example, a input of type long is validated by a constraint of type CXlValueListConstraint<long>.

Requirements

Header: xlvaluelistconstraint.h

See Also

CXlValueListConstraint<INT_T> Methods | xlvaluelistconstraint.h


CXlValueListConstraint<INT_T> Methods

The methods of the CXlValueListConstraint<INT_T> class are listed here.

Construction

public method CXlValueListConstraint Constructs a CXlValueListConstraint object

Validation

public method | SetValues | Sets the constraint's list of values
public method | Validate | Validate an input argument's value against the constraint's list of values

Requirements

Header: xlvaluelistconstraint.h

See Also

CXlValueListConstraint<INT_T> Class | xlvaluelistconstraint.h


CXlValueListConstraint<INT_T>::CXlValueListConstraint

Constructs a CXlValueListConstraint object

CXlValueListConstraint(
   size_t nValues,
   const INT_T* values
);

Parameters

nValues

The number of items in the values parameter.
values

An array of integer values which constrain the value of the input.

Requirements

Header: xlvaluelistconstraint.h

See Also

CXlValueListConstraint<INT_T> Class | CXlValueListConstraint<INT_T> Methods


CXlValueListConstraint<INT_T>::SetValues

Sets the constraint's list of values

void SetValues(
   size_t nValues,
   const INT_T* values
);

Parameters

nValues

The number of items in the values parameter.
values

An array of integer values which constrain the value of the input.

Requirements

Header: xlvaluelistconstraint.h

See Also

CXlValueListConstraint<INT_T> Class | CXlValueListConstraint<INT_T> Methods


CXlValueListConstraint<INT_T>::Validate

Validate an input argument's value against the constraint's list of values

void Validate(
   INT_T scalarValue,
   LPCTSTR pszArgName
) const;
void Validate(
   const std::vector<INT_T>& vectorValue,
   LPCTSTR pszArgName
) const;
void Validate(
   const ple::imtx<INT_T>& matrixValue,
   LPCTSTR pszArgName
) const;

Parameters

scalarValue

A scalar input value. If this is not a member of the constraint's list of values, an exception of type CXlRuntimeException will be thrown, and an error message will be returned, e.g. Expected one of 1, 2, 3 for X.

pszArgName

The name of the argument being validated.

vectorValue

A vector input value. If any item in the vector is not a member of the constraint's list of values, an exception of type CXlRuntimeException will be thrown, and an error message will be returned, e.g. Expected one of 1, 2, 3 for X[12].

matrixValue

A matrix input value. If any item in the matrix is not a member of the constraint's list of values, an exception of type CXlRuntimeException will be thrown, and an error message will be returned, e.g. Expected one of 1, 2, 3 for X[3, 4].

Requirements

Header: xlvaluelistconstraint.h

See Also

CXlValueListConstraint<INT_T> Class | CXlValueListConstraint<INT_T> Methods


CXlValueListWriter Class

Converts a list of enumerated integer values and names into a string list for use by CXlWizExUIArgumentListCreator.

class CXlValueListWriter

Overview

This class is used to generate a single string used by the extended UI, to display possible values for arguments with ValueLists.

Requirements

Header: xlvaluelistconstraint.h

See Also

CXlValueListWriter Methods | xlvaluelistconstraint.h


CXlValueListWriter Methods

The methods of the CXlValueListWriter class are listed here.

Validation

CreateEnumValueList Sets the constraint's list of values

Requirements

Header: xlvaluelistconstraint.h

See Also

CXlValueListWriter Class | xlvaluelistconstraint.h


CXlValueListWriter::CreateEnumValueList

Sets the constraint's list of values

static std::wstring CreateEnumValueList(
   size_t cEntries,
   wchar_t chFieldSep,
   wchar_t chLineSep,
    ...
);

Parameters

cEntries

The number of entries in the value list.
chFieldSep

The character to be used as a field separator. This is inserted between each value and its name.
chLineSep

The character to be used as a line separator. This is inserted between each value pair.
...

The remaining arguments should contain value/name pairs. There should be (cEntries * 2) arguments. Each value argument must be of type int; each name argument must be of type const wchar_t*.

Requirements

Header: xlvaluelistconstraint.h

See Also

CXlValueListWriter Class | CXlValueListWriter Methods


xlwizexui.h

Overview

xlwizexui.h contains classes that extend the user interface (UI) of the Excel Formula Wizard. You can use these classes to add extra editing tools to the Formula Wizard, making for a more efficient user experience.

For an introduction to the Excel Formula Wizard extended user interface, see Extending the Excel Formula Wizard in the User Guide.

Classes

The table below lists the classes declared in the header file.

Class | Description
CXlWizExUIListProvider | A container for a list of value + description pairs, providing a "Value List", which can appear in a drop-down combo in the Formula Wizard.
CXlWizExUIPopupProviderBase | The base class for a popup editor, providing a "..." button in the Formula Wizard, which can pop up a modal dialog.
CXlWizExUIFunctionDescriptor | The definition of the extended UI elements of a single add-in function.
CXlWizExUIFunctionRegistry | A registry of all functions that have an extended UI.
CXlWizExUIArgumentListCreator | A simple class that creates and registers a drop-down value list for a single argument.
CXlWizExUIArgumentPopupCreator | A simple class that creates and registers a popup editor for a single argument.


CXlWizExUIArgumentListCreator Class

A utility class that creates and registers a drop-down value list, for a specified add-in function and argument.

class CXlWizExUIArgumentListCreator

Overview

This simple class creates a CXlWizExUIListProvider object for the specified value list, and registers it during the OnXllOpenEx event.

Objects of this class can conveniently be declared at global scope; this is the technique used by the XLL+ Function Wizard.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIArgumentListCreator Methods | xlwizexui.h | CXlWizExUIListProvider | Extending the Excel Formula Wizard


CXlWizExUIArgumentListCreator Methods

The methods of the CXlWizExUIArgumentListCreator class are listed here.

Construction

public method CXlWizExUIArgumentListCreator Constructs a CXlWizExUIArgumentListCreator object

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIArgumentListCreator Class | xlwizexui.h | CXlWizExUIListProvider | Extending the Excel Formula Wizard


CXlWizExUIArgumentListCreator::CXlWizExUIArgumentListCreator

Constructs a CXlWizExUIArgumentListCreator object

CXlWizExUIArgumentListCreator(
   const TCHAR* pszName,
   int argIndex,
   const std::vector<CString>& vlist
);
CXlWizExUIArgumentListCreator(
   const TCHAR* pszName,
   int argIndex,
   const TCHAR** list,
   int nPairs = -1
);
CXlWizExUIArgumentListCreator(
   const TCHAR* pszName,
   int argIndex,
   const TCHAR* text,
   TCHAR chFieldSep = ',',
   TCHAR chLineSep = ';'
);

Parameters

pszName

The exported name of the function.

argIndex

The index of the argument. (The first argument has index 0.)

vlist

A set of alternating value/description pairs, in the order value1, description1, value2, description2, etc.

These pairs will be added to the new object.
list

An array of pointers to strings. The array should contain a set of alternating value/description pairs, in the order value1, description1, value2, description2, etc.

If nPairs is negative, then a NULL pointer should end the list.

If nPairs is positive, then list should contain nPairs * 2 strings.

These pairs will be added to the new object.
nPairs

The number of pairs of values in the list.

If nPairs is negative, then a NULL pointer should end the list.

If nPairs is positive, then list should contain nPairs * 2 strings.

text

A single null-terminated string containing a set of alternating value/description pairs, in the order value1, description1, value2, description2, etc.

Each value and description should be separated by the character specified as chFieldSep. Each pair should be separated by the character specified as chLineSep.

For example, if chFieldSep is a comma, and chLineSep is a semicolon, then a suitable text string might be: "value1,description of value1;value2,description of value2"

The pairs parsed from text will be added to the new object.
chFieldSep

The character used to separate a value from its description.

chLineSep

The character used to separate a value/description pair from the next pair.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIArgumentListCreator Class | CXlWizExUIArgumentListCreator Methods


CXlWizExUIArgumentPopupCreator Class

A utility class that creates and registers a popup editor for a single argument.

class CXlWizExUIArgumentPopupCreator

Overview

This simple class stores a CXlWizExUIPopupProviderBase-derived object for the specified function and argument, and registers it during the OnXllOpenEx event.

Objects of this class can conveniently be declared at global scope.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIArgumentPopupCreator Methods | xlwizexui.h | CXlWizExUIListProvider | Extending the Excel Formula Wizard


CXlWizExUIArgumentPopupCreator Methods

The methods of the CXlWizExUIArgumentPopupCreator class are listed here.

Construction

public method CXlWizExUIArgumentPopupCreator Constructs a CXlWizExUIArgumentPopupCreator object

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIArgumentPopupCreator Class | xlwizexui.h | CXlWizExUIListProvider | Extending the Excel Formula Wizard


CXlWizExUIArgumentPopupCreator::CXlWizExUIArgumentPopupCreator

Constructs a CXlWizExUIArgumentPopupCreator object

CXlWizExUIArgumentPopupCreator(
   const TCHAR* pszName,
   int argIndex,
   CXlWizExUIPopupProviderBase* ppopup
);

Parameters

ppopup

A pointer to an object derived from CXlWizExUIPopupProviderBase.

Remarks

Once the pointer in ppopup is passed to this constructor, the object pointed to is "owned" by the CXlWizExUIArgumentPopupCreator object. The destructor for ppopup should not be called, since it will be called by the registry's destructor. Note that the destructor (if any) for a class derived from CXlWizExUIPopupProviderBase must be declared as virtual.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIArgumentPopupCreator Class | CXlWizExUIArgumentPopupCreator Methods


CXlWizExUIFunctionDescriptor Class

The definition of the extended UI elements of a single add-in function.

class CXlWizExUIFunctionDescriptor

Overview

A CXlWizExUIFunctionDescriptor object holds all the extended user interface elements that have been defined for the arguments of a single add-in function.

Developers do not normally need to access it directly. When creating and registering extended UI elements, it is simpler to use the creator classes CXlWizExUIArgumentListCreator and CXlWizExUIArgumentPopupCreator.

The class is most likely to be used directly when setting up dynamic value lists, when it can be used to override a standard value list with a dynamically-created list.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionDescriptor Methods | xlwizexui.h | CXlWizExUIFunctionRegistry | Extending the Excel Formula Wizard


CXlWizExUIFunctionDescriptor Methods

The methods of the CXlWizExUIFunctionDescriptor class are listed here.

Construction

public method CXlWizExUIFunctionDescriptor Constructs a CXlWizExUIFunctionDescriptor object

Accessors

public method | GetListProvider | Returns the provider class for a drop-down list
public method | GetName | Returns the exported name of the function
public method | GetPopupProvider | Returns the provider class for a popup editor
public method | GetUIType | Returns the extended UI type for a specified argument
public method | HasExUI | Returns whether the function has any extended UI elements

Operations

public method | AddList | Adds a drop-down list provider for the specified argument
public method | AddPopup | Adds a popup editor provider for the specified argument

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionDescriptor Class | xlwizexui.h | CXlWizExUIFunctionRegistry | Extending the Excel Formula Wizard


CXlWizExUIFunctionDescriptor::AddList

Adds a drop-down list provider for the specified argument

void AddList(
   int argIndex,
   CXlWizExUIListProvider* plist
);

Parameters

argIndex

The index of the argument. (The first argument has index 0.)

plist

A pointer to a CXlWizExUIListProvider object.

Remarks

Once the pointer in plist is passed to this method, the object pointed to is "owned" by the CXlWizExUIFunctionDescriptor object. The destructor for plist should not be called, since it will be called by the CXlWizExUIFunctionDescriptor destructor.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionDescriptor Class | CXlWizExUIFunctionDescriptor Methods | CXlWizExUIListProvider class


CXlWizExUIFunctionDescriptor::AddPopup

Adds a popup editor provider for the specified argument

void AddPopup(
   int argIndex,
   CXlWizExUIPopupProviderBase* ppopup
);

Parameters

argIndex

The index of the argument. (The first argument has index 0.)

ppopup

A pointer to an object derived from CXlWizExUIPopupProviderBase.

Remarks

Once the pointer in ppopup is passed to this method, the object pointed to is "owned" by the CXlWizExUIFunctionDescriptor object. The destructor for ppopup should not be called, since it will be called by the CXlWizExUIFunctionDescriptor destructor. Note that the destructor (if any) for a class derived from CXlWizExUIPopupProviderBase must be declared as virtual.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionDescriptor Class | CXlWizExUIFunctionDescriptor Methods | CXlWizExUIPopupProviderBase class


CXlWizExUIFunctionDescriptor::CXlWizExUIFunctionDescriptor

Constructs a CXlWizExUIFunctionDescriptor object

CXlWizExUIFunctionDescriptor(
   const TCHAR* pszName
);

Parameters

pszName

The exported name of the function.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionDescriptor Class | CXlWizExUIFunctionDescriptor Methods


CXlWizExUIFunctionDescriptor::GetListProvider

Returns the provider class for a drop-down list

virtual IXlWizExUIListProvider* GetListProvider(
   int argIndex
);

Parameters

argIndex

The index of the argument. (The first argument has index 0.)

Return Value

Returns the drop-down list provider for the specified argument, or NULL if no provider exists.

Remarks

This function is only useful if GetUIType returns XLWIZEXUI_UITYPE_LIST (1).

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionDescriptor Class | CXlWizExUIFunctionDescriptor Methods


CXlWizExUIFunctionDescriptor::GetName

Returns the exported name of the function

virtual CString GetName( );

Return Value

Returns the exported name that was provided in the constructor.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionDescriptor Class | CXlWizExUIFunctionDescriptor Methods


CXlWizExUIFunctionDescriptor::GetPopupProvider

Returns the provider class for a popup editor

virtual IXlWizExUIPopupProvider* GetPopupProvider(
   int argIndex
);

Parameters

argIndex

The index of the argument. (The first argument has index 0.)

Return Value

Returns the popup editor provider for the specified argument, or NULL if no provider exists.

Remarks

This function is only useful if GetUIType returns XLWIZEXUI_UITYPE_POPUP (2).

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionDescriptor Class | CXlWizExUIFunctionDescriptor Methods


CXlWizExUIFunctionDescriptor::GetUIType

Returns the extended UI type for a specified argument

virtual int GetUIType(
   int argIndex
);

Parameters

argIndex

The index of the argument. (The first argument has index 0.)

Return Value

Returns one of the following values:

Value | Description
XLWIZEXUI_UITYPE_NONE (0) | The specified argument does not present an extended user interface.
XLWIZEXUI_UITYPE_LIST (1) | The argument displays a drop-down list of values, with descriptions.
XLWIZEXUI_UITYPE_POPUP (2) | The argument displays a button, which will show a modal editor dialog.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionDescriptor Class | CXlWizExUIFunctionDescriptor Methods | XLWIZEXUI_UITYPES enumeration


CXlWizExUIFunctionDescriptor::HasExUI

Returns whether the function has any extended UI elements

virtual bool HasExUI( );

Return Value

Returns true if any of the function's arguments has any extended UI elements, false if there no are no extended UI elements.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionDescriptor Class | CXlWizExUIFunctionDescriptor Methods


CXlWizExUIFunctionRegistry Class

The definition of the extended UI elements of a single add-in function.

class CXlWizExUIFunctionRegistry

Overview

A CXlWizExUIFunctionRegistry object holds all the extended user interface elements that have been defined for all the add-in functions in an add-in application. It is constrained to be a singleton - only one instance of this class may exist in an application.

Developers do not normally need to access it directly. When creating and registering extended UI elements, it is simpler to use the creator classes CXlWizExUIArgumentListCreator and CXlWizExUIArgumentPopupCreator.

The class is most likely to be used directly when setting up dynamic value lists, when it can be used to access a function's CXlWizExUIFunctionDescriptor instance, and then override a standard value list with a dynamically-created list.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Methods | xlwizexui.h | CXlWizExUIFunctionDescriptor | Extending the Excel Formula Wizard


CXlWizExUIFunctionRegistry Methods

The methods of the CXlWizExUIFunctionRegistry class are listed here.

Construction

public method CXlWizExUIFunctionRegistry Constructs a CXlWizExUIFunctionRegistry object

Singleton

GetInstance Return the single instance of CXlWizExUIFunctionRegistry

Services

OnCallFunction Informs the Extended UI that the named function is being called

Function list

public method | AddFunctionDescriptor | Adds a CXlWizExUIFunctionDescriptor object to the registry
public method | FindAddFunctionDescriptor | Finds a CXlWizExUIFunctionDescriptor object in the registry, and adds a new object if it is not found
public method | GetFunctionDescriptor | Finds a CXlWizExUIFunctionDescriptor object in the registry

Properties

public method | GetKeyMapping | Returns a pointer to the key mappings for an extended user interface type
public method | RequiresExtendedUI | Returns whether the registry contains any functions that require an extended user interface
public method | SetShouldUseThemes | Sets whether the extended user interface should use Windows XP themes
public method | SetSupportsExtendedUI | Sets whether the registry supports an extended user interface
public method | ShouldUseThemes | Returns whether the extended user interface should use Windows XP themes
public method | SupportsExtendedUI | Returns whether the registry supports an extended user interface

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Class | xlwizexui.h | CXlWizExUIFunctionDescriptor | Extending the Excel Formula Wizard


CXlWizExUIFunctionRegistry::AddFunctionDescriptor

Adds a CXlWizExUIFunctionDescriptor object to the registry

CXlWizExUIFunctionDescriptor* AddFunctionDescriptor(
   CXlWizExUIFunctionDescriptor* pfn
);

Parameters

pfn

A pointer to a CXlWizExUIFunctionDescriptor object.

Return Value

Returns the value of pfn.

Remarks

Once the pointer in pfn is passed to this method, the object pointed to is "owned" by the registry. The destructor for pfn should not be called, since it will be called by the registry destructor.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Class | CXlWizExUIFunctionRegistry Methods


CXlWizExUIFunctionRegistry::CXlWizExUIFunctionRegistry

Constructs a CXlWizExUIFunctionRegistry object

CXlWizExUIFunctionRegistry( );

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Class | CXlWizExUIFunctionRegistry Methods


CXlWizExUIFunctionRegistry::FindAddFunctionDescriptor

Finds a CXlWizExUIFunctionDescriptor object in the registry, and adds a new object if it is not found

CXlWizExUIFunctionDescriptor* FindAddFunctionDescriptor(
   const TCHAR* pszFnName
);

Parameters

pszFnName

The exported name of the function.

Return Value

Returns a pointer to the CXlWizExUIFunctionDescriptor for the specified function.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Class | CXlWizExUIFunctionRegistry Methods


CXlWizExUIFunctionRegistry::GetFunctionDescriptor

Finds a CXlWizExUIFunctionDescriptor object in the registry

virtual IXlWizExUIFunctionDescriptor* GetFunctionDescriptor(
   const TCHAR* pszFnName
);

Parameters

pszFnName

The exported name of the function.

Return Value

Returns a pointer to the CXlWizExUIFunctionDescriptor for the specified function. If the function is not found, NULL is returned.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Class | CXlWizExUIFunctionRegistry Methods


CXlWizExUIFunctionRegistry::GetInstance

Return the single instance of CXlWizExUIFunctionRegistry

static CXlWizExUIFunctionRegistry* GetInstance( );

Return Value

Returns the single instance of CXlWizExUIFunctionRegistry.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Class | CXlWizExUIFunctionRegistry Methods


CXlWizExUIFunctionRegistry::GetKeyMapping

Returns a pointer to the key mappings for an extended user interface type

virtual PXLWIZEXUI_KEYMAPPING GetKeyMapping(
   int nUiType
);

Parameters

nUiType

Pass XLWIZEXUI_UITYPE_LIST (1) to get the key mappings for drop-down lists, or XLWIZEXUI_UITYPE_POPUP (2) to get the key mappings for popup editors.

Return Value

Returns a pointer to a set of key mappings for an extended user interface type. Developers can change the members of the XLWIZEXUI_KEYMAPPING structure, to change the default key mappings for the extended UI.

Remarks

The XLWIZEXUI_KEYMAPPING structure contains three members:

Type | Name | Description
WORD | vk | The virtual key code for the UI type. By default this is VK_DOWN for drop-down lists and VK_RETURN for popup editors.
WORD | vkModifier | The modifier key for the UI type, which must be one of 0, VK_SHIFT, VK_CONTROL or VK_MENU, indicating no modifier key, the shift key, the control key and the alt key respectively. By default this is 0 for drop-down lists and VK_MENU for popup editors.
int | nBehavior | The behavior for the key, as dscribed below. By default this is XLWIZEXUI_KEY_IF_NOT_REFERENCE for drop-down lists and XLWIZEXUI_KEY_ALWAYS for popup editors.

The following values may be used for nBehavior:

Value | Description
XLWIZEXUI_KEY_NEVER | The extended UI cannot be triggered by the keyboard; only the mouse can be used to invoke the UI.
XLWIZEXUI_KEY_IF_EMPTY | The keyboard shortcut will only trigger the UI action if the field is currently empty.
XLWIZEXUI_KEY_IF_NOT_REFERENCE | The keyboard shortcut will not trigger the UI action if the field contains a reference to a cell. It will only be triggered if the field contains a value.
XLWIZEXUI_KEY_NEVER | The extended UI will be triggered by the keyboard regardless of the current contents of the field.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Class | CXlWizExUIFunctionRegistry Methods | XLWIZEXUI_UITYPES enumeration | XLWIZEXUI_KEY_BEHAVIORS enumeration


CXlWizExUIFunctionRegistry::OnCallFunction

Informs the Extended UI that the named function is being called

static void OnCallFunction(
   const TCHAR* pszName
);

Parameters

pszName

The exported name of the function.

Remarks

This static method is thread-safe.

It should be called at the start of any add-in function that uses Extended UI elements. A call is inserted by the XLL+ Function Wizard at the appropriate point in each wrapper function. The developer rarely needs to code a call to the function.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Class | CXlWizExUIFunctionRegistry Methods


CXlWizExUIFunctionRegistry::RequiresExtendedUI

Returns whether the registry contains any functions that require an extended user interface

bool RequiresExtendedUI( );

Return Value

Returns true if the registry contains any functions that require the extended user interface for Excel's Formula Wizard, false if it does not.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Class | CXlWizExUIFunctionRegistry Methods


CXlWizExUIFunctionRegistry::SetShouldUseThemes

Sets whether the extended user interface should use Windows XP themes

void SetShouldUseThemes(
   bool bUseThemes
);

Parameters

bUseThemes

true if the the extended user interface should use Windows XP themes. false if it should not.

Remarks

Use this method to turn off theme support in the extended user interface. You should ensure that this value matches the behavior of your add-in. If you provide a manifest file that loads Common Controls 6, then theme support should be on, so that the extended UI buttons match the controls in Common Controls 6. If you do not provide a manifest file, or you expect your add-in to be used under Excel XP (2002) or below, then you should not support themes.

By default, XLL+ projects built with Visual Studio 2005 and above provide a manifest. Projects built with Visual Studio.NET do not.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Class | CXlWizExUIFunctionRegistry Methods


CXlWizExUIFunctionRegistry::SetSupportsExtendedUI

Sets whether the registry supports an extended user interface

void SetSupportsExtendedUI(
   bool bSupported
);

Parameters

bSupported

true if the registry should support the extended user interface for Excel's Formula Wizard, false if it should not.

Remarks

Use this method to turn off the extended user interface.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Class | CXlWizExUIFunctionRegistry Methods


CXlWizExUIFunctionRegistry::ShouldUseThemes

Returns whether the extended user interface should use Windows XP themes

virtual bool ShouldUseThemes( );

Return Value

Returns true if the extended user interface should use Windows XP themes. By default a registry returns true; you can turn the functionality off by calling SetShouldUseThemes.

Under Visual Studio .NET, the default value is false. You should use SetShouldUseThemes(true) if you need theme support.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Class | CXlWizExUIFunctionRegistry Methods


CXlWizExUIFunctionRegistry::SupportsExtendedUI

Returns whether the registry supports an extended user interface

virtual bool SupportsExtendedUI( );

Return Value

Returns true if the registry supports the extended user interface for Excel's Formula Wizard, false if it does not. By default a registry returns true; you can turn the functionality off by calling SetSupportsExtendedUI.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIFunctionRegistry Class | CXlWizExUIFunctionRegistry Methods


CXlWizExUIListProvider Class

A "Value List", which contains a set of value/description pairs that will appear in a drop-down within the Excel Formula Wizard.

class CXlWizExUIListProvider

Overview

An add-in can extend the Excel Formula Wizard user interface by displaying a drop-down button on an argument field. When the user clicks on the button (or presses the down arrow key), a drop-down list of values (each with a description) appears: this list is provided by a CXlWizExUIListProvider object.

The XLL+ Function Wizard generates all the code required for this functionality: just populate the Value List for an argument, and set the ShowValueListInFormulaWizard property to true.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIListProvider Methods | xlwizexui.h | CXlWizExUIArgumentListCreator | Extending the Excel Formula Wizard


CXlWizExUIListProvider Methods

The methods of the CXlWizExUIListProvider class are listed here.

Construction

public method CXlWizExUIListProvider Constructs a CXlWizExUIListProvider object

Accessors

public method | GetCount | Returns the number of value/description pairs in the value list
public method | GetListText | Returns the display string of the specified item in the value list
public method | GetValueText | Returns the value of the specified item in the value list

Operations

public method | Add | Adds an item to the list of value/description pairs
public method | Clear | Clears all value/description pairs
public method | LoadList | Loads items into the list of value/description pairs

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIListProvider Class | xlwizexui.h | CXlWizExUIArgumentListCreator | Extending the Excel Formula Wizard


CXlWizExUIListProvider::Add

Adds an item to the list of value/description pairs

void Add(
   const TCHAR* value,
   const TCHAR* description
);

Parameters

value

The value of the item to be added to the list.

description

The description of the item to be added to the list.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIListProvider Class | CXlWizExUIListProvider Methods


CXlWizExUIListProvider::Clear

Clears all value/description pairs

void Clear( );

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIListProvider Class | CXlWizExUIListProvider Methods


CXlWizExUIListProvider::CXlWizExUIListProvider

Constructs a CXlWizExUIListProvider object

CXlWizExUIListProvider( );
CXlWizExUIListProvider(
   const CXlWizExUIListProvider& other
);
CXlWizExUIListProvider(
   const std::vector<CString>& vlist
);
CXlWizExUIListProvider(
   const TCHAR** list,
   int nPairs = -1
);
CXlWizExUIListProvider(
   const TCHAR* text,
   TCHAR chFieldSep = ',',
   TCHAR chLineSep = ';'
);

Parameters

other

A CXlWizExUIListProvider whose contents will be copied to the new object.
vlist

A set of alternating value/description pairs, in the order value1, description1, value2, description2, etc.

These pairs will be added to the new object.
list

An array of pointers to strings. The array should contain a set of alternating value/description pairs, in the order value1, description1, value2, description2, etc.

If nPairs is negative, then a NULL pointer should end the list.

If nPairs is positive, then list should contain nPairs * 2 strings.

These pairs will be added to the new object.
nPairs

The number of pairs of values in the list.

If nPairs is negative, then a NULL pointer should end the list.

If nPairs is positive, then list should contain nPairs * 2 strings.

text

A single null-terminated string containing a set of alternating value/description pairs, in the order value1, description1, value2, description2, etc.

Each value and description should be separated by the character specified as chFieldSep. Each pair should be separated by the character specified as chLineSep.

For example, if chFieldSep is a comma, and chLineSep is a semicolon, then a suitable text string might be: "value1,description of value1;value2,description of value2"

The pairs parsed from text will be added to the new object.
chFieldSep

The character used to separate a value from its description.

chLineSep

The character used to separate a value/description pair from the next pair.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIListProvider Class | CXlWizExUIListProvider Methods


CXlWizExUIListProvider::GetCount

Returns the number of value/description pairs in the value list

virtual size_t GetCount( );

Return Value

Returns the number of value/description pairs in the value list.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIListProvider Class | CXlWizExUIListProvider Methods


CXlWizExUIListProvider::GetListText

Returns the display string of the specified item in the value list

virtual size_t GetListText(
   size_t index
);

Parameters

index

The zero-based index of the item whose value is to be returned.

Return Value

Returns a string containing the text to be displayed in the drop-down list.

Remarks

The standard behavior is to return the value, followed by " - " and then the description, e.g. Value1 - Description of Value1. To change the behavior, derive a class from CXlWizExUIListProvider, and override this virtual method.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIListProvider Class | CXlWizExUIListProvider Methods


CXlWizExUIListProvider::GetValueText

Returns the value of the specified item in the value list

virtual size_t GetValueText(
   size_t index
);

Parameters

index

The zero-based index of the item whose value is to be returned.

Return Value

Returns a string containing the value text for the specified item.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIListProvider Class | CXlWizExUIListProvider Methods


CXlWizExUIListProvider::LoadList

Loads items into the list of value/description pairs

void LoadList(
   const std::vector<CString>& vlist
);
void LoadList(
   const TCHAR** list,
   int nPairs
);
void LoadList(
   const TCHAR* text,
   TCHAR chFieldSep = ',',
   TCHAR chLineSep = ';'
);

Parameters

vlist

A set of alternating value/description pairs, in the order value1, description1, value2, description2, etc.

These pairs will be added to the object.
list

An array of pointers to strings. The array should contain a set of alternating value/description pairs, in the order value1, description1, value2, description2, etc.

If nPairs is negative, then a NULL pointer should end the list.

If nPairs is positive, then list should contain nPairs * 2 strings.

These pairs will be added to the new object.
nPairs

The number of pairs of values in the list.

If nPairs is negative, then a NULL pointer should end the list.

If nPairs is positive, then list should contain nPairs * 2 strings.

text

A single null-terminated string containing a set of alternating value/description pairs, in the order value1, description1, value2, description2, etc.

Each value and description should be separated by the character specified as chFieldSep. Each pair should be separated by the character specified as chLineSep.

For example, if chFieldSep is a comma, and chLineSep is a semicolon, then a suitable text string might be: "value1,description of value1;value2,description of value2"

The pairs parsed from text will be added to the object.
chFieldSep

The character used to separate a value from its description.

chLineSep

The character used to separate a value/description pair from the next pair.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIListProvider Class | CXlWizExUIListProvider Methods


CXlWizExUIPopupProviderBase Class

The base class for a popup editor, providing a "..." button in the Formula Wizard, which can pop up a modal dialog.

class CXlWizExUIPopupProviderBase

Overview

An add-in can extend the Excel Formula Wizard user interface by displaying a popup button ("...") on an argument field. When the user clicks on the button (or presses Alt+Enter), the event is passed to an object derived from CXlWizExUIPopupProviderBase, and the Edit function is called.

To implement a popup editor, the developer must do the following:

  1. create a class derived from CXlWizExUIPopupProviderBase;
  2. register an instance of the class, by creating a CXlWizExUIArgumentPopupCreator object; and
  3. use the XLL+ Function Wizard to mark the argument to be edited, by setting the ShowPopupInFormulaWizard property to true.

Virtual Functions

A class inheriting from CXlWizExUIPopupProviderBase must provide an implementation of Edit. If a destructor is provided, it must be declared as virtual.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIPopupProviderBase Methods | xlwizexui.h | CXlWizExUIArgumentPopupCreator | Extending the Excel Formula Wizard


CXlWizExUIPopupProviderBase Methods

The methods of the CXlWizExUIPopupProviderBase class are listed here.

Construction

public method CXlWizExUIPopupProviderBase Constructs a CXlWizExUIPopupProviderBase object

Virtual functions

public method Edit Displays a dialog to allow the user to edit a value in the Formula Wizard

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIPopupProviderBase Class | xlwizexui.h | CXlWizExUIArgumentPopupCreator | Extending the Excel Formula Wizard


CXlWizExUIPopupProviderBase::CXlWizExUIPopupProviderBase

Constructs a CXlWizExUIPopupProviderBase object

CXlWizExUIPopupProviderBase( );

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIPopupProviderBase Class | CXlWizExUIPopupProviderBase Methods


CXlWizExUIPopupProviderBase::Edit

Displays a dialog to allow the user to edit a value in the Formula Wizard

virtual bool Edit(
   CString& strValue,
   HWND hwndParent
);

Parameters

strValue

When the method is called, strValue contains the current contents of the argument in the Formula Wizard. On exit, it should contain the new value after the user has editied it. If the method returns false, then the exit value will be ignored.

hwndParent

The window handle which a modal dialog must use as a parent window.

Return Value

Returns true if the user has changed the value of the argument, false if no changes were made.

Remarks

This method must be implemented by a class that is derived from CXlWizExUIPopupProviderBase. It will be invoked whenever the user clicks on the edit button ("...") in an argument of the Formula Wizard, or when they type the accelerator key combination (which is Alt+Enter by default).

The implementation should display a modal window, which lets the user edit the value of the argument.

If the user cancels, then the function should return false; if the user makes changes to the argument's value, the function should return true, and the new value should be contained in strValue.

Requirements

Header: xlwizexui.h

See Also

CXlWizExUIPopupProviderBase Class | CXlWizExUIPopupProviderBase Methods


Enumerations

The enumerations declared in xlwizexui.h are listed below.

XLWIZEXUI_KEY_BEHAVIORS
XLWIZEXUI_UITYPES

Requirements

Header: xlwizexui.h

See Also

xlwizexui.h


XLWIZEXUI_KEY_BEHAVIORS Enumeration

Types of keyboard behavior that can be added to the Excel Formula Wizard.

enum XLWIZEXUI_KEY_BEHAVIORS

Members

XLWIZEXUI_KEY_NEVER | 0 | There is no keyboard shortcut.
XLWIZEXUI_KEY_IF_EMPTY | 1 | The keyboard shortcut only causes an action if the argument is currently empty.
XLWIZEXUI_KEY_IF_NOT_REFERENCE | 2 | The keyboard shortcut only causes an action if the argument is currently either empty or contains a value. It is ignored if the argument contains a cell reference.
XLWIZEXUI_KEY_ALWAYS | 3 | The keyboard shortcut always causes an action, regardless of the current state of the argument.

Requirements

Header: xlwizexui.h

See Also

xlwizexui.h | Extending the Excel Formula Wizard - Advanced Features


XLWIZEXUI_UITYPES Enumeration

The types of extended user interface that can be added to the Excel Formula Wizard.

enum XLWIZEXUI_UITYPES

Members

XLWIZEXUI_UITYPE_NONE | 0 | The selected argument has no extended user interface elements.
XLWIZEXUI_UITYPE_LIST | 1 | The selected argument has a drop-down list of values.
XLWIZEXUI_UITYPE_POPUP | 2 | The selected argument has a prompt button ("..."), which launches a popup dialog.

Requirements

Header: xlwizexui.h

See Also

xlwizexui.h | Extending the Excel Formula Wizard (User Guide)


XLL+ Tools

XLL+ contains a number of tools to help you write fully-featured Excel add-ins.

XLL+ Function Wizard
The XLL+ Function Wizard is an add-in for Microsoft Developer Studio which lets you create and edit add-in functions. It generates all the code required for registering the function with Excel and for input & output of Excel data structures.
XLL+ AppWizard
The XLL+ AppWizard creates a new Developer Studio project, containing all the code required to build and register an Excel add-in XLL library.
Help Generator
The XLL+ Help Generator examines your source code, and use it to generate all the files of a Microsoft Help Project. Users can then see help for each of your functions from within any version of Excel.
Help Builder
This command line tool runs the XLL+ Help generator outside Visual Studio, and can therefor be used as part of an automated build.
XLL Wrapper Generator
This toolkit contains tools, a runtime library, samples and documentation to help with the development of COM modules and .NET assemblies that wrap Excel XLL add-ins. The add-in functions in the library are available as COM and .NET methods to client programs that use the wrapper modules. The wrapper objects can be used by clients written in any development environment that supports COM or .NET, including C++, Java, C#, Visual Basic and VBA.


XLL+ Function Wizard

The XLL+ Function Wizard is an addin for Microsoft® Visual Studio. It makes it easy to create and maintain Excel Add-in functions.

Writing addin functions for Excel in C/C++ is tedious and error-prone, even for the most experienced and conscientious of developers. The developer must write code to:

  • Register the add-in library with Excel
  • Register each add-in function
  • Read each argument and convert it from Excel data format to native C types
  • Return errors if inputs do not satisfy constraints regarding shape and content
  • Construct and populate a return value in Excel data format

If you use the XLL+ AppWizard to create your Visual Studio project and the XLL+ Function Wizard to create your addin functions, all this code will be generated for you. And if you need to change your function's interface later, the Wizard will modify the generated code as needed.

Getting started

The links below will take you to the main topics, to get you started with the Function Wizard.

Function Wizard On-Line Help
Summary of commands
User Guide: Function Wizard

See Also

Summary of Commands | XLL+ Class Reference | XLL+ AppWizard | User Guide


Windows

The various windows of the Function Wizard are listed below.

Function Wizard Dialog
New Function dialog
New Macro dialog
Argument Details
Value List Editor
Excel Formula Wizard Preview
Favorites window
License Information
Select Function Dialog


Function Wizard Dialog

XLL+ Function Wizard

The XLL+ Function Wizard lets you edit all aspects of an add-in function, including its name, description and signature.

At the top of the window is a menu and a toolbar, containing all the commands that may be used. See Summary of Commands for a list.

The upper half of the window contains four important fields that define and describe the function. They are listed below, with a link to the property that each field contains.

Name

This is the name of the function as it will appear in Excel. It may not be localized, i.e. it must be the same in all user languages. It should be unique within an add-in project.

See also Function.ExportedName.

Return type

The type of value that will be returned to Excel.

The value will always be CXlOper for functions which return a variable type, or return arrays, or may fail. The default value for ReturnType is CXlOper.

See also Function.ReturnType.

Category

Category in which the function will appear within the Excel Formula Wizard. You can use one of Excel's built-in categories, or you can define your own.

The category name can be localized, so that it will appear in the language of the user. Localized categories should be in the form #123 where the number refers to a string in the resource file. See Types of string - Category in the User Guide for more information on localizing categories.

See also Function.Category.

Description

The description of a function, as it will appear in Excel's Formula Wizard.

The description can be localized, so that it will appear in the language of the user. Localized descriptions should be in the form #123 where the number refers to a string in the resource file. See Types of string - Help text in the User Guide for more information on localizing function descriptions.

See also Function.Description.

Tabs

There are several tabs in the lower half of the window, which let you edit and review various aspects of the add-in function.

Tab | Contents
Arguments | The arguments grid lets you edit all the function's argument in a grid form.
Features | The features page lets you control the behavior and availability of the add-in function.
Extensions | This tab lists any of the function extensions that are currently available. You can switch them on and off for this add-in function, and set any parameters.
Details | The details tab displays all aspects of the add-in function in a tree/grid view. You can use it to drill-down to any level of detail about the function itself and all of its arguments.
Preview | A preview of the function, as it will appear in C++ code, is displayed in the preview tab
Error | The errors tab displays a list of all the errors and warnings detected by the wizard in the current add-in function.

See Also

Summary of Commands | User Guide: Function Wizard


Function Wizard - Arguments Tab

The Arguments Tab contains a toolbar and a grid.

The toolbar contains commands for use with arguments, and the grid contains a summary of each of the add-in function's arguments.

You can add a new argument by typing into any of the columns of the empty row which appears at the bottom of the grid.

You can use the grid's controls to manipulate the list of arguments:

  • Selecting arguments
  • Copy and paste arguments
  • Drag and drop arguments
  • Reorder arguments
  • Arrange arguments into groups

Columns

The columns of the grid are listed below, with a link to the property that each column contains.

Name

This is the name of the argument as it will appear in C++ code, and (usually) also as it will appear in the Excel Formula Wizard.

It should be unique within a function; when you copy or drag-copy arguments the wizard will ensure that the names of new arguments are unique.

If you want the argument name to be localized in Excel (i.e. to appear in the language of the user) then use the Resource ID column.

See also Argument.Name.

Type

The type of value that will be passed from Excel to the add-in function.

Use the drop-down to control the data type, and whether it is a single value, a vector or a matrix.

All the built-in data types are listed in the drop-down, and so are any Extended scalar types that have been registered.

The built-in types are as follows:

Type | C++ type | Description
Boolean | BOOL | Boolean (true or false) value
Double | double | Floating-point number
Int | long | Signed integer (32-bit)
Short Int | short int | Signed integer (16-bit)
String | const CXlStringArg& | Text string
Unsigned Short Int | unsigned short int | Unsigned integer (16-bit)
Reference | const CXlOper* | A reference to an Excel cell range
Value | const CXlOper* | The value(s) contained in an Excel cell range
XlArray | const CXlArray& | An array of numbers

Value types can be assigned a rank, which defines the number of dimensions they are expected to have.

Rank | Name | Description
0 | Scalar | A single value
1 | Vector | A set of values contained in a single row or column
2 | Matrix | A set of values contained in one or more rows and one or more columns

Vector or matrix arguments will be stored in a container, such as std::vector<T>. You can use the Container column to specify a particular container class. Otherwise the default class (as defined by the DefaultVectorContainer or DefaultMatrixContainer settings) will be used.

See also Argument.Signature.

Resource ID

You can choose to localize the name of the argument, as it will appear in the Excel Formula Wizard. If you specify a number for the resource ID, then the ID will be used to get a string from the add-in's resource file. If an entry can be found in the resource file that matches the language of the user, then that entry will be used instead of the argument's name.

See argument names in the User Guide for more details.

To show or hide the Resource ID column, use the View Resource ID Column command.

See also Argument.ResourceId.

Optional

Check this box to make the argument optional. If the argument is empty or missing then the value in the Default column will be used.

To show or hide the Optional column, use the View Optional Column command.

See also Argument.UseDefault.

Default

If the argument is marked as optional and the argument is empty or missing at run-time then the value in the Default column will be used.

To show or hide the Default column, use the View Default Value Column command.

See also Argument.DefaultValueText.

Container

This column allows you to specify the C++ container class into which the argument's values will be copied.

If you leave it blank, then the default container class (as defined by the DefaultVectorContainer or DefaultMatrixContainer setting) will be used.

For details of the notation to be used for the container class, see Argument.ContainerClass.

Working with the argument list

Selecting arguments

You can select an argument by left-clicking with the mouse in one of the cells of the row that contains it. You can also use the arrow keys on the keyboard to move from cell to cell and row to row.

Multiple selection works in the same way as in the file list of the Windows Explorer. Holding the shift key down while left-clicking or moving with the arrow keys extends the selection: the selection will include the last active row and the newly selected row, and all rows in between.

Holding the control key down while left-clicking allows you to select a new row without deselecting the currently selected row(s). If the row clicked on is already selected, then it will be deselected.

Copy/Paste

You can use the [image] Copy argument and [image] Cut argument commands to put the selected arguments into the clipboard.

From there you can use the [image] Paste argument command to insert them at a different location within the function's argument list. Alternatively you can paste them to a different function, after selecting a different function in the Wizard.

Drag and drop

You can move one or more arguments within the list of arguments by clicking within the selected arguments and dragging the mouse.

If you hold down the CTRL key at the same time as dragging then you will get a new copy of the dragged arguments. (The names of the new arguments will be altered to ensure uniqueness.)

Argument order

You can use drag and drop to move arguments up or down in the argument order. Select the arguments you want to move, and drag them with the mouse to a position earlier or later in the list.

You can also the [image] Move argument up and [image] Move argument down commands to change the selected argument's position.

Groups

Sometimes it is necessary or desirable to create a grouped argument. This is a group of arguments that appear as a single argument in Excel, but is split into its component inner arguments by the validation code.

The Function Wizard offers a variety of tools for working with groups.

  • The [image] New Group command can be used to create a new empty group, to which you can then add new or existing arguments.
  • The [image] Group arguments and [image] Ungroup arguments commands can be used to group selected arguments or to ungroup an existing group.
  • You can drag an argument into or out of a group using the mouse.
  • You can use the [image] Move argument right and [image] Move argument left commands to move a group into or out of a group respectively.

For more information about grouped arguments, see Grouping arguments in the User Guide.

See Also

Function Wizard Dialog | Summary of Commands


Function Wizard - Features Tab

The Features Tab contains two groups of controls:

  • Behavior
  • Availability

Behavior

The Behavior panel contains a list of switches which control the code that is generated for the function. The more commonly used switches are described below.

Cache results

If this item is checked, then the function's result will be stored in an application-level cache. Each time the function is called, the cache is searched for an identical set of inputs. If they are found, then the result is returned from the cache and the implementation function is not called. This can result in a considerable performance improvement.

See also the Function.CacheResults property.

Create asynchronous version

If this item is checked, then an additional add-in function will be created which runs the core function asynchronously, in a worker thread. The function will be have the same name as the core function, plus the suffix "Async". See Asynchronous functions in the User Guide.

See also the Function.CreateAsyncVersion property.

Do not call in Formula Wizard

If this item is checked, then the function will return #VALUE! when it is called from the Excel Formula Wizard.

See also Excel Formula Wizard: Automating the code in the User Guide.

Thread safe

If this item is checked, then the function will be registered as a thread-safe function, which means that Excel can call the function on multiple threads simultaneously. See Ensuring global data is thread-safe in the User Guide.

Note that this property is ignored in Excel 2003 and below.

See also the Function.IsThreadSafe property.

Volatile

If this item is checked, then the function will be registered as a volatile function, which means that Excel will recalculate any cell containing the function whenever any cell in the same sheet is recalculated. See Volatile functions in the User Guide.

See also the Function.IsVolatile property.

Availability

This group of controls specifies when and where the add-in function will be available.

Worksheet | Function can be called from worksheet cells, and will be listed in the Excel Formula Wizard.
Macro | Function can be called from macros or as a command. It may not be called from worksheet cells. It will not be listed in the Excel Formula Wizard.
Hidden | Function can be called from worksheets cells or from macros or as a command. It will not be listed in the Excel Formula Wizard.

See also the Function.Availability property.

See Also

Function Wizard Dialog | Summary of Commands


Function Wizard - Extensions Tab

The Extensions tab of the XLL+ Function Wizard shows in detail all the function extensions that have been registered and are available for use with the current add-in function.

The tab will not be visible if no function extensions with parameters have been registered.

A list of all the extensions is shown on the left of the tab. If you check an extension, then it will be added to the function.

If the extension has any parameters that need to be set, these will appear in the property grid on the right-hand side of the tab. Any descriptions and display names that are contained in the extension definition will be displayed as help in the grid. If the text was localized in the extension definition file, then the help and display names will appear in the language of the user.

See Also

Function Wizard Dialog | Summary of Commands | Function extensions | XLL+ Extension Schema


Function Wizard - Details Tab

The Details tab of the XLL+ Function Wizard allows a more detailed view of the function and its arguments than is available in the Arguments and the Features tabs.

To see all the available properties of the function, including the rarely used properties, use the [image] Show advanced properties command.

See Also

Function Wizard Dialog | Summary of Commands


Function Wizard - Preview Tab

The Preview tab of the XLL+ Function Wizard shows you what the generated code will look like when you press OK to accept all changes.

If you are simultaneously working on the code template being used by the code generator, you can refresh the display with the [image] Refresh preview command.

See Also

Function Wizard Dialog | Summary of Commands


Function Wizard - Errors Tab

The Errors tab of the XLL+ Function Wizard shows all the warnings and errors that have been detected in the current add-in function.

You can use the [image] Go to error location command, or double-click on the error, to jump to the location of the error.

You can use the [image] Show Error Details command, to zoom the error message.

Errors

Errors are shown with this symbol:

An error is likely to make the generated code fail to compile or fail to run. You should take steps to rectify it immediately.

Warnings

Warnings are shown with this symbol:

A warning is an indication that the add-in function does not follow best practises. They can be ignored without causing the function to fail, but it is usually best to deal with them before releasing the add-in to other users.

See Also

Function Wizard Dialog | Summary of Commands


New Function dialog

Use this dialog to enter the name of a new function. You can also choose to copy the signature and descriptions of an existing function, by selecting it in the drop-down box.

If you enter the name of a function that already exists, then you will be warned.

See Also

User Guide | Function Wizard Dialog


New Macro dialog

Use this dialog to create a new macro function.

If you enter the name of a function that already exists, then you will be warned.

See Also

Macro Functions (User Guide)


Argument Details

Argument Details Window

The Argument Details Window allows you to edit all aspects of an add-in function's argument, including its name, description and signature.

Opening the Argument Details Window

You can open the window in several different ways:

  • From the XLL+ Function Wizard, right-click on an argument and select "Details".
  • In the XLL+ Function Wizard, select an argument and press ALT+Enter.
  • In the XLL+ Function Wizard, select an argument and press the "Details" tool, which is positioned above the Argument Grid.
  • In the XLL Add-ins window, select an argument and double-click it.
  • In the XLL Add-ins window, select an argument and click on the "Design" tool.

Tabs

The window is divided into four tabs. Folloe the links below for information about each tab.

  • General Tab
  • Vector Tab
  • Matrix Tab
  • Extensions Tab


Argument Details - General Tab

The controls on the General tab of the Argument Details window are divided into groups:

  • Definition
  • Appearance
  • Default value

Definition

This group defines the basic behavior of the argument.

Name

This is the name of the argument, as it will appear in the generated C++ code.

The name must be unique within a function, and you will receive an error message if you try to specify a name that is already in use.

If the name is not a valid C++ variable name, you will recieve an error message.

The name will also be used in the Excel Formula Wizard, unless you specify a Resource ID, in which case a localized name will be used.

Type

Use this control to define the argument's data type. All the built-in data types are listed here, and so are any Extended scalar types that have been registered.

The built-in types are as follows:

Type | C++ type | Description
Boolean | BOOL | Boolean (true or false) value
Double | double | Floating-point number
Int | long | Signed integer (32-bit)
Short Int | short int | Signed integer (16-bit)
String | const CXlStringArg& | Text string
Unsigned Short Int | unsigned short int | Unsigned integer (16-bit)
Reference | const CXlOper* | A reference to an Excel cell range
Value | const CXlOper* | The value(s) contained in an Excel cell range
XlArray | const CXlArray& | An array of numbers

Rank

Value types can be assigned a rank, which defines the number of dimensions they are expected to have.

Rank | Name | Description
0 | Scalar | A single value
1 | Vector | A set of values contained in a single row or column
2 | Matrix | A set of values contained in one or more rows and one or more columns

Some types cannot be assigned a rank, and for these types the Rank control is disabled.

Vector or matrix arguments will be stored in a container, such as std::vector<T>. You can use the Vector Container or Matrix Container controls to specify a particular container class. Otherwise the default class (as defined by the DefaultVectorContainer or DefaultMatrixContainer settings) will be used.

Optional

Check this box to specify that the argument is optional. This means that the user can omit it, in which case a Default value will be used.

Appearance

This group defines the appearance of the argument.

Description

This text will appear in the Excel Formula Wizard.

The description may be localized, in which case it will appear in the language of the user.

For groups, the description builder drop-down is also displayed. This allows you the option to auto-generate the group's description, based on the names and/or descriptions of the group's member arguments.

The Excel Formula Wizard applies some constraints to argument descriptions when it displays them. You may wish to use the Preview Formula Wizard tool to see how the argument's decription will actually appear.

Resource ID

You can choose to localize the name of the argument, as it will appear in the Excel Formula Wizard. If you specify a number for the resource ID, then the ID will be used to get a string from the add-in's resource file. If an entry can be found in the resource file that matches the language of the user, then that entry will be used instead of the argument's name.

See argument names in the User Guide for more details.

Default value

This group controls the behavior of the argument when the input is missing or empty. It is disabled unless the Optional box has been checked.

Default

Use this field to specify the default value that will be used if the argument is found to be missing.

This value will be inserted directly into your code, so it should be a valid C++ expression, and of a type that can be assigned to the destination value.

For example, if you have an optional integer value, you might use any of the following as default values:

0
123
-1000
global_value

global_value will only be legal if you have defined a C++ variable of type long with this name, and the variable is available in the scope of the add-in function.

Use default if Blank

A cell often contains blank text rather than being empty. For example, the following style of formula is often used:

=IF(A1<0,"",A1)

where the value will be blank is A1 is negative.

You can specify that blank values will be treated as missing, in which case the default value will be used.

Use default if Zero

You can specify that zero values will be treated as missing, in which case the default value will be used.

Use default if not Numeric

You can specify that values that are not numbers (or dates) will be treated as missing, in which case the default value will be used.


Argument Details - Vector Tab

The controls on the Vector tab of the Argument Details window are divided into groups:

  • Constraints
  • Truncate
  • Container
  • Fill
  • Bounds

Constraints

This group defines the constraints that will be applied to the shape and size of the argument.

Row or Column

This drop-down allows you to constrain the direction of the input vector. If you specify "Must be a column" or "Must be a row" then the add-in function will return an error such as Expected a column for X if the constraint fails.

See also Argument.VectorDirection property.

Size is equal to

Use this combo-box to constrain the size of the argument.

If you type in an integer, then the vector must contain exactly that number of items or the input will be rejected by the add-in function, with a message such as "Expected 3 cells for X".

If the property contains a name, then a variable of that name will be instantiated in the add-in functions, and the validation code will set it to the size of the array. If the variable has already been set, then it will be tested. If the size is different from the value of the variable, then the input will rejected, with a message such as "Expected 3 cells for X". By using the same bounding variable for two arrays, you can constrain multiple inputs to have the same size, width or height.

If your function has other inputs that are vectors or matrices, then the drop-down list will contain a list of their bounds, so that you can immediately bind the size of this vector to the size of another vector or matrix.

See also Constraining the size of an argument in the User Guide.

If the combo-box is left empty (the default) then there are no constraints on the size of the array.

Reject empty vector

Check this box if your function should reject vectors that contain zero values.

If the user supplies an empty range as the input, then the function will return an error message such as Expected at least one value for X.

Truncate

This group controls how the validation code will detect the edges of the vector within the input range.

The behavior of this group of flags is also dependent on the Fill settings.

If Fill is set to "Do not fill" then truncation occurs at the first empty/blank/zero cell and all cells after the empty cell are ignored, even if they are not empty

If Fill is set to "Fill used area", then the array is truncated after the cell that is not empty/blank/zero. Empty cells before the last empty/blank/zero cell are filled with the Fill value.

Truncate at empty cell

If Fill is set to "Do not fill", the array is truncated at the first empty cell. All cells after the empty cell are ignored, even if they are not empty.

If Fill is set to "Fill used area", then the array is truncated after the last non-empty cell. Empty cells before the last empty cell are filled with the Fill value.

Truncate at blank cell

If Fill is set to "Do not fill", the array is truncated at the first blank cell. All cells after the blank cell are ignored, even if they are not blank.

If Fill is set to "Fill used area", then the array is truncated after the last non-blank cell. Blank cells before the last blank cell are filled with the Fill value.

A formula such as ="" will produce a blank cell.

Truncate at zero cell

If Fill is set to "Do not fill", the array is truncated at the first zero cell. All cells after the zero cell are ignored, even if they are not zero.

If Fill is set to "Fill used area", then the array is truncated after the last non-zero cell. Zero cells before the last zero cell are filled with the Fill value.

Container

Container class combo-box

This control allows you to specify the C++ container class into which the argument's values will be copied.

If you leave it blank, then the default container class (as defined by the DefaultVectorContainer setting) will be used.

For details of the notation to be used for the container class, see Argument.ContainerClass.

Fill

The controls in this group control how the validation code deals with empty cells.

Fill type

This control allows you to control what will be done with input cells that are considered to be empty.

The following values are supported:

Do not fill
Do not fill empty cells
Fill used area
The used area is the continuous area that includes the start (top or left) of the vector and also the last non-empty cell. Empty cells inside that area will be filled. The definition of an empty cell for calculating the used area depends on the Truncate settings.
Fill all cells
Empty cells anywhere in the input range will be filled.

Fill value

This is the value which will be used to fill empty cells if the Fill Type is not set to "Do not fill". It should be a valid C++ expression that can be used to set the target type.

Fill empty cells

If the Fill Type is not "Do not fill", then empty cells will be set to the fill value.

Fill blank cells

If the Fill Type is not "Do not fill", then blank cells will be set to the fill value.

Fill zero cells

If the Fill Type is not "Do not fill", then cells containing the value zero will be set to the fill value.

Bounds

The controls in this group control how the size of the array is measured.

1-based vector

If this box is checked then the target vector will have an empty cell at its start. This is useful if you are passing values to code written for 1-based vectors, such as some Basic, Fortran or Lisp compilers.

Upper bound value

If a constraint has been set on the size of the vector then this control modifies how the size is calculated. This size is compared to the value of the upper bound specified in the Size control.


Argument Details - Matrix Tab

The controls on the Matrix tab of the Argument Details window are divided into groups:

  • Constraints
  • Truncate
  • Container
  • Fill
  • Bounds
  • Layout

Constraints

This group defines the constraints that will be applied to the size of the matrix argument.

Height is equal to

Use this combo-box to constrain the height of the argument (i.e. the number of rows it contains).

If you type in an integer, then the matrix must contain exactly that number of rows or the input will be rejected by the add-in function, with a message such as "Expected 3 rows for X".

If the property contains a name, then a variable of that name will be instantiated in the add-in functions, and the validation code will set it to the height of the array. If the variable has already been set, then it will be tested. If the size is different from the value of the variable, then the input will rejected, with a message such as "Expected 3 rows for X".

By using the same bounding variable for two arrays, you can constrain multiple inputs to have the same size, width or height.

By using the same bounding variable for the hight and the width of a matrix, you can constrain a matrix input to be square.

If your function has other inputs that are vectors or matrices, then the drop-down list will contain a list of their bounds, so that you can immediately bind the size of this vector to the size of another vector or matrix.

See also Constraining the size of an argument in the User Guide.

If the combo-box is left empty (the default) then there are no constraints on the height of the array.

Width is equal to

Use this combo-box to constrain the width of the argument (i.e. the number of columns it contains).

If you type in an integer, then the matrix must contain exactly that number of columns or the input will be rejected by the add-in function, with a message such as "Expected 3 columns for X".

If the property contains a name, then a variable of that name will be instantiated in the add-in functions, and the validation code will set it to the width of the array. If the variable has already been set, then it will be tested. If the size is different from the value of the variable, then the input will rejected, with a message such as "Expected 3 columns for X".

By using the same bounding variable for two arrays, you can constrain multiple inputs to have the same size, width or height.

By using the same bounding variable for the height and the width of a matrix, you can constrain a matrix input to be square.

If your function has other inputs that are vectors or matrices, then the drop-down list will contain a list of their bounds, so that you can immediately bind the size of this vector to the size of another vector or matrix.

See also Constraining the size of an argument in the User Guide.

If the combo-box is left empty (the default) then there are no constraints on the width of the array.

Reject empty matrix

Check this box if your function should reject matrices that contain zero values.

If the user supplies an empty range as the input, then the function will return an error message such as Expected at least one cell for X.

Truncate

This group controls how the validation code will detect the edges of the vector within the input range.

The behavior of this group of flags is also dependent on the Fill settings.

If Fill is set to "Do not fill" then truncation occurs at the first empty/blank/zero cell and all cells after the empty cell are ignored, even if they are not empty

If Fill is set to "Fill used area", then the array is truncated after the cell that is not empty/blank/zero. Empty cells before the last empty/blank/zero cell are filled with the Fill value.

Truncate at empty cell

If Fill is set to "Do not fill", the array is truncated at the first empty cell. All cells after the empty cell are ignored, even if they are not empty.

If Fill is set to "Fill used area", then the array is truncated after the last non-empty cell. Empty cells before the last empty cell are filled with the Fill value.

Truncate at blank cell

If Fill is set to "Do not fill", the array is truncated at the first blank cell. All cells after the blank cell are ignored, even if they are not blank.

If Fill is set to "Fill used area", then the array is truncated after the last non-blank cell. Blank cells before the last blank cell are filled with the Fill value.

A formula such as ="" will produce a blank cell.

Truncate at zero cell

If Fill is set to "Do not fill", the array is truncated at the first zero cell. All cells after the zero cell are ignored, even if they are not zero.

If Fill is set to "Fill used area", then the array is truncated after the last non-zero cell. Zero cells before the last zero cell are filled with the Fill value.

Container

Container class combo-box

This control allows you to specify the C++ container class into which the argument's values will be copied.

If you leave it blank, then the default container class (as defined by the DefaultMatrixContainer setting) will be used.

For details of the notation to be used for the container class, see Argument.ContainerClass.

Fill

The controls in this group control how the validation code deals with empty cells.

Fill type

This control allows you to control what will be done with input cells that are considered to be empty.

The following values are supported:

Do not fill
Do not fill empty cells
Fill used area
The used area is the continuous area that includes the start (top or left) of the vector and also the last non-empty cell. Empty cells inside that area will be filled. The definition of an empty cell for calculating the used area depends on the Truncate settings.
Fill all cells
Empty cells anywhere in the input range will be filled.

Fill value

This is the value which will be used to fill empty cells if the Fill Type is not set to "Do not fill". It should be a valid C++ expression that can be used to set the target type.

Fill empty cells

If the Fill Type is not "Do not fill", then empty cells will be set to the fill value.

Fill blank cells

If the Fill Type is not "Do not fill", then blank cells will be set to the fill value.

Fill zero cells

If the Fill Type is not "Do not fill", then cells containing the value zero will be set to the fill value.

Bounds

The controls in this group control how the size of the array is measured.

1-based rows

If this box is checked then the target matrix will have an empty row at its start. This is useful if you are passing values to code written for 1-based matrices, such as some Basic, Fortran or Lisp compilers.

1-based columns

If this box is checked then the target matrix will have an empty column at its start.

Upper bound value

If a constraint has been set on the size of the vector then this control modifies how the size is calculated. This size is compared to the value of the upper bound specified in the Size control.

Layout

Transpose drop-down

This drop-down can be set to one of two values:

  1. Store as [row,column] (the default)
  2. Store as [column,row]

This will define how the data is stored in the target container. Code may address the data for an argumnt x as x[row][column] or x.at(row, column) in the first case, or as x[column][row] or x.at(column, row) in the second case.


Argument Details - Value List Tab

The Value List tab of the Argument Details window allows you to set up a list of values for an integer argument.

The Value List tab only appears for the integer types:

  • int
  • short int
  • unsigned short int

Use the grid to add, delete, edit and reorder the values in the list. The left column should contain an integer value; the right column should contain a description of the value.

The value list may be used for either or both of two purposes:

  • If you check the List is Exclusive box, then code will be generated so that any input other than one of the values in the list will cause an immediate input error.
  • If you check the Show List in Formula Wizard box, then the value list will appear in the Excel Formula Wizard as a drop-down list.

See Value Lists in the User Guide for more information.


Argument Details - Extensions Tab

The Extensions tab of the Argument Details window allow you to set the parameters of an extended scalar type that has parameters.

The Extensions tab will only appear if the type selected on the General tab is an extended scalar type that has parameters.

Use the property grid to set each of the parameters. These will be used in the generated validation code.


Value List Editor

The Value List Editor windows pops up when you edit an argument's value list property in the XLL+ Function Wizard or the XLL Add-ins window.

Each line contains an acceptable value for the argument. The 1st column should contain an integer value, and the second column should contain a useful description of the value.

Use the Add, Delete, Move Up and Move Down buttons to edit the list of entries, and type in the grid to add or amend entries.

Use the Copy All and Paste to copy the entries to and from Excel, for easier editing.

See Value Lists in the User Guide for more information.


Excel Formula Wizard Preview

You can use the Preview Formula Wizard window to see what an add-in function will look like in the Excel Formula Wizard.

The Excel Formula Wizard is quite restrictive about what it will display. Under some circumstances it will display an extra full stop at the end of a description, or it will truncate your text. The preview is very similar to what the user will see in Excel.

The precise layout of the help in the preview window follows as closely as possible the layout of the Formula Wizard in Excel 2007.

See Also

User Guide


Favorites

The Favorite Arguments window shows the contents of your favorite arguments list.

On the left is a tree which shows all the favorites folder and all its sub-folders. You can create a new folder using the File/New Folder... (Ctrl+N) command. You can move sub-folders to different locations in the tree using drag/drop or cut & paste.

On the right is a list of each of the arguments in the selected folder. You can control which columns are displayed by using the View menu, and putting a check against columns of interest.

You can move arguments to a different folder using drag/drop or cut & paste, or you can copy them to another folder using Ctrl-Drag or copy & paste.

To inspect an argument, right-click on it and select Properties....

Once you're finished managing the list, use the File/Save menu to save your changes.

See Also

Favorites (User Guide)


Add To Favorites

Select a folder to store the argument.

You can use the New Folder... button to create a new sub-folder. It will be created as a sub-folder of the currently selected folder.

See Also

Favorites window | Favorites (User Guide)


Favorite Argument Details

This window shows the details of an argument stored in Favorites.

You cannot make changes to the stored argument.

See Also

Favorites


New Favorites Folder

Use this dialog to enter the name of a new favorites folder.

If you enter the name of a folder that already exists, then you will be asked to choose another.

See Also

Favorites window | Favorites (User Guide)


License Information

If your license is valid, then a description of the license will appear here.

If you are encountering licensing problems, you may find it useful to use the Copy button to copy the license details to the clipboard and mail them to support.


Concurrent License Information

This topic applies only to the retail version of the product. It is not pertinent to the trial version.

Status

If you are not currently logged on to a license server, select a server from the "License server" combo, and use the "Logon" button to lock a license.

You can check the "Always log on automatically" check-box to ensure that Visual Studio always attempts to lock a license as soon as it starts.

If you are currently logged on, then you can use the "Release" button to log off, freeing up the license for another user.

Status

Use this panel to find out who is currently using the licenses on the listed license servers, and which applications are locking the license instances.


Trial Expired

This window appears because your trial license has expired.

If you believe you have a retail license, and this window still appears, then you need to uninstall the Trial version of XLL+ and install the retail version.

If you believe that you need longer to try out the product, please contact at the email address provided, enclosing the information in the "Request an extension" panel, and the reason for the extension.


License Failure

This window appears because the licensing system detected an error.

You can use the Copy button to copy the error information to the clipboard.


Select Function Dialog

Use this window to select a function to be displayed in the XLL+ Function Wizard. All the add-in functions from the current file will be listed.

You can double-click on an item, or press the OK button.


Incompatible Data Version Warning

This form appears if you attempt to save a function in a format which will cause some of its features to be lost. If the features are important, you should consider saving the function in a more advanced format.


Commands

The table below lists the common commands of the XLL+ Function Wizard.

Command | Description | Shortcut | Menu
OK/Save & Exit | Save changes and close the wizard. | Enter | File
Cancel | Abandon changes and close the wizard. | Escape |
New Function | Create a new function. | Ctrl+N | File
New Macro | Create a new macro add-in function. |  | File
Select Function | Select a function from the active document. |  | File
Show Advanced Properties | Show or hide advanced properties. |  | View
Preview Function Wizard | Display a preview of the Excel Formula Wizard. |  | View
Undo | Undo the last change. | Ctrl+Z | Edit
Cut | Cut the selected text to the clipboard. | Ctrl+X | Edit
Copy | Copy the selected text to the clipboard. | Ctrl+C | Edit
Paste | Paste text from the clipboard to the field currently being edited. | Ctrl+V | Edit
Delete | Delete the selected text. | Delete | Edit
Cut Argument | Cut the selected argument to the clipboard. |  | Argument
Copy Argument | Copy the selected argument to the clipboard. |  | Argument
Paste Argument | Paste a new argument from the clipboard. |  | Argument
Add Argument | Add a new argument to the function. | Ctrl+I | Argument
Argument Details | Edit all the properties of the selected argument. | Alt+Enter | Argument
Delete Argument | Delete the selected argument. |  | Argument
Move Argument Up | Move the selected argument to an earlier position in the list. |  |
Move Argument Down | Move the selected argument to a later position in the list. |  |
Scalar | Set the selected argument to be a single value. | Ctrl+0 | Argument
Vector | Set the selected argument to be a one-dimensional array of values. | Ctrl+1 | Argument
Matrix | Sets the selected argument to be a two-dimensional array. | Ctrl+2 | Argument
Refresh Preview Template | Reload template file and regenerate the preview. |  | Tools


Add To Favorite Arguments

Toolbar: |
Menu: | Argument

This command opens the Add To Favorites window, to let you save one or more arguments as a favorite, which can be imported into other functions, and distributed to other team members to ensure consistency between argument signatures and documentation.

See Also

XLL+ Function Wizard


Argument Details

Shortcut: | Alt+Enter
Toolbar: |
Menu: | Argument

This command opens the Argument Details window to let you modify the selected argument.

See Also

XLL+ Function Wizard


Cancel

Shortcut: | Escape
Button: | Cancel

Abandon all changes, and exit the Function Wizard.

See Also

XLL+ Function Wizard


Copy

Shortcut: | Ctrl+C
Toolbar: |
Menu: | Edit

Copy the selected text to the clipboard.

See Also

XLL+ Function Wizard


Copy Argument

Toolbar: |
Menu: | Argument

This command copies the selected arguments to the clipboard. You can then paste them into another function or to a different position within the same function (in which case they will be renamed, to avoid duplication).

Note that you can also use drag-and-drop in the Arguments grid to duplicate arguments, if you hold down the Control key as you drop.

See Also

XLL+ Function Wizard


Cut

Shortcut: | Ctrl+X
Toolbar: |
Menu: | Edit

Delete the selected text and copy it to the clipboard.

See Also

XLL+ Function Wizard


Cut Argument

Toolbar: |
Menu: | Argument

This command copies the selected arguments to the clipboard and removes them from the current function. You can then paste them into another function or to a different position within the same function.

See Also

XLL+ Function Wizard


Delete

Shortcut: | Delete
Toolbar: |
Menu: | Edit

Delete the selected text.

See Also

XLL+ Function Wizard


Delete Argument

Toolbar: |
Menu: | Argument

This command deletes the selected arguments and removes them from the current function.

See Also

XLL+ Function Wizard


Favorite Arguments

Toolbar: |
Menu: | Argument

This command opens the Favorite Arguments window, to let you select one or more arguments to be imported into the current function.

See Also

XLL+ Function Wizard


GoTo Error Location

Toolbar: |
Menu: | Errors

This command jumps to the location of the selected error in the Errors tab.

See Also

XLL+ Function Wizard


Group Arguments

Toolbar: |
Menu: | Argument

This command creates a new group and moves all the selected arguments into it.

See Also

XLL+ Function Wizard


Matrix

Shortcut: | Ctrl+2
Toolbar: |
Menu: | Argument

This command makes the selected argument a matrix, rather than a scalar or vector.

See Also

XLL+ Function Wizard


Move Argument Down

Toolbar: |
Menu: | Argument

This command moves the selected argument to a position one further down in the argument list.

Note that you can also use the mouse to drag-and-drop the argument within the argument list.

See Also

XLL+ Function Wizard


Move Argument Left

Toolbar: |
Menu: | Argument

This command moves the selected argument out of its current group, into the containing group, or the function.

Note that you can also use the mouse to drag-and-drop the argument within the argument list.

See Also

XLL+ Function Wizard


Move Argument Right

Toolbar: |
Menu: | Argument

This command moves the selected argument into the nearest appropriate group.

Note that you can also use the mouse to drag-and-drop the argument within the argument list.

See Also

XLL+ Function Wizard


Move Argument Up

Toolbar: |
Menu: | Argument

This command moves the selected argument to a position one higher up in the argument list.

Note that you can also use the mouse to drag-and-drop the argument within the argument list.

See Also

XLL+ Function Wizard


New Argument

Shortcut: | Ctrl+I
Toolbar: |
Menu: | Argument

This command creates a new argument at the end of the current set of arguments, and opens the Argument Details window to let you modify it.

See Also

XLL+ Function Wizard


New Choice

Toolbar: |
Menu: | Argument

This command creates a new choice group at the end of the current set of arguments, and opens the Argument Details window to let you modify it.

See Also

XLL+ Function Wizard


New Function

Shortcut: | Ctrl+N
Button: | New Function
Toolbar: |
Menu: | File

Create a new function. When the function is saved it will be appended to the end of the current source document.

If the current function has any changes, the Function Wizard will keep track of them. All changes to all functions will be committed to the document when you close the Wizard by pressing the OK button.

The New Function dialog will be shown.

See Also

XLL+ Function Wizard


New Group

Toolbar: |
Menu: | Argument

This command creates a new argument group at the end of the current set of arguments, and opens the Argument Details window to let you modify it.

See Also

XLL+ Function Wizard


New Macro

Toolbar: |
Menu: | File

Create a new macro function, with a default name. When the function is saved it will be appended to the end of the current source document.

If the current function has any changes, the Function Wizard will keep track of them. All changes to all functions will be committed to the document when you close the Wizard by pressing the OK button.

See Also

XLL+ Function Wizard


OK

Shortcut: | Enter
Button: | OK
Menu: | File

Save all changes to all edited functions, and exit the Function Wizard.

Changes will be written to the DevStudio window containing the source file, but the file itself will not be saved. So if you want to undo all your changes when you return to DevStudio, you can use the Undo command to reverse them.

See Also

XLL+ Function Wizard


Paste

Shortcut: | Ctrl+V
Toolbar: |
Menu: | Edit

Paste text from the clipboard into the current field or cell.

See Also

XLL+ Function Wizard


Paste Argument

Toolbar: |
Menu: | Argument

This command pastes into the current function, at the selected position, any arguments that are currently copied to the clipboard. The arguments may be renamed to avoid duplication.

Note that you can also use drag-and-drop in the Arguments grid to copy arguments, if you hold down the Control key as you drop.

See Also

XLL+ Function Wizard


Preview Formula Wizard

Toolbar: |
Menu: | View

Use this command to see how an add-in function will appear in the Excel Formula Wizard. The Formula Wizard Preview window will show a preview of the current function.

See Also

XLL+ Function Wizard | User Guide


Refresh Preview

Toolbar: |
Menu: | Tools

Use this command to force the function code in the Preview tab to be regenerated. This is a useful tool if you are simultaneously editing the code generation template in another editor.

See Also

XLL+ Function Wizard


Scalar

Shortcut: | Ctrl+0
Toolbar: |
Menu: | Argument

This command makes the selected argument a scalar, i.e. a single value, rather than a vector or matrix.

See Also

XLL+ Function Wizard


Select Function

Toolbar: |
Menu: | File

Select a function from the active document. A drop-down menu will appear, containing the names of the functions in the active document.

If there are too many to display in a menu, then the final menu item will be "More Functions...". Click this item to select a function from a list. The Select Function dialog will be shown.

You can use the MaxFunctionsOnMenu setting to vary the maximum number of functions displayed on the drop-down menu.

See Also

XLL+ Function Wizard


Select Function (Prompt)

Toolbar:

Select a function contained in the active document, from a list presented in the Select Function dialog.

See Also

XLL+ Function Wizard


Show Advanced Properties

Toolbar: |
Menu: | View

Use this command to show or hide advanced properties in the properties grid of the Details tab. Many properties are rarely used and do not need to shown most of the time.

See Also

XLL+ Function Wizard


Show Error Details

Toolbar: |
Menu: | Errors

This command shows the details of the selected error in the Errors tab.

See Also

XLL+ Function Wizard


Undo

Shortcut: | Ctrl+Z
Toolbar: |
Menu: | Edit

Undo the last change you made to the current function.

See Also

XLL+ Function Wizard


Ungroup Arguments

Toolbar: |
Menu: | Argument

This command ungroups the selected arguments or group.

See Also

XLL+ Function Wizard


Vector

Shortcut: | Ctrl+1
Toolbar: |
Menu: | Argument

This command makes the selected argument a vector, rather than a scalar or matrix.

See Also

XLL+ Function Wizard


View Alphabetical Properties

Toolbar: |
Menu: | View

Use this command to order the properties in the properties grid of the Details tab alphabetically, ignoring category. Properties may be grouped by category, or sorted in alphabetical order.

See Also

XLL+ Function Wizard


View Arguments

Toolbar: |
Menu: | View

Use this command to switch to the Arguments tab.

See Also

XLL+ Function Wizard


View Categorized Properties

Toolbar: |
Menu: | View

Use this command to group the properties in the properties grid of the Details tab by category. Properties may be grouped by category, or sorted in alphabetical order.

See Also

XLL+ Function Wizard


View Container Column

Menu: View

Use this command to show or hide the Container column in the arguments grid.

See Also

XLL+ Function Wizard | ContainerClass property


View Default Value Column

Menu: View

Use this command to show or hide the Default Value column in the arguments grid.

See Also

XLL+ Function Wizard | DefaultValueText property


View Details

Toolbar: |
Menu: | View

Use this command to switch to the Details tab.

See Also

XLL+ Function Wizard


View Errors

Toolbar: |
Menu: | View

Use this command to switch to the Errors tab.

See Also

XLL+ Function Wizard


View Extensions

Toolbar: |
Menu: | View

Use this command to switch to the Extensions tab.

See Also

XLL+ Function Wizard


View Features

Toolbar: |
Menu: | View

Use this command to switch to the Features tab.

See Also

XLL+ Function Wizard


View Optional Column

Menu: View

Use this command to show or hide the Optional column in the arguments grid.

See Also

XLL+ Function Wizard | UseDefault property


View Preview

Toolbar: |
Menu: | View

Use this command to switch to the Preview tab.

See Also

XLL+ Function Wizard


View Resource ID Column

Menu: View

Use this command to show or hide the Resource ID column in the arguments grid.

See Also

XLL+ Function Wizard | Resource ID | Types of string | String substitutions


View Row Numbers

Menu: View

Use this command to show or hide row numbers on the arguments grid.

See Also

XLL+ Function Wizard


XLL+ ToolWindow

The XLL Add-ins Window can be used as an alternative to the XLL+ Function Wizard.

The Add-ins window is available at all times within Visual Studio; you don't need to pop it up to see it. The window shows a list of all of the add-in functions in the current source file. It also contains a toolbar with a set of commands for developing XLL add-in functions.

Topics

XLL Add-ins Window on-line help
Summary of commands
User Guide: The XLL Add-ins ToolWindow
User Guide: Showing the XLL Add-ins Window
User Guide: Upgrading from a previous version of XLL+

See Also

User Guide | Summary of Commands | Help for XLL Add-ins window


Windows

The various panels and windows of the XLL Add-ins Window are listed below.

XLL Add-ins Window
XLL+ Options Pages
Extensions Window
Export To XML
Extended Type Load Results Window
Imported Assemblies
Import Editor


XLL Add-ins Window

The XLL Add-ins Window can be used as an alternative to the XLL+ Function Wizard.

The Add-ins window is available at all times within Visual Studio; you don't need to pop it up to see it. The window shows a list of all of the add-in functions in the current source file.

Toolbar

At the top of the window is a toolbar with a set of commands for developing XLL add-in functions. See Summary of commands for a list of these commands.

Functions pane

The window's upper pane shows a list of all the add-in functions in the current document.

Each function is listed with a summary of its arguments. If there are any errors or warnings for a function, then a warning symbol will appear next to the function's name. You can see the error messages for a function by hovering the mouse over the function.

You can double-click on a function to edit it in the XLL+ Function Wizard, and use the Go to function command to jump to it in the source code window.

You can edit the selected function using the Visual Studio Properties window. If you select multiple functions, you can use the Properties window to edit all of them simultaneously. So you could for example change the category of the add-in functions in the current source file by selecting them all in the Functions pane (Ctrl+A is the short-cut), and changing the category in the Properties window.

Arguments pane

The arguments of the selected function are shown in the lower part of the window.

You can double-click on an argument to edit it in the Argument Details window.

You can edit the selected argument directly using the Visual Studio Properties window.

You can right-click and use the Copy command to copy an argument from one function, and then use the Paste command to paste it into another function.

Topics

Summary of commands
User Guide: The XLL Add-ins ToolWindow
User Guide: Showing the XLL Add-ins Window

See Also

XLL+ ToolWindow: Overview | User Guide


Options Pages

The XLL+ Options pages are listed below. Use the Tools/Options... menu of Visual Studio to open them.

General Options Page
Template Settings Options Page
Extensions Options Page


General Options Page

This page lets you set global properties in XLL+. These properties will apply to all projects.

See Settings Properties for a list of the settings that can be controlled from this page.


Template Settings Options Page

This page lets you control the code generation templates used by XLL+.


Extensions Options Page

This page lets you manage XLL+ extensions.

Use the file list to add, delete and reorder the list of extension files.

Use the Test button to check that the list of files loads properly.

Use the View button to inspect all the extensions in the list in the Extensions window.

You can open an extension file in the Visual Studio editor by selecting the extension file in the list, and clicking the Edit button.


Extensions Window

The XLL+ Extensions displays a list of all currently loaded extensions, including Scalar extended types and Function extensions.

Expand the tree on the left-hand side to see details of each extension on the right-hand side.

You cannot edit the extensions in this window. Instead, you should edit the extension file.

Help is also available for the following nodes in the tree:

Function
Scalar type
Code
Parameter

See Also

Scalar extended types | Function extensions


Function Extension

The properties of the selected function extension are shown in the property grid on the right-hand side. Some of the properties are described below.

Name

The unique name of the extension. This name will not appear in C++ code, and therefore does not need to be a valid C++ name. However, it must be unique among function extensions, and it cannot be changed without breaking any functions that use it.

HeaderFiles

A list of header files that are required in order for the extension code to compile. If the list contains more than one file, they should be separated with semi-colons. A #include statement will be added (if necessary) to the source file for each of the header files listed.

IgnoreLocalHeaders

If IgnoreLocalHeaders is true, then the #include statement will exclude the local directory, e.g.:

CopyC++
#include <myheader.h>

If IgnoreLocalHeaders is false, then the compiler will look in the current directory first, e.g.:

CopyC++
#include "myheader.h"

See Also

Function extensions | Extensions Window


Code Definition

Each code element defines a fragment of code that will be injected into your function if the extension is utilized.

See Function extensions for more detail.

InsertionPoint

This property defines where the code will be inserted. See Code injection in the User Guide for more details.

Code

The code that will be inserted into the add-in function. The element may include macros that will be substituted by the code generator.

Macros must be surrounded by $ signs. Property macros must also begin with a #. e.g.: $#ExportedName$.

See Also

Function extensions | Extensions Window


Parameter

A parameter defines a means by which the developer can modify the behavior of an extension at compile-time and at run-time.

A parameter to an extended type will appear in the argument grid of the XLL+ Function Wizard. A parameter for a function extension will appear on the Extensions tab.

See Parameters for more details.

See Also

Extensions Window


Scalar Type Extension

The ScalarType element defines an extended type.

The properties of an extended type are discussed in the User Guide under XLL+ extension files.

See Also

Scalar extended types | Extensions Window


Export To XML

This window lets you save some or all of the add-in functions in the current project to XML format.

This is the format used by the help generator to store the signatures and help texts of a function.

Note that this XML format only includes the information stored by the XLL+ Function Wizard - it does not include the source code added by the developer.


Extended Type Load Results Window

This form lists each of the extension files that you have just attempted to load. For each file the number of extensions successfully loaded is given.

To see the details of the extensions, use the Extensions Window


Imported Assemblies

This window lets you select a .NET assembly, which will be imported into your add-in. A file containing C++ wrapper functions will be generated from the assembly and its documentation file, and will be added to your project.

Note that only .NET assemblies that are already present in the project as references will be listed. If you want to import an assembly that is not listed, first add a reference to it (see .NET Import Wizard: Adding a reference).

Put a check against the name of any library you want to import. When you select it, its details will appear on the right hand side of the window.

Use the Edit button to show the Import Editor, which allows you to edit the set of classes, methods and properties that will be imported, and control the behavior the generated add-in functions.

If you have a XML documentation file for the imported assembly, and it is not in the same directory as the assembly DLL file, use the Documentation field to specify its location.

You can use the Options tab to change the default settings, including the name of the generated C++ file.


Import Editor

The Import Editor pops up when you click the Edit button in the Imported Assemblies Window. The editor shows all the exportable methods and properties in the imported assembly.

The methods can be viewed in a tree or in a list. Use the tool-buttons to switch between Tree View and List View.

Using the tree view, you can apply settings at the assembly level or at the type level, and these will apply to all methods and properties in the types affected. For instance, you could set the Category property at assembly level to Math & Trig to set the category of all exported methods. Or you could set the Filter property of a Type to StaticMethods to ensure that all the type's eligible static methods will be exported.

Using either the tree view or the list view, you can also apply settings to individual methods and parameters, controlling exactly how they are exported as Excel add-in functions and arguments.

You can control many aspects of the function's behaviour and how the arguments are treated, including:

  • Function name in Excel
  • Function category
  • Argument names
  • Default values for omitted arguments
  • Array handling rules for arguments
  • Help text

When you are happy with the import settings for the assembly, click OK to save your changes and return to the Imported Assemblies Window. You can change the settings at any time, by returning to the Import Editor.


Initialization Error

This window appears if an error occurs during the initialization of the XLL+ Visual Studio package.

You should refer to the Trouble-shooting section of the User Guide for help on fixing initialization errors.


Commands

The table below lists the commands available from the XLL Add-ins window.

Command | Description
New Function | Create a new add-in function.
New Macro | Create a new macro add-in function.
Design | Opens the Function Wizard or the Argument Details window to edit the currently selected function or argument.
Go To Function | Moves the selection of the current document to the selected function.
Regenerate functions | Regenerates all the C++ code for the selected functions.
Refresh | Refreshes the XLL Add-ins window, by rereading the current C++ document.
Collapse All Hidden Regions | Collapses any collapsible regions within generated code, for all functions in the current C++ document.
Preview Function Wizard | Display a preview of the Excel Formula Wizard.
Upgrade Project to XLL+ 6 | Upgrades a project built with an earlier version of XLL+ to XLL+ 6.
Add VersionInfo Function | Inserts a standard Version Info add-in function, providing information about the XLL.
Set Up Debugging | Sets up the debugger command line settings for the current build.
Import Assemblies | Lets you import a .NET assembly and automatically create add-in functions from its methods.
Update Help Command line | Updates the build settings for the help file.
Set Help IDs | Sets a unique help ID for each add-in function in the current project.
Ribbon Manager | Opens the Ribbon Manager configuration file for the development computer.
Manage Extensions | Displays the XLL+ extensions options window.
View Extensions | Displays all currently loaded XLL+ extensions.
Reload Extensions | Reloads all currently loaded XLL+ extensions.
Export to XML | Export function definitions as an XML file.
Favorite Arguments | Opens the Favorite Arguments window.
Options | Shows the Options dialog.
About | Shows the Help/About dialog.


About

Menu: Tools

This command opens the XLL+ About window. This contains all details of your installation, and may be useful for diagnosing problems.

See Also

XLL Add-ins Window Commands


Add VersionInfo Function

Toolbar: |
Menu: | Tools

This command inserts a standard Version Info add-in function. This function returns details of the add-in, including its author, build and version number, to Excel.

You may find a function of this kind very useful if you are supporting users remotely.

See Also

XLL Add-ins Window Commands


Collapse All Hidden Regions

Toolbar:

This command collapses any regions within XLL+ generated code that contain #pragma region/endregion.

Use this command to hide the vast bulk of the implementation code, leaving only your own functions visible.

Use the CollapseAllSections setting to make this behavior automatic.

See Also

XLL Add-ins Window Commands


Design

Toolbar:

If a function is selected in the XLL Add-ins window, this command will open the XLL+ Function Wizard to allow it to be edited.

If an argument is selected, then the Argument Details window will be opened for the selected argument.

You can also invoke this command by double-clicking on a function or an argument in the XLL Add-ins window.

See Also

XLL Add-ins Window Commands


Export To XML

Toolbar: |
Menu: | Tools

This command opens the Export to XML window, which you can use to export some or all of the add-in functions in the current project to XML format.

See Also

XLL Add-ins Window Commands


Favorite Arguments

Toolbar: |
Menu: | Tools

This command opens the Favorite Arguments window.

You can use the window to share argument definitions and descriptions with other members of your team, to ensure adherence to standards, and to reduce coding effort.

See Also

XLL Add-ins Window Commands


Go to function

Toolbar:

If a function is selected in the XLL Add-ins window, this command will move the current document's selection to the function's code, just after the end of the generated code.

See Also

XLL Add-ins Window Commands


Import Assemblies

Toolbar: |
Menu: | Tools

This command shows the Imported Assemblies Window, which lets you import .NET assemblies and automatically create XLL+ add-in functions as wrappers for the .NET methods.

See Also

XLL Add-ins Window Commands


Manage extensions

Menu: Tools

Use this command to display the XLL+ Options / Extensions window. This will allow you to manage the list of active XLL+ extension files.

See Also

XLL Add-ins Window Commands


New Function

Toolbar:

Creates a new function, and opens the New Function dialog to allow it to be edited.

See Also

XLL Add-ins Window Commands


New Macro

Toolbar:

Creates a new macro function, and opens the New Macro dialog to allow its name to be entered.

See Also

XLL Add-ins Window Commands


Options

Toolbar: |
Menu: | Tools

This command opens the Visual Studio Options window to the XLL+/General page. This is where you can change global settings and preferences.

See Also

XLL Add-ins Window Commands


Preview Formula Wizard

Toolbar:

Use this command to see how an add-in function will appear in the Excel Formula Wizard. The Formula Wizard Preview window shows a preview of the currently selected function.

See Also

XLL Add-ins Window Commands


Refresh window

Toolbar:

This command refreshes the XLL Add-ins window, and the Visual Studio Properties window. It re-reads the source code from the active document and rebuilds the functions' object model.

Use this command to immediately apply any changed global settings to the display of the XLL Add-ins window or the Visual Studio Properties window.

See Also

XLL Add-ins Window Commands


Regenerate functions

Toolbar:

If one or more functions are selected in the XLL Add-ins window, this command will cause all their code to be regenerated. Code outside the //{{XLP_SRC delimiters - i.e. code you have added yourself - will not be affected.

See Also

XLL Add-ins Window Commands


Reload extensions

Menu: Tools

Use this command to reload all the XLL+ extensions currently in use. If you have made changes to any of the extension files, this is the quickest way to load the changes.

You should regenerate any functions to which you wish to apply the changed extensions.

See Also

XLL Add-ins Window Commands


Ribbon Manager

Menu: Tools

Use this command to open the Ribbon Manager configuration file on the development computer. If the file does not exist, the menu will be disabled. This will allow you to manage the list of XLL+ add-ins that are registered with the Ribbon Manager.

See Also

XLL Add-ins Window Commands


Set Help IDs

Toolbar: |
Menu: | Tools

This command sets a unique help ID for each add-in function in the current project.

See Also

XLL Add-ins Window Commands


Set Up Debugging

Toolbar: |
Menu: | Tools

This command sets up the debugger command line settings for the current build. The debugger will run the default version of Excel and will open the XLL.

See Also

XLL Add-ins Window Commands


Update Help Command Line

Toolbar: |
Menu: | Tools

This command updates the build settings for the help file. If you have added any new C++ source files that contain add-in functions or if you added a dependency on an extension, then you should use this command to update the command line in the build settings so that the new file is included.

See Also

XLL Add-ins Window Commands


Upgrade Project to XLL+ 6

Menu: Tools

This command upgrades a project built with an earlier version of XLL+ to XLL+ 6.0. Changes may be made to the project file, resource files and to each add-in function.

All changed files are first copied to a backup directory. An HTML conversion report is displayed at the end of the upgrade.

See Also

XLL Add-ins Window Commands


View extensions

Menu: Tools

Use this command to inspect the contents of all the XLL+ extensions currently in use.

See Also

XLL Add-ins Window Commands


View License Information

Menu: Tools

Use this command to see the current status of the XLL+ license in use. The License Information window will be shown.

See Also

XLL Add-ins Window Commands


XLL+ AppWizard

The pages of the XLL+ AppWizard are listed below.

Overview
Application Settings


XLL+ Application Wizard - Overview

The XLL+ Application Wizard allows you to create an XLL add-in project.

The Overview page summarizes the settings of the project. To make changes, click on the Next button or on the Application Settings link.

This will show the Application Settings page.

See Also

XLL+ AppWizard - Application Settings


XLL+ Application Wizard - Application Settings

The Application Settings page of the XLL+ Application Wizard allows you to control the content and build flags of a new XLL add-in project. The settings are listed below.

For full details of the code that is generated for each option, see XLL+ Application Wizard - Generated Code.

XLL friendly name

This is the name that will be displayed in the Excel Add-ins dialog.

You can easily change it later, by changing the value of CMyApp::m_pszDefName in the application code.

Run-time library

XLL+ comes with two versions of the run-time libraries: one that works with Microsoft's MFC (Microsoft Foundation Classes) and one that uses standard STL (Standard Template Library) classes.

Unless you are using MFC to build parts of the user interface or need to use other parts of MFC for technical reasons, it is better to use the STL libraries.

Create 64-bit version

Check this box to create an a 64-bit version of the add-in for use with 64-bit versions of Excel, in addition to the 32-bit version. A 32-bit version will always be created, whether the box is checked or not.

Use Unicode libraries

This switch chooses the character set for your project. If you wish to use Unicode, check the box.

You can change the project settings to or from Unicode later yourself, if necessary, as follows:

  • For unicode builds, add UNICODE and _UNICODE to the list of "Preprocessor Definitions" under "C/C++/Preprocessor". For non-unicode builds, remove them.
  • For unicode builds, under "General" set "Character Set" to "Use Unicode Character Set". For non-unicode builds, select "Use Multi-Byte Character Set".

Common Language Runtime Support (/clr)

This switch enables CLR support for your project. If you wish to use the Common Language Runtime, or use your own .NET assemblies, check the box.

You can change the project settings to or from CLR later yourself, if necessary, as follows:

  • Under the "General" node: for CLR builds, set "Common Language Runtime support" to "Common Language Runtime Support (/clr)". For non-CLR builds, set it to "No Common Language Runtime support".
  • Under "C/C++/Code Generation": for CLR builds, set "Runtime Library" to "Multi-threaded DLL (/MD)" or "Multi-threaded Debug DLL (/MDd)", as appropriate for debug or release configurations. For non-CLR builds, choose whichever setting you prefer.
  • Under "C/C++/Code Generation": for CLR builds, set "Basic Runtime Checks" to "Default". For non-CLR builds, set "Basic Runtime Checks" to "Both (/RTC1, equiv. to /RTCsu)".

Add XLL+ Include and Lib paths

If this box is checked, then the directories containing XLL+ will be added to the project's Include and Lib paths.

If you uncheck the box, you will need to make sure that the XLL+ header files and library files are available to the compiler and linker respectively.

If you have moved the XLL+ header files and libraries since you installed them, then use the XLL+ Options page to change the values of Settings.IncludePath and Settings.LibPath. These are the values that are used by the AppWizard.

Include a cache for results

Check this box to add a results cache to your project. This can radically speed up the performance of the add-in when the same results are calculated repeatedly.

See Results cache in the User Guide for more details.

Save the cache to file

Check this box to save the results cache to file. Results calculated and cached during one session of Excel will be available again when Excel is restarted.

Add to the ribbon

If this box is checked, then skeleton code and resources to create a group on the Office ribbon will be added to your project.

For more information about the ribbon see The Ribbon in the User Guide.

If you do not check it, and you need to add the code later, see Adding Ribbon support to a project in the Ribbon Reference Guide for instructions.

Add a menu

If this box is checked, then skeleton code to create a menu will be added to your project.

If you do not check it, and you need to add the code later, see Menus in the User Guide for instructions.

Add a toolbar

If this box is checked, then a toolbar will be added to your project.

If you do not check it, and you need to add the code for a toolbar later, see Toolbars in the User Guide for instructions.

Generate a VersionInfo function

This option will add a standard VersionInfo add-in function to your XLL, which can be used in a spreadsheet to get details of the author, date, version build and copyright of the XLL.

You can add a VersionInfo function later by using the Add VersionInfo Function command.

Enable Logging

This option will add basic logging functionality to the project, using the framework in cpplog.h. The following changes are made:

  1. #include <cpplog.h> is added to the main source file.
  2. A logger "g_logger" is added to the main source file.
  3. A logging configuration file, <AppName>.xll.log.ini is added to the project, and is copied to the output directory (alongside the XLL itself) when the project is built.
  4. The logging framework is initialized from the configuration file during the OnXllOpenEx event, when the XLL is opened.

For more information on logging, see Logging in the User Guide.

See Also

XLL+ AppWizard - Overview | XLL+ AppWizard - Generated Code | Project Settings


XLL+ Application Wizard - Generated Code

The code blocks generated by the various settings of the XLL+ Application Wizard are listed below.

In the code below, the add-in is assumed to be called MyAddin; your file names and your code should replace MyAddin with the name of your add-in.

XLL friendly name

This is the name that will be displayed in the Excel Add-ins dialog.

It is defined in MyAddin.cpp:

CopyC++
/* static */ LPCTSTR CMyAddinApp::m_pszDefName = _T("MyAddin");

Create 64-bit version

To create a 64-bit version at a later time:

  1. In Visual Studio, click the menu item Build/Configuration Mnager....
  2. In the Active solution platform combo box, select <New...>.
  3. In the New Solution Platform dialog, select x64. Ensure that Create new project platforms is checked, and press OK.

Use Unicode libraries

This switch chooses the character set for your project, via the project settings, as follows:

  • For unicode builds, add UNICODE and _UNICODE to the list of "Preprocessor Definitions" under "C/C++/Preprocessor". For non-unicode builds, remove them.
  • For unicode builds, under "General" set "Character Set" to "Use Unicode Character Set". For non-unicode builds, select "Use Multi-Byte Character Set".

Common Language Runtime Support (/clr)

This switch enables CLR support for your project.

You can change the project settings to or from CLR later yourself, if necessary, as follows:

  • Under the "General" node: for CLR builds, set "Common Language Runtime support" to "Common Language Runtime Support (/clr)". For non-CLR builds, set it to "No Common Language Runtime support".
  • Under "C/C++/Code Generation": for CLR builds, set "Runtime Library" to "Multi-threaded DLL (/MD)" or "Multi-threaded Debug DLL (/MDd)", as appropriate for debug or release configurations. For non-CLR builds, choose whichever setting you prefer.
  • Under "C/C++/Code Generation": for CLR builds, set "Basic Runtime Checks" to "Default". For non-CLR builds, set "Basic Runtime Checks" to "Both (/RTC1, equiv. to /RTCsu)".

Add XLL+ Include and Lib paths

If this box is checked, then the directories containing XLL+ will be added to the project's Include and Lib paths.

If you uncheck the box, you will need to make sure that the XLL+ header files and library files are available to the compiler and linker respectively.

  1. In the Project Properties dialog, set Configuration to All Configurations and Platform to All Platforms.
  2. Select the node C/C++ / General and add one of the following to the Additional Include Directories list:
    Visual Studio | Path
    VS 2005 | $(Xlp80InstallDir7)include
    VS 2008 | $(Xlp90InstallDir7)include
    VS 2010 | $(Xlp100InstallDir7)include
  3. Select the node Linker / General and add one of the following to the Additional Library Directories list:
    Visual Studio | Path
    VS 2005 | $(Xlp80InstallDir7)lib\$(PlatformName)
    VS 2008 | $(Xlp90InstallDir7)lib\$(PlatformName)
    VS 2010 | $(Xlp100InstallDir7)lib\$(PlatformName)

If you have moved the XLL+ header files and libraries since you installed them, then use the XLL+ Options page to change the values of Settings.IncludePath and Settings.LibPath. These are the values that are used by the AppWizard.

Include a cache for results

This box adds a results cache to your project.

In MyAddin.h, the following will appear before the class definition:

CopyC++
#include <xlserialize.h>

In MyAddin.h, the following will appear within the public section of the class definition:

CopyC++
// Data
    CXlOperCache m_cache;

Save the cache to file

Check this box to save the results cache to file.

In MyAddin.h, the following will appear within the public section of the class definition, after CXlOperCache m_cache;:

CopyC++
CString m_strCacheFile;

In MyAddin.cpp, the following will appear within the method CMyAddinApp::OnXllOpenEx():

CopyC++
// Restore the cache (if it exists), ignoring failure
if (CXlOperCache::GetUserCacheFilePath(m_strCacheFile))
    m_cache.Restore(m_strCacheFile);

In MyAddin.cpp, the following will appear within the method CMyAddinApp::OnXllClose():

CopyC++
// Save cache
m_cache.Save(m_strCacheFile);

Add to the ribbon

If this box is checked, then skeleton code and resources to create a group on the Office ribbon will be added to your project. See Adding Ribbon support to a project for instructions.

Add a menu

If this box is checked, then skeleton code to create a menu will be added to your project.

In MyAddin.h, the following will appear before the class definition:

CopyC++
#include <xlmenu.h>

In MyAddin.h, the following will appear within the public section of the class definition:

CopyC++
// Menu
    CXlMenu m_menu;

In MyAddin.cpp, the following will appear within the method CMyAddinApp::OnXllOpenEx():

CopyC++
if (!SupportsRibbon())
{
    // Set up menu
    // TODO: Change the menu captions
    //       Write an add-in function to be called when the menu item is clicked
    //       Add other menu items
    m_menu.SetTexts(_T("&My menu"));
    m_menu.AddItem(_T("&My menu task"), _T("MyAddinFunction"));
    m_menu.Create();
}

In MyAddin.cpp, the following will appear within the method CMyAddinApp::OnXllClose():

CopyC++
// Delete menu
if (!SupportsRibbon())
    m_menu.Destroy();

Add a toolbar

If this box is checked, then a toolbar will be added to your project.

In MyAddin.h, the following will appear within the public section of the class definition:

CopyC++
// Toolbar
    static LPCTSTR m_pszToolbarName;

In MyAddin.cpp, the following will appear before the class implementation:

CopyC++
#include <xltoolbar.h>

In MyAddin.cpp, the following will appear within the method CMyAddinApp::OnXllOpenEx():

CopyC++
if (!SupportsRibbon())
{
    // Create toolbar
    // TODO: Change the toolbar name and captions
    //       Write an add-in function to be called when the tool button is clicked
    //       Add other buttons
    CXlToolbarState tstate;
    CXlToolbar::AddToolbar(m_pszToolbarName, tstate);
    CXlToolbar::AddTool(m_pszToolbarName, 1, _T("MyAddinFunction"), _T("My addin function"));
    CXlToolbar::SetToolBitmap(m_pszToolbarName, 1, IDB_BITMAP1);
    CXlToolbar::ShowToolbar(m_pszToolbarName, tstate, true, CXlToolbar::DockRight);
}

In MyAddin.cpp, the following will appear within the method CMyAddinApp::OnXllClose():

CopyC++
// Delete toolbar
if (!SupportsRibbon())
    CXlToolbar::DeleteToolbar(m_pszToolbarName);

Generate a VersionInfo function

This option will add a standard VersionInfo add-in function to your XLL, which can be used in a spreadsheet to get details of the author, date, version build and copyright of the XLL.

You can add a VersionInfo function later by using the Add VersionInfo Function command.

Enable Logging

This option will add basic logging functionality to the project, using the framework in cpplog.h. The following changes are made:

The following will appear in MyAddin.cpp before the #ifdef _DEBUG line:

CopyC++
#include <cpplog.h>
using namespace psl::log;
static LoggerPtr g_logger = Logger::getLogger(_T("Global"));

In MyAddin.cpp, the following will appear within the method CMyAddinApp::OnXllOpenEx():

CopyC++
// Start logging
if (!XllConfigurator::configure())
    return FALSE;

A new file MyAddin.xll.log.ini is added to the project. Its contents are as follows:

CopyC++
# To write to different appenders, add them to the rootLogger directive,
# e.g.:
#    log.rootLogger=ERROR, T
#    log.rootLogger=ERROR, F, T

# To set the severity level for all loggers, change the level in the
# rootLogger directive, e.g.:
#    log.rootLogger=INFO, T

# To set the severity level for a specific logger, use a logger directive,
# e.g.:
#    log.logger.CMyLoggedClass=TRACE
#    log.logger.Global=DEBUG

log.rootLogger=ERROR, F

log.appender.F=FileAppender
log.appender.F.File=%TMP%\MyAddin.log
log.appender.F.layout=PatternLayout
log.appender.F.layout.ConversionPattern=%-20.20d %t %-5p %c %m%n

log.appender.T=TraceAppender
log.appender.T.layout=PatternLayout
log.appender.T.layout.ConversionPattern=%c %-5p %c %m%n

The following Custom Build Step settings are applied to the file:

Setting | Value
Command line | copy "$(InputFileName)" "$(TargetDir)"
Description | Copy log configuration file to output
Outputs | "$(TargetDir)$(InputFileName)"

See Also

XLL+ AppWizard - Overview | XLL+ AppWizard - Application Settings | Project Settings


XLL+ Object Model

XLL+ maintains a model of an add-in function. The model is run against a selected code template to generate and regenerate the code for the add-in functions. The model can be edited using the XLL+ user interface tools: the XLL+ Function Wizard and the XLL+ ToolWindow.

The model is saved as one of the arguments of the IMPLEMENT_XLLFN3 macro. It is loaded from there by the XLL+ ToolWindow and XLL+ Function Wizard.

The model can be exported as XML, and is used in that form by the help generator.

The objects of the model are listed below.

Object | Description
Settings | This object contains properties which apply at a system-wide level. These settings apply to all projects, and to all add-in functions within each project. Settings can be edited using the XLL+/General page of the Visual Studio Options dialog.
Function | This object represents a single add-in function, including its signature, arguments, description and features.
Argument | A single argument to an add-in function
Group | An argument to an add-in function that contains multiple inner arguments.
Bound | The constraints and behavior of a single dimension of a vector or matrix argument.


Argument Class

Overview

This object represents a single argument to an add-in function. It can also represent a single item in a grouped argument.

See Also

Argument Properties | Function model


Argument Properties

The properties of the Argument class are listed here.

Behavior

public method | ContainerClass | Template class used in C++ for the targets of vector or matrix arguments.
public method | Name | Name of the argument, as it will appear in the Excel Formula Wizard

Signature

public method Signature The signature of the argument, including its dimensions and constraints.

Help

public method | Description | Description of the argument, as it will appear in the Excel Formula Wizard.
public method | ResourceId | ID of language-independent text resource used for the argument's name in the Excel Formula Wizard.
public method | ShowPopupInFormulaWizard | Sets whether the argument should have a popup button in the Formula Wizard.

Default values

public method | DefaultValueText | Default value used for argument if it is empty or missing.
public method | UseDefault | Controls whether the argument is optional.

Array

public method | CellUseDefault | Controls which cells in an array should be treated as missing.
public method | FillArray | Controls how empty cells in an array are handled.
public method | RejectNullArray | If this flag is set to true, then an empty array will be rejected.
public method | TruncateArray | Controls which cells cause the converter to truncate the array at that point.
public method | UBoundInner | Controls the values of upper bound constraints.
public method | VectorDirection | Controls whether a vector input is required to be in a row or a column, or is not constrained.

Value List

public method | ShowValueListInFormulaWizard | Controls whether a value list is used to display a drop-down list in the Excel Formula Wizard.
public method | ValueList | Contains a list of value/description pairs.
public method | ValueListIsExclusive | Controls whether a value list is used to validate inputs.

See Also

Argument Model | Function model


Argument.CellUseDefault

Controls which cells in an array should be treated as missing.

Remarks

This property controls which cells in an array are treated as missing. If the FillArray property is set to a value other than None, then these cells will be filled with a default value.

CellUseDefault may include any, all or none of the following flags:

Flag | Description
MissingOrEmpty | Cells that are empty are considered to be missing.
Blank | Blank cells are considered to be missing. This would include a cell containing ="".
Zero | Numeric cells with zero values are considered to be empty.
Nonnumeric | Non-numeric cells are considered to be empty.

See Also

Argument Model | Argument Properties


Argument.ContainerClass

Template class used in C++ for the targets of vector or matrix arguments.

Remarks

For each vector or matrix argument to an add-in function, a local container variable is declared, and the input is copied into it after validation. If the argument's ContainerClass property is set, then the container will be of the type specified by the property. However, if the argument's container class property is left empty (the default), then the container class used will be that specified by DefaultVectorContainer or DefaultMatrixContainer as appropriate.

Notation

There are two varieties of notation for specifying a container class.

  1. Template class for T

    The class name is a C++ template class, with the letter T representing the scalar type. Thus, if you specify std::vector<T> for a vector of type Double, the generated container class will be std::vector<double>.

    Template arguments other than T will be left unchanged. Thus a container class boost::multi_array<T, 2> for a numeric vector will be expanded to: boost::multi_array<double, 2>.

  2. Concrete class

    The class name is a C++ class, with no template arguments. If you specify MyStringVector for a string vector, the generated class will simply be MyStringVector.

    A concrete container class must be capable of containing items of the specified type. If you specify MyStringVector for a numeric vector, the generated class will still be MyStringVector, and your code will probably not compile.

See Also

Argument Model | Argument Properties


Argument.DefaultValueText

Default value used for argument if it is empty or missing.

Remarks

This text value will be inserted directly into code as the right-hand-side of an assignment.

See Also

Argument Model | Argument Properties


Argument.Description

Description of the argument, as it will appear in the Excel Formula Wizard.

Validation

If an argument's description is left blank, then a warning will be generated.

See Also

Argument Model | Argument Properties


Argument.FillArray

Controls how empty cells in an array are handled.

Remarks

This property controls how empty cells in an array input are treated. whether the argument is optional, and when it should be treated as missing, in which case the DefaultValueText is used. It must contain one of the following values:

Value | Description
None | Empty cells are discarded (if array truncation settings allow it) or rejected.
FillUsedArea | All empty cells within the used area are filled with the default value. The used area is defined as being the smallest rectangular area which includes all populated cells and also the origin (0, 0).
FillAll | All empty cells are filled with the default value.

Cells are classed as empty according to the flags of the CellUseDefault property.

See Also

Argument Model | Argument Properties


Argument.Name

Name of the argument, as it will appear in the Excel Formula Wizard

Remarks

This name should be unique within a function. If it is not, then warnings will be issued by the XLL+ tools and the code will fail to compile.

Validation

If an argument's name is a duplicate, or is not a valid C++ variable name, then a warning will be generated.

See Also

Argument Model | Argument Properties


Argument.RejectNullArray

If this flag is set to true, then an empty array will be rejected.

See Also

Argument Model | Argument Properties


Argument.ResourceId

ID of language-independent text resource used for the argument's name in the Excel Formula Wizard.

Remarks

If zero, this property will be ignored, and the Name property will be used as usual.

If non-zero, then the matching text-resource will be loaded from the add-ins resource file at run-time, and used instead. The name will then be in the language of the user, if available.

See Also

Argument Model | Argument Properties


Argument.ShowPopupInFormulaWizard

Sets whether the argument should have a popup button in the Formula Wizard.

Remarks

If false, this property will be ignored.

If true, then the argument will be marked as requiring the Excel Formula Wizard extended user interface. The developer is reponsible for creating a class derived from CXlWizExUIPopupProviderBase, and for registering it, using CXlWizExUIArgumentPopupCreator.

See Also

Argument Model | Argument Properties


Argument.ShowValueListInFormulaWizard

Controls whether a value list is used to display a drop-down list in the Excel Formula Wizard.

Remarks

If this property is set to true, then the value list will be used to display a drop-down list in the Excel Formula Wizard.

The property is ignored for arguments that are not scalar integer values.

See Also

Argument Model | Argument Properties


Argument.Signature

The signature of the argument, including its dimensions and constraints.

Remarks

An argument's type may be a built-in data types or any Extended scalar type that has been registered.

The built-in types are as follows:

Type | C++ type | Description
Boolean | BOOL | Boolean (true or false) value
Double | double | Floating-point number
Int | long | Signed integer (32-bit)
Short Int | short int | Signed integer (16-bit)
String | const CXlStringArg& | Text string
Unsigned Short Int | unsigned short int | Unsigned integer (16-bit)
Reference | const CXlOper* | A reference to an Excel cell range
Value | const CXlOper* | The value(s) contained in an Excel cell range
XlArray | const CXlArray& | An array of numbers

Value types can be assigned a rank, which defines the number of dimensions they are expected to have.

Rank | Name | Description
0 | Scalar | A single value
1 | Vector | A set of values contained in a single row or column
2 | Matrix | A set of values contained in one or more rows and one or more columns

Vector or matrix arguments will be stored in a container, such as std::vector<T>. You can use the Vector Container or Matrix Container controls to specify a particular container class. Otherwise the default class (as defined by the DefaultVectorContainer or DefaultMatrixContainer settings) will be used.

See Also

Argument Model | Argument Properties


Argument.TruncateArray

Controls which cells cause the converter to truncate the array at that point.

Remarks

This property controls how empty cells in an array input are treated. whether the argument is optional, and when it should be treated as missing, in which case the DefaultValueText is used. It must contain one of the following values:

TruncateArray may include any, all or none of the following flags:

Flag | Description
TruncateOnEmpty | Array is truncated at first empty cell. If FillUsedArea is used, array is truncated at last empty cell, searching backwards.
TruncateOnBlank | Array is truncated at first blank cell. If FillUsedArea is used, array is truncated at last blank cell, searching backwards.
TruncateOnNonNumeric | Array is truncated at first non-numeric cell. If FillUsedArea is used, array is truncated at last non-numeric cell, searching backwards.
TruncateOnZero | Array is truncated at first cell containing the numeric value zero. If FillUsedArea is used, array is truncated at last zero cell, searching backwards.

See Also

Argument Model | Argument Properties


Argument.UBoundInner

Controls the values of upper bound constraints.

Remarks

This flag controls how upper bound values are calculated; it specifies when the inner value size() - 1 is used as the bound value, as opposed to the more normal size(). It may have any of the following values:

Value | Description
Never | Upper bounds are always calculated as size().
Always | Upper bounds are always calculated as size() - 1.
FollowLBound | An upper bound is calculated as size() - 1 if the lower bound for that dimension is non-zero. An upper bound is calculated as size() if the lower bound for that dimension is zero.

See Also

Argument Model | Argument Properties


Argument.UseDefault

Controls whether the argument is optional.

Remarks

This property controls whether the argument is defined as optional, and when it should be treated as missing, in which case the DefaultValueText is used. It may contain any or all of the following flags:

Flag | Description
MissingOrEmpty | Argument has been omitted completely from the formula, or is an empty cell.
Blank | Argument is a blank cell, containing the string returned by ="".
Zero | Argument value is zero.
Nonnumeric | Argument value is not numeric.

See Also

Argument Model | Argument Properties


Argument.ValueList

Contains a list of value/description pairs.

Remarks

This list of values will be used in three places:

  1. As a drop-down list in the Excel Formula Wizard, if ShowValueListInFormulaWizard is true, and the argument is scalar.
  2. As a set of values that constrain the value of the input, if ValueListIsExclusive is true.
  3. As the source for a table of values in the function's help page.

See Also

Argument Model | Argument Properties


Argument.ValueListIsExclusive

Controls whether a value list is used to validate inputs.

Remarks

If this property is set to true, then the value list will be used to constrain the value of the input. If the input is not one of the values in the list, then an exception will be raised and the function will report an input error.

See Also

Argument Model | Argument Properties


Argument.VectorDirection

Controls whether a vector input is required to be in a row or a column, or is not constrained.

Remarks

VectorDirection must be one of the following values:

Value | Description
Horizontal | Vector must be horizontal (a row).
Vertical | Vector must be vertical (a column).
Either | Vector may be either horizontal or vertical.

See Also

Argument Model | Argument Properties


Bound Class

Overview

This object represents the behavior of an array input in a single dimension. Vector arguments have 1 bound, matrix arguments have 2.

Bounds can be edited in the Argument details window, in the Vector and Matrix tabs. window.

See Also

Bound Properties


Bound Properties

The properties of the Bound class are listed here.

Behavior

public method | Lower | The lower bound of the dimension
public method | Upper | The upper bound of the dimension

See Also

Bound Model


Bound.Lower

The lower bound of the dimension

Remarks

This property controls the base of the output array.

If it is set to 0 (the default) then the output array will begin at index 0.

It may be set to 1, so that the ouput array will have an empty item at its start, and its data will start at index 1. This setting is useful for calling functions in libraries that expect 1-based arrays.

See Also

Bound Model | Bound Properties


Bound.Upper

The upper bound of the dimension

Remarks

This property constrains the size of the array. If it contains an integer, then the array must contain exactly that number of items (in the specified dimension) or the input will be rejected by the add-in function, with a message such as "Expected 3 cells for X".

If the property contains a name, then a variable of that name will be instantiated in the add-in functions, and the validation code will set it to the size of the array. If the variable has already been set, then it will be tested. If the size is different from the value of the variable, then the input will rejected, with a message such as "Expected 3 cells for X". By using the same bounding variable for two arrays, you can constrain multiple inputs to have the same size, width or height. See also Constraining the size of an argument in the User Guide.

If the property is left empty (the default) then there are no constraints on the size of the array.

See Also

Bound Model | Bound Properties


Function Class

Overview

XLL+ maintains a model of an add-in function. The model is run against a selected code template to generate and regenerate the code for the add-in functions. The model can be edited using the XLL+ user interface tools: the XLL+ Function Wizard and the XLL+ ToolWindow.

The model is saved as one of the arguments of the IMPLEMENT_XLLFN3 macro. It is loaded from there by the XLL+ ToolWindow and XLL+ Function Wizard.

The model can be exported as XML, and is used in that form by the help generator.

See Also

Function Properties | Argument model | Group model | Settings model


Function Properties

The properties of the Function class are listed here.

Names

public method | CppNameResolved | The name of the function as it will appear in C++
public method | EntryPointXL12 | 'C' entry point for 2007 and above
public method | EntryPointXL4 | 'C' entry point for Excel 2003 and below
public method | ExportedName | The name of the function as it will appear in Excel

Behavior

public method | Availability | The conditions under which the function will be available: from a worksheet cell, from a macro and from the Excel Formula Wizard
public method | CacheResults | Specifies whether the function's results should be cached, to improve performance of expensive calculations.
public method | CanDeferRecalc | Specifies whether the function can defer recalculation
public method | DoNotCallInFormulaWizard | Specifies whether the function returns early, without any action, when called from the Excel Formula Wizard
public method | DoNotCatchStructuredExceptions | Controls whether wrapper functions will contain code to catch C runtime exceptions
public method | ExecutionCanFail | Specifies whether the function may fail while executing
public method | IsVolatile | Specifies whether the function is volatile, and will be recalculated every time any cell in the same sheet is calculated
public method | Versions | Controls which Excel versions the function will support explicitly

Design

public method | ArgumentValueHasPrefix | Specifies whether the inner function's argument values' names are prefixed
public method | TemplateKey | Identifies the template used to generate the code of this function

Extensions

public method Extensions The set of function extensions that have been added to the function.

Help

public method | Category | Category in which the function will appear within the Excel Formula Wizard
public method | Description | Description of the function which will appear within the Excel Formula Wizard
public method | HelpId | Numeric help ID (ignored if 0)

Signature

public method ReturnType The type of value returned to Excel.

Thread model

public method | CreateAsyncVersion | Specifies that an asynchronous version of the function should also be created.
public method | CreateQueuedVersion | Specifies that a queued version of the function should also be created. (Excel 2010 and above only)
public method | ExportedNameAsync | The Excel name used for the asynchronous version of the function.
public method | ExportedNameQueued | The Excel name used for the queued version of the function.
public method | ExportedNameSync | The Excel name used for the synchronous (standard) version of the function.
public method | HideSyncVersion | Specifies that the standard (synchronous) version of the function is hidden from the Excel Formula Wizard.
public method | IsClusterSafe | Specifies that the function is cluster safe. (Excel 2010 and above only)
public method | IsThreadSafe | Specifies whether the function is thread-safe (Excel 2007 and above only)
public method | UseAsyncHandleModel | Specifies that an extra (dummy) argument should be added to asynchronous function versions, to support spreadsheets created using the older (6.0.x) function model.

See Also

Function Model | Argument model | Group model | Settings model


Function.ArgumentValueHasPrefix

Specifies whether the inner function's argument values' names are prefixed

Remarks

If this flag is true, then the XlOper input's name will be the name of the argument, and the calculated value's name will be "val" + the name of the argument. If it is false, then the XlOper input's name will be the name of the argument followed by "_oper", and the calculated value's name will be just the name of the argument. Old-style functions that have been upgraded will have this flag set.

The default value for the property is false.

See Also

Function Model | Function Properties


Function.Availability

The conditions under which the function will be available: from a worksheet cell, from a macro and from the Excel Formula Wizard

Remarks

Availability may have one of the following values:

Worksheet | Function can be called from worksheet cells, and will be listed in the Excel Formula Wizard.
Macro | Function can be called from macros or as a command. It may not be called from worksheet cells. It will not be listed in the Excel Formula Wizard.
Hidden | Function can be called from worksheets cells or from macros or as a command. It will not be listed in the Excel Formula Wizard.

See Also

Function Model | Function Properties


Function.CacheResults

Specifies whether the function's results should be cached, to improve performance of expensive calculations.

Remarks

If this property is set to true, then the function's result will be stored in an application-level cache. Each time the function is called, the cache is searched for an identical set of inputs. If they are found, then the result is returned from the cache and the implementation function is not called. This can result in a considerable performance improvement.

The default value for the property is false.

Requirements

An application-level results cache must exist in order for this feature to work. Create a results cache when creating the add-in project using the AppWizard.

See Also

Function Model | Function Properties | Results cache


Function.CanDeferRecalc

Specifies whether the function can defer recalculation

Remarks

If this property is set to true, then the function will be registered as a type 2 function, which is allowed to call a wider set of Excel API calls, including calls that allow specific cells to be examined.

The default value for the property is false.

See Also

Function Model | Function Properties


Function.Category

Category in which the function will appear within the Excel Formula Wizard

Remarks

This property controls which category the function will appear under, in the Excel Formula Wizard.

The default value for Category is controlled by the XLL+ General Options setting DefaultCategory.

Standard categories

The standard built-in categories are stored as numbers between 1 and 14, but are displayed in XLL+ as they would appear in Excel. The standard categories are listed below with their US English names.

Number | Name
1 | Financial
2 | Date & Time
3 | Math & Trig
4 | Statistical
5 | Lookup & Reference
6 | Database
7 | Text
8 | Logical
9 | Information
10 | Commands
11 | Customizing
12 | Macro Control
13 | DDE/External
14 | User Defined

See Also

Function Model | Function Properties


Function.CppNameResolved

The name of the function as it will appear in C++

Remarks

This read-only property is calculated from the function's CppName property, if it is set, or, if it is not, from the function's ExportedName. It is used as the root of the names of the wrapper and implementation functions in C++.

CppNameResolved should be used instead of ExportedName as part of a safe name for a script-generated variable.

See Also

Function Model | Function Properties | ExportedName property


Function.CreateAsyncVersion

Specifies that an asynchronous version of the function should also be created.

Remarks

If this property is set to true, then an additional add-in function will be created which runs the core function asynchronously, in a worker thread. The function will be have the same name as the core function, plus the suffix "Async".

The default value for the property is false.

See Also

Function Model | Function Properties | Asynchronous functions


Function.CreateQueuedVersion

Specifies that a queued version of the function should also be created. (Excel 2010 and above only)

Remarks

If this property is set to true, then an additional add-in function will be created which runs the core function asynchronously, in a worker thread. The function will be have the same name as the core function, plus the suffix "Queued".

The default value for the property is false.

See Also

Function Model | Function Properties | Queued functions


Function.Description

Description of the function which will appear within the Excel Formula Wizard

Remarks

This property holds the description of a function, as it will appear in Excel's Formula Wizard.

The default value for Description is empty.

Validation

If a function's description is left blank, then a warning will be generated.

See Also

Function Model | Function Properties


Function.DoNotCallInFormulaWizard

Specifies whether the function returns early, without any action, when called from the Excel Formula Wizard

Remarks

If this property is set to true, then the function will return #VALUE! when it is called from the Excel Formula Wizard.

The default value for the property is false.

See Also

Function Model | Function Properties | Excel Formula Wizard


Function.DoNotCatchStructuredExceptions

Controls whether wrapper functions will contain code to catch C runtime exceptions

Remarks

If this property is set to true, then the code which normally traps C runtime exceptions will not be generated. It is then the responsibility of the developer to catch any such exceptions, if they are liable to occur.

The default value for the property is false.

See Also

Function Model | Function Properties | C Runtime Exceptions


Function.EntryPointXL12

'C' entry point for 2007 and above

Remarks

By default the 'C' entry point for Excel 2007 and above is ExportedName followed by "_12". This value can be overridden by setting the EntryPointXL12 property.

The default value for this property is empty.

See Also

Function Model | Function Properties


Function.EntryPointXL4

'C' entry point for Excel 2003 and below

Remarks

By default the 'C' entry point for Excel 2003 and below is ExportedName followed by "_4". This value can be overridden by setting the EntryPointXL4 property.

The default value for this property is empty.

See Also

Function Model | Function Properties


Function.ExecutionCanFail

Specifies whether the function may fail while executing

Remarks

If this property is set to true, then the return type of the function will always be CXlOper, so that error values can be returned.

The default value for the property is false.

See Also

Function Model | Function Properties


Function.ExportedName

The name of the function as it will appear in Excel

Remarks

This name should be unique within an add-in. If it is not, then the function will not be registered, and the code may not even compile. The XLL+ tools issue warnings when a duplicate function name is used.

The ExportedName property controls the default values of several other properties, including:

  • EntryPointXL4
  • EntryPointXL12

See Also

Function Model | Function Properties | CppNameResolved property


Function.ExportedNameAsync

The Excel name used for the asynchronous version of the function.

Remarks

The Excel name used for the asynchronous version of the function. If omitted or blank, a default value will be used. (Ignored if CreateAsyncVersion is not specified.)

The default value for the property is the empty string.

See Also

Function Model | Function Properties


Function.ExportedNameQueued

The Excel name used for the queued version of the function.

Remarks

The Excel name used for the queued version of the function. If omitted or blank, a default value will be used. (Ignored if CreateQueuedVersion is not specified.)

The default value for the property is the empty string.

See Also

Function Model | Function Properties


Function.ExportedNameSync

The Excel name used for the synchronous (standard) version of the function.

Remarks

The Excel name used for the synchronous version of the function. If omitted or blank, a default value will be used. (Ignored if CreateAsyncVersion or CreateQueuedVersion are not specified.)

The default value for the property is the empty string.

See Also

Function Model | Function Properties


Function.Extensions

The set of function extensions that have been added to the function.

Remarks

This property controls the list of extensions that have been added to the function. If the extension has properties, these are also stored.

A function's extensions can be edited in the Extensions tab of the XLL+ Function Wizard.

You can choose to add a standard set of extensions to newly created functions by adding their names to the DefaultFunctionExtensions setting.

See Also

Function Model | Function Properties


Function.HelpId

Numeric help ID (ignored if 0)

Remarks

If a function has a non-zero help ID, then it will be used to resolve the help topic for the file when the user clicks "Help on this function".

The default value for HelpId is zero.

See Also

Function Model | Function Properties | Help


Function.HideSyncVersion

Specifies that the standard (synchronous) version of the function is hidden from the Excel Formula Wizard.

Remarks

If an async version has been specified, then this flag specifies that the standard (synchronous) version of the function is hidden from the Excel Formula Wizard. The name will have a Sync suffix added, and the async version's name will not receive a suffix. The flag is ignored unless CreateAsyncVersion or CreateQueuedVersion is specified.

The default value for the property is false.

See Also

Function Model | Function Properties | Asynchronous functions


Function.IsClusterSafe

Specifies that the function is cluster safe. (Excel 2010 and above only)

Remarks

If this flag is set to true, it specifies that the function is cluster safe and can be off-loaded to a high-performance computing cluster through a dedicated cluster connector. The function is constrained: no OPER arguments are permitted, and call-backs to the SDK are not permitted, unless specifically supported by the cluster connector. (Excel 2010 and above only.)

The default value for the property is false.

See Also

Function Model | Function Properties


Function.IsThreadSafe

Specifies whether the function is thread-safe (Excel 2007 and above only)

Remarks

If this property is set to true, then the function will be registered as a thread-safe function, which means that Excel can call the function on multiple threads simultaneously.

The default initial value for IsThreadSafe is controlled by the XLL+ General Options setting DefaultIsThreadSafe.

See Also

Function Model | Function Properties | Ensuring global data is thread-safe


Function.IsVolatile

Specifies whether the function is volatile, and will be recalculated every time any cell in the same sheet is calculated

Remarks

If this property is set to true, then the function will be registered as a volatile function, which means that Excel will recalculate any cell containing the function whenever any cell in the same sheet is recalculated.

The default value for the property is false.

See Also

Function Model | Function Properties | Volatile functions


Function.ReturnType

The type of value returned to Excel.

Remarks

The value will always be CXlOper for functions that return a variable type, or that return arrays, or that may fail.

The default value for ReturnType is CXlOper.

ReturnType may have any of the values below:

Type | Description
Boolean | Boolean value (true or false)
Double | Double-precision floating-point number
Short | Short (16-bit) signed integer
UShort | Short (16-bit) unsigned integer
Int | Long (32-bit) signed integer
CXlOper | Any value type, including arrays

See Also

Function Model | Function Properties


Function.TemplateKey

Identifies the template used to generate the code of this function

Remarks

This property can control the choice of the template used to generate the function's code.

The default value for TemplateKey is empty.

See Also

Function Model | Function Properties


Function.UseAsyncHandleModel

Specifies that an extra (dummy) argument should be added to asynchronous function versions, to support spreadsheets created using the older (6.0.x) function model.

Remarks

If this property is set to true, then an additional argument 'RtdSignalCell', will be added to the asynchronous version of the add-in function.

The default value for the property is false.

The property should only be used in order to support existing spreadsheets which used asynchronous functions first developed under XLL+ 6.0.0 to 6.0.4. The extra argument is no longer required, and is not created in asynchronous functions developed using XLL+ 6.2 upwards.

Requirements

This property is ignored unless CreateAsyncVersion is set to true.

See Also

Function Model | Function Properties | Asynchronous functions


Function.Versions

Controls which Excel versions the function will support explicitly

Remarks

Versions may have one of the following values:

Excel2003AndBelow | Excel 95 to Excel 2003
Excel2007AndAbove | Excel 2007 upwards
AllExcelVersions | All Excel versions from Excel 95 upwards

This property controls the code that will be generated by XLL+. If Versions is set to AllExcelVersions then two wrapper functions will be generated, one for each environment, and the appropriate one will be registered, depending on which version of Excel is running.

If only one environment is supported then only one wrapper function will be generated. If Excel2003AndBelow is used then the add-in will work in all versions of Excel, but will not take advantage of the new features of Excel 2007 and above. If Excel2007AndAbove is used, then the function will not be available in Excel 2003 and below.

The default value for Versions is controlled by the XLL+ General Options setting DefaultExcelVersions.

See Also

Function Model | Function Properties


Group Class

Overview

A Group contains a group of inner arguments. A group is represented in Excel by a single argument, but is split into its component inner arguments by the validation code generated by the XLL+ Function Wizard.

See Also

Group Properties


Group Properties

The properties of the Group class are listed here.

Behavior

public method GroupType The group's type, which defines its behavior

Help

public method DescriptionBuilderType A flag that controls how a group's description is built out of its component arguments

See Also

Group Model


Group.DescriptionBuilderType

A flag that controls how a group's description is built out of its component arguments

Remarks

Consider a group which contains the following arguments:

Name | Description
Real | Real component
Imag | Imaginary component

The table below lists the allowed values of this property, and shows how the group's description would appear for the group defined above.

Value | Description | Example
DynamicIndexName | Numbers and names of each argument | 2 items: 1:Real; 2:Imag
DynamicIndexDescription | Numbers and descriptions of each argument | 2 items: 1:Real component; 2:Imaginary component
DynamicIndexNameDescription | Numbers, names and descriptions of each argument | 2 items: 1:Real (Real component); 2:Imag (Imaginary component)
DynamicName | Names of each argument | 2 items: Real; Imag
DynamicDescription | Descriptions of each argument | 2 items: Real component; Imaginary component
DynamicNameDescription | Names and descriptions of each argument | 2 items: Real (Real component); Imag (Imaginary component)
Static | Determined only by the value of the group's Description | N/A

See Also

Group Model | Group Properties


Group.GroupType

The group's type, which defines its behavior

Remarks

A group may be either a Sequence or a Choice.

A sequence is a list of component arguments, each of which should be present. The sequence must be either ordered or named. The validation code will extract each of the arguments from the input array into a separate variable.

A choice is list of alternative arguments, only one of which may be present. The validation will attempt to match the input against the type of each argument in turn, until it succeeds. A local variable will be set, which indicates, which (if any) of the arguments was successfully validated.

See Also

Group Model | Group Properties


Settings Class

Overview

XLL+ Settings values can be reached via the XLL+/General tab of the Tools/Options dialog in Visual Studio.

You can also go straight to this tab by clicking the XLL+ Options command.

See Also

Settings Properties | Function model | Argument model


Settings Properties

The properties of the Settings class are listed here.

Defaults for arguments

public method | DefaultArgumentType | Data type applied to new arguments
public method | DefaultFillArrayBehavior | Array fill behavior applied by default to array arguments
public method | DefaultFillArrayTargets | Array fill flags applied by default to array arguments
public method | DefaultMatrixContainer | Template class used in C++ for the targets of matrix arguments.
public method | DefaultTruncateArrayFlags | Array truncation flags applied by default to array arguments
public method | DefaultVectorContainer | Template class used in C++ for the targets of vector arguments.

Defaults for functions

public method | DefaultCategory | Category used for new add-in functions
public method | DefaultDoNotCallInFormulaWizard | Default value for DoNotCallInFormulaWizard applied to new functions.
public method | DefaultDoNotCatchStructuredExceptions | Default value for DoNotCatchStructuredExceptions applied to new functions.
public method | DefaultExcelVersions | Controls which Excel versions a new function will support explicitly
public method | DefaultFunctionExtensions | List of function extensions automatically added to new functions.
public method | DefaultIsThreadSafe | Default value for IsThreadSafe applied to new functions.

Output

public method MaxCharsPerLine The maximum number of characters per line in generated code.

Project

public method | DefaultExcelExe | Full path to Excel executable file EXCEL.EXE. This is the version of Excel that will be used for debugging.
public method | IncludePath | Directory containing XLL+ header files.
public method | LibPath | Directory containing XLL+ run-time libraries.

Templates

public method TemplatesFolder Directory containing the XLL+ code generation templates.

Code generator

public method | GeneratorClassName | Name of generated class.
public method | GeneratorNamespace | Namespace of generated class.
public method | IncludeDebugInformation | Determines whether the emitted generator code will contain debug information.
public method | TmpFolder | Name of sub-folder of the user's temporary directory where generator code will be emitted and compiled.

Tools

public method | CollapseAllSections | Controls whether the Function Wizard automatically collapses collapsible regions in generated code.
public method | EditorIdleInterval | The number of milliseconds to wait between running background tasks in the editor.
public method | FavoriteArgumentsFile | Location for file containing favorite arguments.
public method | InstallationFolder | Returns the installation folder for this version of XLL+
public method | MaxFunctionsOnMenu | Maximum number of functions listed in the 'Select Function' menu.
public method | ShowAdvancedProperties | Show or hide advanced function properties in Visual Studio Properties window
public method | ToolsFolder | Returns the folder containing the XLL+ development tools
public method | UserSettingsFolder | Location for per-user XLL+ configuration files.

Help generator

public method | HhcExe | Full path to HTML Help Compiler HHC.EXE.
public method | HhcExeResolved | Full path to actual executable used for help compilation
public method | IncludeHelpInDebugBuild | Controls whether help files are included in the Debug configuration build of new and upgraded projects.
public method | SkipHelpBuilderSetup | Controls whether the command line for buildoing a help file is updated before a build.

User

public method | UserName | The name of the user of the XLL+ Tool-kit
public method | UserOrganization | The organization to which the user belongs

See Also

Settings Model | Function model | Argument model


Settings.CollapseAllSections

Controls whether the Function Wizard automatically collapses collapsible regions in generated code.

Remarks

This boolean property controls whether the Function Wizard attempts to automatically collapse any collapsible regions within generated code. If it is set to true, then any regions within the generated code that are bounded by #pragma region and #pragma endregion will be collapsed whenever code is generated or regenerated for a function.

See Also

Settings Model | Settings Properties


Settings.DefaultArgumentType

Data type applied to new arguments

Remarks

When new arguments are created in the XLL+ Function Wizard, they will initially be scalar values with this data type.

DefaultArgumentType may be set to any of the built-in data types:

Type | Description
Boolean | Boolean value (true/false)
Double | Double-precision floating-point number
Int | 32-bit signed integer
Reference | A reference to a range of cells in Excel, or any value type
Short Int | 16-bit signed integer
String | A text string. Under Excel 2003 and below, an ASCII string limited to 255 characters in length. Under Excel 2007 and above, a Unicode string of up to 32767 characters in length.
Unsigned Short Int | 16-bit unsigned integer
Value | Any value type, or an array of values.
XlArray | An array of numbers. Empty cells will be passed as the value 0.0.

See Also

Settings Model | Settings Properties | Argument type


Settings.DefaultCategory

Category used for new add-in functions

Remarks

Changing this setting will have no effect on existing add-in functions; new add-in functions willl be created with this category.

See Also

Settings Model | Settings Properties | Function category


Settings.DefaultDoNotCallInFormulaWizard

Default value for DoNotCallInFormulaWizard applied to new functions.

Remarks

When a new add-in function is created by the XLL+ Function Wizard, this value will be applied to the property DoNotCallInFormulaWizard.

See Also

Settings Model | Settings Properties | Function DoNotCallInFormulaWizard


Settings.DefaultDoNotCatchStructuredExceptions

Default value for DoNotCatchStructuredExceptions applied to new functions.

Remarks

When a new add-in function is created by the XLL+ Function Wizard, this value will be applied to the property DoNotCatchStructuredExceptions.

See Also

Settings Model | Settings Properties | Function DoNotCatchStructuredExceptions


Settings.DefaultExcelExe

Full path to Excel executable file EXCEL.EXE. This is the version of Excel that will be used for debugging.

Effects

Changing this property will have no immediate impact on the settings of existing projects. You should use the Set up debugging command to apply the value to an existing project.

See Also

Settings Model | Settings Properties


Settings.DefaultExcelVersions

Controls which Excel versions a new function will support explicitly

Remarks

Versions may have one of the following values:

Excel2003AndBelow | Excel 95 to Excel 2003
Excel2007AndAbove | Excel 2007 upwards
AllExcelVersions | All Excel versions from Excel 95 upwards

This property controls the value of Function.Versions that will be applied to new functions created with the XLL+ Function Wizard.

See Also

Settings Model | Settings Properties


Settings.DefaultFillArrayBehavior

Array fill behavior applied by default to array arguments

Remarks

When an argument is edited so that it becomes a vector or matrix, the fill behavior selected in this property will automatically be applied to it.

DefaultFillArrayBehavior must be set to one of the following flags:

Flag | Description
None | Empty cells are discarded (if array truncation settings allow it) or rejected.
FillUsedArea | All empty cells within the used area are filled with the default value. The used area is defined as being the smallest rectangular area which includes all populated cells and also the origin (0, 0).
FillAll | All empty cells are filled with the default value.

See Also

Settings Model | Settings Properties | Argument truncation flags


Settings.DefaultFillArrayTargets

Array fill flags applied by default to array arguments

Remarks

When an argument is edited so that it becomes a vector or matrix, the truncation flags selected in this property will automatically be applied to it.

This property controls which cells in an array are treated as missing. If the FillArray property is set to a value other than None, then these cells will be filled with a default value.

DefaultFillArrayTargets may include any, all or none of the following flags:

Flag | Description
FillEmptyCells | Cells that are empty are considered to be missing.
FillBlankCells | Blank cells are considered to be missing. This would include a cell containing ="".
FillZeroCells | Numeric cells with zero values are considered to be empty.
FillNonNumericCells | Non-numeric cells are considered to be empty.

See Also

Settings Model | Settings Properties | Argument cell defaults


Settings.DefaultFunctionExtensions

List of function extensions automatically added to new functions.

Remarks

When a new add-in function is created by the XLL+ Function Wizard, all the extensions listed in this property will be applied to it. Multiple Extension names should be separated by semi-colons, e.g. log;trace.

See Also

Settings Model | Settings Properties | Function extensions


Settings.DefaultIsThreadSafe

Default value for IsThreadSafe applied to new functions.

Remarks

When a new add-in function is created by the XLL+ Function Wizard, this value will be applied to the property IsThreadSafe.

See Also

Settings Model | Settings Properties | Function IsThreadSafe


Settings.DefaultMatrixContainer

Template class used in C++ for the targets of matrix arguments.

Remarks

For each matrix argument to an add-in function, a local container variable is declared, and the input is copied into it after validation. If the argument's container class property is set, then the container will be of the type specifed by the property. However, if the argument's container class property is left empty (the default), then the container class used will be that specified by DefaultMatrixContainer.

If DefaultMatrixContainer is empty, then a default type, ple::mtx_ptrs, will be used.

Effects

Changing this property does not automatically change the code of arguments whose container class property is empty; if you wish to apply the new default matrix container to an argument, you should regenerate the code for the add-in function.

See Also

Settings Model | Settings Properties | Argument container class


Settings.DefaultTruncateArrayFlags

Array truncation flags applied by default to array arguments

Remarks

When an argument is edited so that it becomes a vector or matrix, the truncation flags selected in this property will automatically be applied to it.

DefaultTruncateArrayFlags may include any, all or none of the following flags:

Flag | Description
TruncateOnEmpty | Array is truncated at first empty cell. If FillUsedArea is used, array is truncated at last empty cell, searching backwards.
TruncateOnBlank | Array is truncated at first blank cell. If FillUsedArea is used, array is truncated at last blank cell, searching backwards.
TruncateOnNonNumeric | Array is truncated at first non-numeric cell. If FillUsedArea is used, array is truncated at last non-numeric cell, searching backwards.
TruncateOnZero | Array is truncated at first cell containing the numeric value zero. If FillUsedArea is used, array is truncated at last zero cell, searching backwards.

See Also

Settings Model | Settings Properties | Argument truncation flags


Settings.DefaultVectorContainer

Template class used in C++ for the targets of vector arguments.

Remarks

For each vector argument to an add-in function, a local container variable is declared, and the input is copied into it after validation. If the argument's container class property is set, then the container will be of the type specified by the property. However, if the argument's container class property is left empty (the default), then the container class used will be that specified by DefaultVectorContainer.

If DefaultVectorContainer is empty, then a default type, std::vector, will be used.

Effects

Changing this property does not automatically change the code of arguments whose container class property is empty; if you wish to apply the new default vector container to an argument, you should regenerate the code for the add-in function.

See Also

Settings Model | Settings Properties | Argument container class


Settings.EditorIdleInterval

The number of milliseconds to wait between running background tasks in the editor.

Remarks

This integer property controls the period between idle task processing in the current document. By default it is set to 1000 (1 second). For a faster response time when hiding code after collapsible regions are generated, reduce the value.

See Also

Settings Model | Settings Properties


Settings.FavoriteArgumentsFile

Location for file containing favorite arguments.

Remarks

This file may be shared with other users. Leave the property blank to use the default (unshared) location.

See Also

Settings Model | Settings Properties


Settings.GeneratorClassName

Name of generated class.

Remarks

If this property is left empty then the default behavior is used, and a random unique name is used.

This value should only be changed if you need to debug or trace a template.

See Also

Settings Model | Settings Properties


Settings.GeneratorNamespace

Namespace of generated class.

Remarks

If this property is left empty then the default behavior is used, and a random unique name is used.

This value should only be changed if you need to debug or trace a template.

See Also

Settings Model | Settings Properties


Settings.HhcExe

Full path to HTML Help Compiler HHC.EXE.

Effects

If this is left empty, then the directory specified in the registry under HKEY_CLASSES_ROOT\hhp.file\shell\open\command will be searched. Changing this property will have no immediate impact on the help files of existing projects. You can use the Upgrade Project to XLL+ 6 command to apply the value to an existing project.

See Also

Settings Model | Settings Properties


Settings.HhcExeResolved

Full path to actual executable used for help compilation

Remarks

This read-only property contains the full path to the file used for compiling help projects. If the HTML Help Compiler is not installed, then the property will contain an empty string.

See Also

Settings Model | Settings Properties


Settings.IncludeDebugInformation

Determines whether the emitted generator code will contain debug information.

Remarks

This value should only be changed if you need to debug or trace a template.

See Also

Settings Model | Settings Properties


Settings.IncludeHelpInDebugBuild

Controls whether help files are included in the Debug configuration build of new and upgraded projects.

Remarks

This boolean property controls whether help files are included in the Debug configuration build of new and upgraded projects.

See Also

Settings Model | Settings Properties


Settings.IncludePath

Directory containing XLL+ header files.

Remarks

This directory will be added to the include path of new projects generated using the XLL+ AppWizard.

Effects

Changing this property will have no impact on the settings of existing projects.

See Also

Settings Model | Settings Properties


Settings.InstallationFolder

Returns the installation folder for this version of XLL+

Remarks

This read-only property contains the full path to the installation folder for this version of XLL+.

See Also

Settings Model | Settings Properties


Settings.LibPath

Directory containing XLL+ run-time libraries.

Remarks

This directory will be added to the additional library directories list of new projects generated using the XLL+ AppWizard.

Effects

Changing this property will have no impact on the settings of existing projects.

See Also

Settings Model | Settings Properties


Settings.MaxCharsPerLine

The maximum number of characters per line in generated code.

Remarks

Much of the code generated by XLL+ is wrapped for imroved readability. This property controls the line wrapping. Lines will be wrapped in such a way that heir length does not exceed this number.

Note that it is not guaranteed that all generated lines will be limited to this number of characters; In some cases, readability concerns may cause a line to be up to 3 characters longer.

Effects

Changing this property does not automatically change the code of generated functions. If you wish to apply the new limit to a function, you should regenerate its code.

See Also

Settings Model | Settings Properties


Settings.MaxFunctionsOnMenu

Maximum number of functions listed in the 'Select Function' menu.

Remarks

This property must be between 2 and 20. The value controls the maximum number of items that will be displayed in the XLL+ Function Wizard's 'Select Function' menu.

See Also

Settings Model | Settings Properties


Settings.ShowAdvancedProperties

Show or hide advanced function properties in Visual Studio Properties window

Remarks

Advanced function model properties are not usually visible in the Visual Studio Properties Window. You can show or hide them by setting this property.

See Also

Settings Model | Settings Properties


Settings.SkipHelpBuilderSetup

Controls whether the command line for buildoing a help file is updated before a build.

Remarks

This boolean property controls whether a pre-build step occurs during which the command-line for the build of the help file is updated. If true, then all input files will be scanned to see whether they include add-in functions. Any that do will be added to the command-line and to the list of additional dependencies if necessary.

If you do not wish the command-line for your help file to be altered, then set this property to true.

See Also

Settings Model | Settings Properties


Settings.TemplatesFolder

Directory containing the XLL+ code generation templates.

Remarks

Leave this property empty to use the default directory.

See Also

Settings Model | Settings Properties


Settings.TmpFolder

Name of sub-folder of the user's temporary directory where generator code will be emitted and compiled.

Remarks

If this property is left empty then the default behavior is used, and a sub-folder with a random unique name is created (and is destroyed after use).

This value should only be changed if you need to debug or trace a template.

See Also

Settings Model | Settings Properties


Settings.ToolsFolder

Returns the folder containing the XLL+ development tools

Remarks

This read-only property contains the full path to the folder containing the XLL+ development tools. It is used by the AppWizard and the Upgrade Wizard to specify the Custom Build Step for help files.

See Also

Settings Model | Settings Properties


Settings.UserName

The name of the user of the XLL+ Tool-kit

Remarks

This property will be used by the AppWizard when generating new projects, and by the Add VersionInfo function command.

See Also

Settings Model | Settings Properties


Settings.UserOrganization

The organization to which the user belongs

Remarks

This property will be used in copyright notices by the AppWizard when generating new projects, and by the Add VersionInfo function command.

See Also

Settings Model | Settings Properties


Settings.UserSettingsFolder

Location for per-user XLL+ configuration files.

Remarks

Displays the folder where XLL+ stores per-user configuration files.

See Also

Settings Model | Settings Properties


Schema Reference

The XML schemas used by the XLL+ Toolkit are listed below.

XLL+ Extensions Schema
This schema defines the contents of an XLL+ extension file
XLL+ Help Schema
This schema defines the contents of an XLL+ help file.
XLL+ Extensions schema
This schema defines the contents of an XLL+ Wrapper Generator information file.
XLL+ Function schema
This schema defines the contents of an XLL+ function definition file.


XLL+ Extension Schema

This schema defines the contents of an XLL+ extension file. The root node of the schema is the Extensions element.

Two types of extension are supported: Extended scalar types and Function extensions.

Elements

Element | Description
Code | Contains the additional code that will be injected into the code generated by the XLL+ Function Wizard.
Extensions | This is the top-level container element for every XPE file.
FunctionExtension | This element defines a function extension.
FunctionExtensions | This is the container element for FunctionExtension definitions.
Include | The Include element allows the inclusion of another extension file within a file.
Inclusions | This is the container element for Include elements.
Insertion | This element defines a piece of code that is injected by a function extension.
Insertions | This is the container element for Insertion definitions.
Item | The Item element defines the localized value of a text for a particular culture.
Localized | This element may contain zero or more Item elements, each of which defines the value of the text for a particular culture.
LocalizedDescription | This optional element contains the localizable description of an extension.
LocalizedDisplayName | This optional element defines the display name of an extension.
Parameter | This element defines a parameter to either a function extension or an extended argument type.
Parameters | This optional element contains a list of the type's parameters.
RejectionMessage | This optional element contains a localizable message which will be used when an illegal value is entered for the parameter in the XLL+ Function Wizard.
ScalarType | This element defines an extended scalar type.
ScalarTypes | This is the container element for ScalarType definitions.


Code Element

This element contains the additional code that will be injected into the code generated by the XLL+ Function Wizard. It should be surrounded in a CDATA construct to preserve white-space layout. If the function extension has any parameters, the code may contain parameter names in the form $param-name$, which will be replaced by the value of the parameter. It may also contain attribute names in the form $#attrib-name$, which will be replaced by the value of the add-in function's named attribute, e.g.: $#ExportedName$.

Element Information

Number of occurrences | 1
Parent elements | Insertion
Child elements | (No child elements)

See Also

XLL+ Extensions Schema


Extensions Element

This is the top-level container element for every XPE file. The ExtendedTypes element may contain any or all of the following child elements: ScalarTypes, Inclusions, FunctionExtensions, in any order. The ExtendedTypes element has no attributes.

Element Information

Number of occurrences | Unlimited
Parent elements | (No parent elements)
Child elements | ScalarTypes Inclusions FunctionExtensions

See Also

XLL+ Extensions Schema


FunctionExtension Element

This element defines a function extension. It must contain an Insertions child element. It may contain any or all of the following optional child elements, each of which may appear only once or not at all: LocalizedDisplayName, LocalizedDescription, Parameters. It must contain the required attribute name. It may contain the following optional attributes: headerFiles and ignoreLocalHeaders.

Attributes

name

Required. The name attribute uniquely defines the name of the function extension. If two extensions use the same name, then the one that is loaded second will override the one that was loaded first. The name is not used in any C++ code, and does not need to be a valid C++ identifier. However, it is used as the persisted form of the extension's type, and therefore can never be changed.

headerFiles

The headerFiles attribute contains a list of the header files that are needed in order for the code inserted by this extension to compile correctly. The file name should not be surrounded by quotes or <...>. Multiple file names can be used, and should be separate by semi-colons, e.g. "myfile.h;..\inc\otherfile.h". Each file will be inserted as a local file if ignoreLocalHeaders is false, e.g. #include "myfile.h", and as a global file if ignoreLocalHeaders is true, e.g. #include <myfile.h>.

ignoreLocalHeaders

The ignoreLocalHeaders attribute controls whether the list of header files contained in the headerFiles attribute will be treated as local or global header files. Each file will be inserted as a local file if ignoreLocalHeaders is false, e.g. #include "myfile.h", and as a global file if ignoreLocalHeaders is true, e.g. #include <myfile.h>.

Element Information

Number of occurrences | Unlimited
Parent elements | FunctionExtensions
Child elements | Insertions LocalizedDisplayName LocalizedDescription Parameters

See Also

XLL+ Extensions Schema


FunctionExtensions Element

This is the container element for FunctionExtension definitions. The FunctionExtensions element may contain zero or more FunctionExtension child elements. The FunctionExtensions element has no attributes.

Element Information

Number of occurrences | 0 or 1
Parent elements | Extensions
Child elements | FunctionExtension

See Also

XLL+ Extensions Schema


Include Element

The Include element allows the inclusion of another extension file within a file. It has one mandatory attribute: file. The Include element has no child elements.

Attributes

file

Required. The file attribute should contain the name of the file to be included. If the file name is rooted (i.e. contains a drive definition) it will be read from the absolute path specified. If the name is not rooted, then it will be loaded from a path relative to the containing file.

Element Information

Number of occurrences | Unlimited
Parent elements | Inclusions
Child elements | (No child elements)

See Also

XLL+ Extensions Schema


Inclusions Element

This is the container element for Include elements. The Inclusions element may contain zero or more Include child elements. The Inclusions element has no attributes.

Element Information

Number of occurrences | 0 or 1
Parent elements | Extensions
Child elements | Include

See Also

XLL+ Extensions Schema


Insertion Element

This element defines a piece of code that is injected by a function extension. It must contain a single Code child element. It must contain the following required attributes: insertionPoint and priority.

Attributes

insertionPoint

Required. This attribute must contain the location where the code will be inserted. It must be one of: BeforeValidation, AfterValidation, BeforeTryCatch, AfterCatchException, BeforeMacro, AfterMacro, AfterFindInValueCache, AfterAddToValueCache.

priority

Required. This attribute sets the priority of the generated code, compared to any other extension that generates code at the same insertion point. Extensions with lower priorities will be placed before extensions with higher priorities.

Element Information

Number of occurrences | Unlimited
Parent elements | Insertions
Child elements | Code

See Also

XLL+ Extensions Schema


Insertions Element

This is the container element for Insertion definitions. The element may contain one or more Insertion child elements. The element has no attributes.

Element Information

Number of occurrences | 1
Parent elements | FunctionExtension
Child elements | Insertion

See Also

XLL+ Extensions Schema


Item Element

The Item element defines the localized value of a text for a particular culture. It has no child elements. It has two required attributes: culture, which must be a .NET culture name (e.g. 'en-US', fr-BE'), and text, which is the localized value of the text.

Attributes

culture

This attribute defines the culture for which the text attribute is valid, in the form of a .NET culture name (e.g. 'en-US', fr-BE').

text

This attribute should contain the Unicode text which will be used for the culture specifed in the culture attribute.

Element Information

Number of occurrences | Unlimited
Parent elements | Localized
Child elements | (No child elements)

See Also

XLL+ Extensions Schema


Localized Element

This element may contain zero or more Item elements, each of which defines the value of the text for a particular culture.

Element Information

Number of occurrences | 0 or 1
Parent elements | LocalizedDisplayName LocalizedDescription RejectionMessage
Child elements | Item

See Also

XLL+ Extensions Schema


LocalizedDescription Element

This optional element contains the localizable description of an extended scalar type. The description, if supplied, will appear as popup help text in the XLL+ Function Wizard. The text attribute is required, and will be used as the default value if no suitable localized values are found. This element may contain the optional element Localized, which contains localized versions of the text.

Attributes

text

Required. The text attribute is required, and will be used as the default value if no suitable localized values are found.

Element Information

Number of occurrences | 0 or 1
Parent elements | ScalarType Parameter FunctionExtension
Child elements | Localized

See Also

XLL+ Extensions Schema


LocalizedDisplayName Element

This optional element defines the display name of an extended scalar type. If it is not present, then the name of the ScalarType will be used as the display name. The text attribute is required, and will be used as the default value if no suitable localized values are found. This element may contain the optional element Localized, which contains localized versions of the text.

Attributes

text

Required. The text attribute is required, and will be used as the default value if no suitable localized values are found.

Element Information

Number of occurrences | 0 or 1
Parent elements | ScalarType Parameter FunctionExtension
Child elements | Localized

See Also

XLL+ Extensions Schema


Parameter Element

This element defines a parameter to either a function extension or an extended argument type. It may contain any or all of the following optional child elements, each of which may appear only once or not at all: LocalizedDisplayName, LocalizedDescription, RejectionMessage. It must contain the following required attributes: name, parameterType and defaultValue. It may contain the following optional attributes: filter, availableAtRuntime.

Attributes

name

Required. The name attribute uniquely defines the name of the parameter. The name is not used in any C++ code, and does not need to be a valid C++ identifier. However, it may be used in the persisted form of any argument or function that uses it, and therefore can never be changed.

parameterType

Required. The parameterType attribute determines the C++ type of the parameter. It must be one of: Boolean, Integer, String.

defaultValue

Required. The defaultValue attribute contains a string that will be used as the default value for this parameter. It must be a legal C++ value of the appropriate type. Thus for Boolean parameters, it should be true, false or a global variable of C++ type bool. For Integer parameters, it should be a numeric literal, e.g. 0, 123, -999, or a global variable of C++ type int. For String parameters, it should be a string literal, e.g. "", "abc", 0, L"", L"abc" or a global variable of C++ type const char* or const wchar_t*.

filter

The filter attribute optionally contains a regular expression which will be tested against any value entered for the parameter in the XLL+ design-time user interface. The filter attribute is used only for String type parameters, and is ignored for other types. If a filter attribute is provided, and a value fails to match the regular expression, then an error message will be displayed, and the developer will have to try another value. You may optionally provide the error message in the RejectionMessage element (which may be localized). If no RejectionMessage element is provided, then a standard error message will be displayed.

availableAtRuntime

The availableAtRuntime attribute determines whether the value of the parameter will be made available at run-time to the convert class instance. If it is set to true, then the converter class's implementation of ConvertFromExcel() can use params.GetIntParam(n), params.GetStringParam(n) or params.GetBoolParam(n) to retrieve the value. If it is set to false, then the parameter will be available to the code generator, but will not be made available at run-time.

Element Information

Number of occurrences | Unlimited
Parent elements | Parameters
Child elements | LocalizedDisplayName LocalizedDescription RejectionMessage

See Also

XLL+ Extensions Schema


Parameters Element

This optional element contains a list of the type's parameters.

Element Information

Number of occurrences | 0 or 1
Parent elements | ScalarType FunctionExtension
Child elements | Parameter

See Also

XLL+ Extensions Schema


RejectionMessage Element

This optional element contains a localizable message which will be used when an illegal value is entered for the parameter in the XLL+ Function Wizard. The text attribute is required, and will be used as the default value if no suitable localized values are found. This element may contain the optional element Localized, which contains localized versions of the text.

Attributes

text

Required. The text attribute is required, and will be used as the default value if no suitable localized values are found.

Element Information

Number of occurrences | 0 or 1
Parent elements | Parameter
Child elements | Localized

See Also

XLL+ Extensions Schema


ScalarType Element

This element defines an extended scalar type. It may contain any or all of the following optional child elements, each of which may appear only once or not at all: LocalizedDisplayName, LocalizedDescription, Parameters. It must contain the following required attributes: name, cppType, excelType and converterType. It may contain the following optional attributes: headerFiles, ignoreLocalHeaders, optionalAllowed and converterTypeArguments.

Attributes

converterType

Required. The converterType attribute should contain the name of the class which will convert values between their Excel form (as specified by the excelType attribute) and the native C++ form (as specified by the cppType attribute). The class name should include a namespace if necessary. Any tokens in the form "{n}", where n is an integer, will be replaced the value of the nth parameter.

converterTypeArguments

The converterTypeArguments attribute, if provided, should contain a comma-separated list of arguments that will be passed to the constructor of the converter class instance. Any tokens in the form "{n}", where n is an integer, will be replaced the value of the nth parameter.

name

Required. The name attribute uniquely defines the name of the extended type. If two extended types use the same name, then the one that is loaded second will override the one that was loaded first. The name is not used in any C++ code, and does not need to be a valid C++ identifier. However, it is used as the persisted form of an argument's type, and therefore can never be changed.

cppType

Required. This attribute must contain the name of the extended type, as it will be written in C++ code, e.g. "double", "std::string", "MyNamespace::MyClass".

excelType

Required. This attribute must contain Excel's representation of the type. It must be one of: Boolean, Double, String, Short, UShort, Int.

optionalAllowed

If this attribute is set to true, then arguments of this type may be omitted, and arrays of this type may have their empty cells filled with default values. Note: There must exist a parameter-less constructor for cppType in order that the code generated for optional arguments compile successfully.

headerFiles

The headerFiles attribute contains a list of the header files that are needed in order for the code inserted by this extended type to compile correctly. This list should include the file where th converterType class is declared. The file name should not be surrounded by quotes or <...>. Multiple file names can be used, and should be separate by semi-colons, e.g. "myfile.h;..\inc\otherfile.h". Each file will be inserted as a local file if ignoreLocalHeaders is false, e.g. #include "myfile.h", and as a global file if ignoreLocalHeaders is true, e.g. #include <myfile.h>.

ignoreLocalHeaders

The ignoreLocalHeaders attribute controls whether the list of header files contained in the headerFiles attribute will be treated as local or global header files. Each file will be inserted as a local file if ignoreLocalHeaders is false, e.g. #include "myfile.h", and as a global file if ignoreLocalHeaders is true, e.g. #include <myfile.h>.

Element Information

Number of occurrences | Unlimited
Parent elements | ScalarTypes
Child elements | LocalizedDisplayName LocalizedDescription Parameters

See Also

XLL+ Extensions Schema


ScalarTypes Element

This is the container element for ScalarType definitions. The ScalarTypes element may contain zero or more ScalarType child elements. The ScalarTypes element has no attributes.

Element Information

Number of occurrences | 0 or 1
Parent elements | Extensions
Child elements | ScalarType

See Also

XLL+ Extensions Schema


XLL+ Help Schema

This schema defines the contents of an XLL+ help file. The root node of the schema is the Help element.

Read Help in the User Guide for more information on XLL+ help files.

Elements

Element | Description
AdditionalFile | The AdditionalFile element adds a user-supplied HTML file to the help system.
Argument | The Argument element controls the appearance of the help for a particular argument of a function.
Description | A Description element can contain simple text or XHTML elements which will be inserted directly into the Description section of a help page, immediately after the standard description.
Function | A Function element controls the appearance of a single named function page.
Help | The Help element is the root element of the help file.
Project | Controls the title of the help project, and the content of the front page.
Remarks | Contains XHTML elements which will be inserted directly into the text of a help page.
ResourceFile | The ResourceFile element adds a user-supplied graphics or style file to the help system.
Section | Controls the appearance of one category page.
SeeAlso | Inserts a link into the See Also list for a page.
TextDescription | Controls the main description section for a function or argument.


AdditionalFile Element

An AdditionalFile element adds one HTML source file to the help system. An additional file must be in the same directory as the help file that refers to it. The required attribute Source should be set to the name of the source file, e.g. "myfile.htm". The AdditionalFile element may contain any number of SeeAlso elements. It has two optional attributes: Title and ApplyCommonFormat.

Attributes

Source

Required. The Source attribute is required. It should be set to the file name. Additional files must be in the same directory as the help file that specifies them.

Title

The optional Title attribute controls the main title of the page. If omitted, the title element in the HTML source file will be used. This attribute is ignored if ApplyCommonFormat is false.

ApplyCommonFormat

The optional ApplyCommonFormat attribute controls whether the contents of the HTML file are wrapped in the common page format used by the other pages in the help project. If true, then the title element and the contents of the body element will be extracted and placed into a standard page. The HTML file must be XHTML, using the schema http://www.w3.org/1999/xhtml. If false, then the file will be copied into the help project with no changes.

Element Information

Number of occurrences | Unlimited
Parent elements | Help
Child elements | SeeAlso

See Also

XLL+ Help Schema


Argument Element

The Argument element controls the appearance of the help for a particular argument of a function. It should always appear inside a Function element. The required attribute Name should be set to the name of the argument to which the element applies. The Argument element may contain zero or one Description element, and any number of TextDescription elements. The element has one optional attribute: Syntax.

Attributes

Name

Required. The Name attribute is required. It defines which argument this element will be applied to.

Syntax

The Syntax attribute controls the position of the standard argument syntax-based text, such as "X should be a vector of numbers...". The text may be positioned as a continuation of the argument's description (Continuation), as a paragraph following the argument's description (Paragraph), or omitted (None). If omitted, it is assumed to be Continuation.

HideValueList

If the HideValueList attribute is false or omitted, then a table of values and descriptions will be added to the argument's help text if a value list is present. If the attribute is true, then the table will be omitted.

Element Information

Number of occurrences | Unlimited
Parent elements | Function
Child elements | TextDescription Description

See Also

XLL+ Help Schema


Description Element

A Description element can contain simple text or XHTML elements which will be inserted directly into the Description section of a help page, immediately after the standard description. Free text will be placed within a new paragraph; XHTML elements will be inserted directly.

Element Information

Number of occurrences | 0 or 1
Parent elements | Project Section Function Argument
Child elements | (No child elements)

See Also

XLL+ Help Schema


Function Element

A Function element controls the appearance of a single named function page. The required attribute ExportedName should be set to the public name of the function the page describes. The Function element may contain zero or one Description element, and any number of TextDescription, Remarks, SeeAlso and Argument elements.

Attributes

ExportedName

Required. The ExportedName attribute is required. It should match the exported name of a function, i.e. the name that is visible in Excel.

Exclude

The Exclude attribute is optional. If it is present and true, then this function will not be included in the help system.

Element Information

Number of occurrences | Unlimited
Parent elements | Help
Child elements | TextDescription Description Remarks SeeAlso Argument

See Also

XLL+ Help Schema


Help Element

The Help element is the root element of the help file. It may contain zero or one Project element, and any number of Section, Function, AdditionalFile and ResourceFile elements. The element has four optional attributes: Language, CopyFileExtensions, HideArgumentSyntax and ArgumentSyntax.

Attributes

Language

The Language attribute, if provided, defines the language of the help project. A list of supported languages can be found in the XSL transform file, Localized.xsl, located in the bin\xsl directory of the XLL+ installation. If the attibute is omitted, then the default value of "en" (English) is used.

CopyFileExtensions

The CopyFileExtensions attribute, if provided, contains a list of file extensions, separated by semi-colons, e.g. "jpg;gif;png". Any file with this extension found in the help directory will be copied to the help project. If omitted, a standard list of graphics file extensions weill be used. Single files can also be copied using the ResourceFile element.

HideArgumentSyntax

The HideArgumentSyntax attribute, if true, hides the standard argument syntax-based text, such as "X should be a vector of numbers...". Setting the attribute at Project level applies it to all arguments of all functions. If omitted, it is assumed to be false.

ArgumentSyntax

The ArgumentSyntax attribute controls the position of the standard argument syntax-based text, such as "X should be a vector of numbers...". The text may be positioned as a continuation of the argument's description (Continuation), as a paragraph following the argument's description (Paragraph), or omitted (None). Setting the attribute at Project level applies it to all arguments of all functions. If omitted, it is assumed to be Continuation.

Element Information

Number of occurrences | Unlimited
Parent elements | (No parent elements)
Child elements | Project Section Function AdditionalFile ResourceFile

See Also

XLL+ Help Schema


Project Element

The Project element may appear once or not at all. The element controls the title of the help project, and the content of the front page. It may contain zero or one Description element, and any number of Remarks and SeeAlso elements. It has two optional attributes: Title and ListCategories.

Attributes

Title

The Title attribute controls the title of the entire help file. This title appears in (i) the title bar of the help window; (ii) the front page and (iii) the "bread-crumb" links at the top of each page. If omitted, a default title based on the file name of the XLL file wil be used.

ListCategories

By default the front page contains a list of all the categories of function contained in the add-in. The ListCategories attribute can be set to false to omit this list. If omitted, it is assumed to be true.

Element Information

Number of occurrences | 0 or 1
Parent elements | Help
Child elements | Description Remarks SeeAlso

See Also

XLL+ Help Schema


Remarks Element

A Remarks element should contain XHTML elements which will be inserted directly into the text of a help page. It should not contain free text, only elements such as p, ul, ol etc. The optional Caption attribute can be used to control the title of the section.

Attributes

Caption

The Caption attribute controls the title of the Remarks section. If omitted, the title "Remarks" will be used.

Element Information

Number of occurrences | Unlimited
Parent elements | Project Section Function
Child elements | (No child elements)

See Also

XLL+ Help Schema


ResourceFile Element

A ResourceFile element adds one graphics or other resource file to the help system. An resource file must be in the same directory as the help file that refers to it. The required attribute Source should be set to the name of the source file, e.g. "myfile.bmp". Note that files matching the extensions listed in Help/@CopyFileExtensions will all be copied, and do not require individual ResourceFile elements.

Attributes

Source

Required. The Source attribute is required. It should be set to the file name of the resource file. Wild-cards may be used e.g. "equation_*.gif". Resource files must be in the same directory as the help file that specifies them.

Element Information

Number of occurrences | Unlimited
Parent elements | Help
Child elements | (No child elements)

See Also

XLL+ Help Schema


Section Element

A Section element controls the appearance of one category page. The required attribute Category should be set to the name of the category of function the page describes, e.g. "Information", "Math & Trig". The Section element may contain zero or one Description element, and any number of Remarks and SeeAlso elements. It has one optional attribute: Title.

Attributes

Category

Required. The Category attribute is required. It should be set to the US English name of the function category to which the Section element applies.

Title

The optional Title attribute controls the main title of the page. If omitted, a default title based on the category will be used, e.g. "Infomation functions".

Element Information

Number of occurrences | Unlimited
Parent elements | Help
Child elements | Description Remarks SeeAlso

See Also

XLL+ Help Schema


SeeAlso Element

The SeeAlso element inserts a link into the See Also list for a page. The text of the element will appear as the link title; the target of the link is controlled by the href attribute.

Element Information

Number of occurrences | Unlimited
Parent elements | Project Section Function AdditionalFile
Child elements | (No child elements)

See Also

XLL+ Help Schema


TextDescription Element

A TextDescription controls the main description section for a function or argument. It can be used to place text before or after the standard description, or to replace the standard description completely. It may contain only unformatted text. It has one optional attribute: Position.

Element Information

Number of occurrences | Unlimited
Parent elements | Function Argument
Child elements | (No child elements)

See Also

XLL+ Help Schema


XLL Wrapper Generator Schema

This schema defines the contents of an XLL+ Wrapper Generator information file. The root node of the schema is the XllWrapper element.

Read the XLL Wrapper Generator User Guide for more information on XLL+ help files.

Elements

Element | Description
Argument | An Argument element is an optional element which controls the wrapping of a single named argument.
Client | The Client element controls the generation of code for a single client type (COM or VBA).
Clients | The Clients element should contain one or more Client elements. Each Client element will be transformed to a wrapper class designed for the specified client type.
ErrorPrefix | Each ErrorPrefix element should contain a text string. If an add-in function returns a string value which starts with the specified text string, then an exception will be raised, using the remainder of the string value (after the prefix has been removed) as the error message.
ErrorPrefixes | The ErrorPrefixes element may contain one or more ErrorPrefix elements.
Function | A Function element will modify the code generation for a single wrapper method.
Functions | The Functions element should contain zero or more Function elements. Each Function element will modify the code generation for a single wrapper method.
XllWrapper | XllWrapper is the root element of an information file.


Argument Element

An Argument element is an optional element which controls the wrapping of a single named argument.

Attributes

Name

Required. The name of the argument as it appears in the Name attribute of the XlArgument element in the model file.

IsDate

If 1, then the argument will be treated as a date (or an array of dates). In the wrapper class, the argument's type will be DateTime (or DateTime[] or DateTime[,] for an array). If 0 or omitted, then the argument's type will be treated normally.

WrappedName

If this attribute is provided, then it will be used as the name of the argument in the wrapper function. This can be useful in avoiding reserved words, or other naming conflicts.

Type

The argument type, as it will appear in the C# wrapper function. Only the following basic types are supported: bool, DateTime, double, int, string, object. The return type may be a scalar (e.g. int), a vector (e.g. int[]) or a matrix (e.g. int[,]). An argument that accepts a vector or matrix of mixed types should use object[] or object[,] respectively. An argument that accepts a variety of different input types should use object.

Element Information

Number of occurrences | Unlimited
Parent elements | Function
Child elements | (No child elements)

See Also

XLL Wrapper Generator Schema


Client Element

The Client element controls the generation of code for a single client type (COM or VBA). It has 6 required attributes: Type, Namespace, Class, ClassGuid, Interface and InterfaceGuid.

Attributes

Type

Required. The Client Type must one of: COM, VBA. This attribute controls the signatures of the wrapper functions. VBA clients are more restrictive, particularly for array arguments.

Namespace

Required. The namespace used for the generated class. This should be a valid C# namespace.

Class

Required. The name of the generated C# wrapper class. This should be a valid C# class name.

ClassGuid

Required. The globally unique identifier of the generated class. (This should not include braces, but should include hyphens.)

Interface

Required. The name of the COM interface class which will be used as the wrapper class’s default interface.

InterfaceGuid

Required. The globally unique identifier of the generated interface. (This should not include braces, but should include hyphens.)

Element Information

Number of occurrences | Unlimited
Parent elements | Clients
Child elements | (No child elements)

See Also

XLL Wrapper Generator Schema


Clients Element

The Clients element should contain one or more Client elements. Each Client element will be transformed to a wrapper class designed for the specified client type.

Element Information

Number of occurrences | Unlimited
Parent elements | XllWrapper
Child elements | Client

See Also

XLL Wrapper Generator Schema


ErrorPrefix Element

Element Information

Number of occurrences | Unlimited
Parent elements | ErrorPrefixes
Child elements | (No child elements)

See Also

XLL Wrapper Generator Schema


ErrorPrefixes Element

The ErrorPrefixes element contains the standard error prefixes to be used for all add-in functions in the project. The ErrorPrefixes element may contain one or more ErrorPrefix elements. If an add-in function returns a string value which starts with any of the text strings specified in the ErrorPrefix elements, then an exception will be raised, using the remainder of the string value (after the prefix has been removed) as the error message. If the ErrorPrefixes element contains zero ErrorPrefix elements, then no testing against string values will occur.

Element Information

Number of occurrences | Unlimited
Parent elements | XllWrapper Function
Child elements | ErrorPrefix

See Also

XLL Wrapper Generator Schema


Function Element

A Function element will modify the code generation for a single wrapper method. The ExportedName attribute controls which add-in function is affected. The element has 1 required attribute (ExportedName) and 3 optional attributes: Wrap, WrappedName, and ReturnType. The Function element may also contain zero or more Argument elements.

Attributes

ExportedName

Required. The name of the add-in function to be wrapped, as it appears in Excel, and as the ExportedName attribute of the XlFunction element in the model file.

Wrap

The Wrap attribute controls whether a wrapper method will be generated for the specified function. Set it to None to remove the function from the list of wrapped functions. If missing, Always or Default, the function will be wrapped.

ReturnType

The function's return type, as it will appear in the C# wrapper function. Only the following basic types are supported: bool, DateTime, double, int, string, object. The return type may be a scalar (e.g. int), a vector (e.g. int[]) or a matrix (e.g. int[,]). A function that returns a vector or matrix of mixed types should use object[] or object[,] respectively.

WrappedName

If this attribute is provided, then it will be used as the name of the argument in the wrapper function. This can be useful in avoiding reserved words, or other naming conflicts.

NoExceptionOnError

If 0 or omitted, then an exception will be thrown if the function returns either an error value or a string beginning with one of the specified ErrorPrefixes. If 1, then an error value will be returned as a COM error value.

Element Information

Number of occurrences | Unlimited
Parent elements | Functions
Child elements | ErrorPrefixes Argument

See Also

XLL Wrapper Generator Schema


Functions Element

The Functions element should contain zero or more Function elements. Each Function element will modify the code generation for a single wrapper method.

Element Information

Number of occurrences | Unlimited
Parent elements | XllWrapper
Child elements | Function

See Also

XLL Wrapper Generator Schema


XllWrapper Element

XllWrapper is the root element of an information file. It contains up to three elements: Clients, ErrorPrefixes and Functions. It has one mandatory attribute: Name.

Attributes

Name

Required.

Element Information

Number of occurrences | Unlimited
Parent elements | (No parent elements)
Child elements | Clients ErrorPrefixes Functions

See Also

XLL Wrapper Generator Schema


XLL+ Function Schema

This schema defines the contents of an XLL+ function definition file. The root node of the schema is the Project element.

Two types of function are supported:

  1. XlFunction elements, which contain only the function's signature and definition, and may be accompanied by a matching CodeBody element, which contains the code of the function.
  2. GeneratedFunction elements, which contain both the function's signature and its code.

Elements

Element | Description
Arguments | The container element for XlArgument elements.
Bounds | The container element for XlBound elements.
CodeBodies | The container element for CodeBody elements.
CodeBody | Contains the code which will be inserted into the function generated for the corresponding XlFunction element.
ExtendedParameters | The container element for XlArgumentExtendedParameter elements.
Extensions | The container element for XlFunctionExtension elements.
Functions | The container element for XlFunction elements.
GeneratedFunction | Contains the signature and specification of a function and also its contents.
GeneratedFunctions | The container element for GeneratedFunction elements.
InsertedCode | Contains (as text) the code which will be inserted into the function.
Parameters | The container element for XlFunctionExtensionParameter elements.
Parts | The container element for XlBoundPart elements.
Project | The top-level container element for the file.
Signature | Defines the data type, rank and behavior of an argument.
ValueList | A list of the values of which the argument's value may or must be a member.
XlArgument | A single argument to an Excel add-in function, or an argument contained within a Choice or Group argument.
XlArgumentExtendedParameter | A single parameter value for an argument of extended type.
XlBound | Represents a dimension of a vector or matrix argument.
XlBoundPart | Represents the lower or upper bound of a dimension.
XlFunction | Represents the signature and definition of a single Excel add-in function.
XlFunctionExtension | A named extension applied to a function.
XlFunctionExtensionParameter | A parameter value for a function extension.
XlValueListItem | An enumerated value for an argument, along with a description of the value


Arguments Element

This is the container element for XlArgument elements. The Arguments element may contain zero or more XlArgument child elements. The Arguments element has no attributes.

Element Information

Number of occurrences | 1
Parent elements | XlFunction
Child elements | XlArgument

See Also

XLL+ Function Schema


Bounds Element

Collection of bounds. A vector has one bound, a matrix has two, and a scalar has none. For each bound, this element has one XlBound child element. The Bounds element has no attributes.

Element Information

Number of occurrences | Unlimited
Parent elements | Signature
Child elements | XlBound

See Also

XLL+ Function Schema


CodeBodies Element

This element contains a collection of zero or more CodeBody elements. If present, these should be in the same order as the XlFunction elements contained by the Functions element. The code contained in each will be inserted into the corresponding XlFunction.

Element Information

Number of occurrences | 0 or 1
Parent elements | Project
Child elements | CodeBody

See Also

XLL+ Function Schema


CodeBody Element

This element contains a single required child element: InsertedCode. The contents of each CodeBody element will be inserted into the function generated for the corresponding XlFunction element. The element also contains a single required attribute: ExportedName.

Attributes

ExportedName

This is the name of the function into which the code will be inserted. It should match the ExportedName attribute in an XlFunction element.

Element Information

Number of occurrences | Unlimited
Parent elements | CodeBodies
Child elements | InsertedCode

See Also

XLL+ Function Schema


Enums Element

The Enums element is currently ignored.

Element Information

Number of occurrences | 0 or 1
Parent elements | XlFunction
Child elements | (No child elements)

See Also

XLL+ Function Schema


ExtendedParameters Element

This element contains a collection of extended parameters. Contains one parameter value for each of the parameters implied by the argument's type. The ExtendedParameters element has no attributes.

Element Information

Number of occurrences | Unlimited
Parent elements | Signature
Child elements | XlArgumentExtendedParameter

See Also

XLL+ Function Schema


Extensions Element

The set of function extensions that have been added to the function. This property controls the list of extensions that have been added to the function. If the extension has properties, these are also stored.

Element Information

Number of occurrences | 1
Parent elements | XlFunction
Child elements | XlFunctionExtension

See Also

XLL+ Function Schema


Functions Element

This is the container element for XlFunction elements. The Functions element may contain zero or more XlFunction child elements. The Functions element has no attributes.

Element Information

Number of occurrences | 0 or 1
Parent elements | Project
Child elements | XlFunction

See Also

XLL+ Function Schema


GeneratedFunction Element

This element contains the signature and specification of a function (as a child XlFunction element) and also its contents (as a child InsertedCode element). It is, in effect, a combination of an XlFunction element and a CodeBody element.

Element Information

Number of occurrences | Unlimited
Parent elements | GeneratedFunctions
Child elements | XlFunction InsertedCode

See Also

XLL+ Function Schema


GeneratedFunctions Element

This element contains a collection of zero or more GeneratedFunction elements.

Element Information

Number of occurrences | 0 or 1
Parent elements | Project
Child elements | GeneratedFunction

See Also

XLL+ Function Schema


InsertedCode Element

The code contained in this element will be inserted directly into the body of the generated function. No substitutions will be performed. It is advisable to wrap the contents in a CDATA section.

Element Information

Number of occurrences | 1
Parent elements | GeneratedFunction CodeBody
Child elements | (No child elements)

See Also

XLL+ Function Schema


Parameters Element

This element contains a collection of extended parameters. Contains one parameter value for each of the parameters defined by the function extension. The Parameters element has no attributes.

Element Information

Number of occurrences | 0 or 1
Parent elements | XlFunctionExtension
Child elements | XlFunctionExtensionParameter

See Also

XLL+ Function Schema


Parts Element

Collection of 2 bound parts, one representing each of the lower and upper bounds of the dimension. The first child element represents the lower bound, the second the upper bound.

Element Information

Number of occurrences | Unlimited
Parent elements | XlBound
Child elements | XlBoundPart

See Also

XLL+ Function Schema


Project Element

This is the top-level container element for every function file. The Project element may contain any or all of the following child elements: Functions, GeneratedFunctions, CodeBodies, in any order. The Project element has no attributes. If there are any items in the Functions element, then there must an equal number of items in the CodeBodies section.

Element Information

Number of occurrences | Unlimited
Parent elements | (No parent elements)
Child elements | Functions GeneratedFunctions CodeBodies

See Also

XLL+ Function Schema


Signature Element

The Signature element defines the data type, rank and behavior of an argument. The Signature element may contain some or all of the following child elements: Bounds, ExtendedParameters. It has a single required attribute: Type. The element may contain one optional attribute: Flags.

Attributes

Type

Required.

Flags

The Flags attribute should contain either an integer or a set of space-separated flag names. In either case, the value represents an OR-ing of any of the following flag values: Optional (0x20), BlankToDefault (0x80), NonNumericToDefault (0x40), ZeroToDefault (0x10), TruncateOnNil (0x2), TruncateOnBlank (0x8), TruncateOnZero (0x1), TruncateOnNonNumeric (0x4), VectorIsRow (0x10000), VectorIsColumn (0x4000), FillUsedArea (0x01000000), FillAll (0x02000000), TransposeMatrix (0x100), FlatMatrixStorage (0x400000), RejectNullArray (0x400), UpperBoundInner (0x00100000), UpperBoundAuto (0x00200000), CellEmptyToDefault (0x10000000), CellBlankToDefault (0x40000000), CellZeroToDefault (0x08000000), CellNonNumericToDefault (0x20000000).

Element Information

Number of occurrences | 1
Parent elements | XlArgument
Child elements | Bounds ExtendedParameters

See Also

XLL+ Function Schema


ValueList Element

A list of the values of which the argument's value may or must be a member. The ValueList element must contain one or more XlValueListItem elements. The ValueList element has no attributes.

Element Information

Number of occurrences | 0 or 1
Parent elements | XlArgument
Child elements | XlValueListItem

See Also

XLL+ Function Schema


XlArgument Element

This element represents a single argument to an Excel add-in function, or an argument contained within a Choice or Group argument. The XlArgument element must have the following required child element: Signature. The XlArgument element may have the following optional child element: ValueList. The XlArgument element has the one required attribute: Name. The XlArgument element may have any or all of the following optional attributes: Description, DefaultValueText, ContainerClass, ValueListIsExclusive, ShowValueListInFormulaWizard, ShowPopupInFormulaWizard.

Attributes

Name

Required. Name of the argument, as it will appear in the Excel Formula Wizard. This name should be unique within a function. If it is not, then warnings will be issued by the XLL+ tools and the code will fail to compile.

Description

Description of the argument, as it will appear in the Excel Formula Wizard.

DefaultValueText

Default value used for argument if it is empty or missing. This text value will be inserted directly into code as the right-hand-side of an assignment.

ContainerClass

Template class used in C++ for the targets of vector or matrix arguments. For each vector or matrix argument to an add-in function, a local container variable is declared, and the input is copied into it after validation. If the argument's ContainerClass property is set, then the container will be of the type specified by the property. However, if the argument's container class property is left empty (the default), then the container class used will be that specified by DefaultVectorContainer or DefaultMatrixContainer as appropriate.

ValueListIsExclusive

Controls whether a value list is used to validate inputs. If this property is set to true, then the value list will be used to constrain the value of the input. If the input is not one of the values in the list, then an exception will be raised and the function will report an input error.

ShowValueListInFormulaWizard

Controls whether a value list is used to display a drop-down list in the Excel Formula Wizard. If this property is set to true, then the value list will be used to display a drop-down list in the Excel Formula Wizard. The property is ignored for arguments that are not scalar integer values.

ShowPopupInFormulaWizard

Sets whether the argument should have a popup button in the Formula Wizard. If false, this property will be ignored. If true, then the argument will be marked as requiring the Excel Formula Wizard extended user interface. The developer is reponsible for creating a class derived from CXlWizExUIPopupProviderBase, and for registering it, using CXlWizExUIArgumentPopupCreator.

Element Information

Number of occurrences | Unlimited
Parent elements | Arguments
Child elements | Signature ValueList

See Also

XLL+ Function Schema


XlArgumentExtendedParameter Element

The XlArgumentExtendedParameter element represents a single parameter value for an argument of extended type. The element has one attribute, Value, and no child elements.

Attributes

Value

Element Information

Number of occurrences | Unlimited
Parent elements | ExtendedParameters
Child elements | (No child elements)

See Also

XLL+ Function Schema


XlBound Element

The XlBound element represents a dimension of a vector or matrix argument. It contains one required attribute, Index, and no optional attributes. It contains one required child element: Parts.

Attributes

Index

The Index attribute contains the index of the bound: always 0 for a vector, and either 0 or 1 for a matrix.

Element Information

Number of occurrences | Unlimited
Parent elements | Bounds
Child elements | Parts

See Also

XLL+ Function Schema


XlBoundPart Element

The XlBoundPart element represents the lower or upper bound of a dimension. The element can contain any or all of the following attributes: HasFixedSize, FixedSize and NamedBound. For a lower bound, the element should contain either no attributes or HasFixedSize=true and FixedSize=1. The latter case represents a 1-based array; the former case a normal 0-based array. For an upper bound, if HasFixedSize=true and FixedSize is present, then the dimension will be constrained to be of size FixedSize, and a run-time error will be generated if it is not. If NamedBound is present, then a variable will be created with the specified name, and will be set to the size of the dimension at run-time. If NamedBound is shared with any other dimension of this or of another argument, then the bounds will be constrained to be of the same size, and a run-time error will be generated if they are not.

Attributes

HasFixedSize

If HasFixedSize is set to true, then the bound will fixed to the value set in FixedSize. If it is false or omitted, then FixedSize will be ignored, and the bound will not be constrained.

FixedSize

For a lower bound, this value represents the base value of an array, and may be 0 or 1. For an upper bound, this value represents the expected size of the array in this dimension; if the array is not of this size, then an error will be raised at run-time. If HasFixedSize is false or omitted, then FixedSize will be ignored, and the bound will not be constrained.

NamedBound

If NamedBound is present in an upper bound, then a variable will be created with the specified name, and will be set to the size of the dimension at run-time. If NamedBound is shared with any other dimension of this or of another argument, then the bounds will be constrained to be of the same size, and a run-time error will be generated if they are not. NamedBound is ignored for lower bounds.

Element Information

Number of occurrences | Unlimited
Parent elements | Parts
Child elements | (No child elements)

See Also

XLL+ Function Schema


XlFunction Element

This element represents a single Excel add-in function. The XlFunction element must contain the following required child element: Arguments. The XlFunction element may contain the following optional child element: Extensions. The XlFunction element may also contain an empty and attribute-less Enums element, which will be ignored. The XlFunction element has the following required attributes: ExportedName, Category. The XlFunction element has the following optional attributes: Availability, EntryPointXL4, EntryPointXL12, Flags, HelpId, ReturnType, Versions, Description, TemplateKey, ExportedNameAsync, ExportedNameQueued, ExportedNameSync. The following optional attributes are ignored: SourceFile, SourceLine, CategoryForLocale, CategoryUSEnglish, SafeName.

Attributes

ExportedName

Required. The name of the function as it will appear in Excel. This name should be unique within an add-in. If it is not, then the function will not be registered, and the code may not even compile. The XLL+ tools issue warnings when a duplicate function name is used. The ExportedName property controls the default values of several other properties, including EntryPointXL4, EntryPointXL12.

EntryPointXL4

By default the 'C' entry point for Excel 2003 and below is ExportedName followed by "_4". This value can be overridden by setting the EntryPointXL4 attribute. The default value for this attribute is empty.

EntryPointXL12

By default the 'C' entry point for Excel 2007 and above is ExportedName followed by "_12". This value can be overridden by setting the EntryPointXL12 attribute. The default value for this attribute is empty.

Category

Required. Category in which the function will appear within the Excel Formula Wizard. The standard built-in categories are stored as numbers between 1 and 14. See the XLL+ documentation for a list of category numbers.

Availability

The conditions under which the function will be available: from a worksheet cell, from a macro or hidden. Availability may have one of the following values: Hidden, Worksheet or Macro.

Versions

Controls which Excel versions the function will support explicitly. Versions may have one of the following values: Excel2003AndBelow indicates Excel 95 to Excel 2003; Excel2007AndAbove indicates Excel 2007 upwards; and AllExcelVersions indicates all Excel versions from Excel 95 upwards. This attribute controls the code that will be generated by XLL+. If Versions is set to AllExcelVersions then two wrapper functions will be generated, one for each environment, and the appropriate one will be registered, depending on which version of Excel is running. If only one environment is supported then only one wrapper function will be generated. If Excel2003AndBelow is used then the add-in will work in all versions of Excel, but will not take advantage of the new features of Excel 2007 and above. If Excel2007AndAbove is used, then the function will not be available in Excel 2003 and below.

Flags

The Flags attribute should contain either an integer or a series of space-separated strings. In either case the attribute can contain some or all of: ThreadSafe (1), HideInFormulaWizard (2), Volatile (8), DeferRecalc (16), CacheResults (64), CreateAsyncVersion (512), CreateQueuedVersion (1024).

HelpID

If a function has a non-zero help ID, then it will be used to resolve the help topic for the file when the user clicks "Help on this function". The default value for HelpId is zero.

Description

Description of the function which will appear within the Excel Formula Wizard. The default value for Description is empty.

ReturnType

The value will always be CXlOper for functions that return a variable type, or that return arrays, or that may fail. The default value for ReturnType is CXlOper. ReturnType may have any of the following values: Boolean, Double, Short, UShort, Int, CXlOper.

TemplateKey

Identifies the template used to generate the code of this function. The default value for TemplateKey is empty.

ExportedNameAsync

The Excel name used for the asynchronous version of the function. If omitted or blank, a default value will be used. (Ignored if CreateAsyncVersion is not specified.) The default value for the property is the empty string.

ExportedNameQueued

The Excel name used for the queued version of the function. If omitted or blank, a default value will be used. (Ignored if CreateQueuedVersion is not specified.) The default value for the property is the empty string.

ExportedNameSync

The Excel name used for the synchronous version of the function. If omitted or blank, a default value will be used. (Ignored if CreateAsyncVersion or CreateQueuedVersion are not specified.) The default value for the property is the empty string.

SourceFile

Ignored.

SourceLine

Ignored.

CategoryForLocale

Ignored.

CategoryUSEnglish

Ignored.

SafeName

Ignored.

Element Information

Number of occurrences | Unlimited
Parent elements | Functions GeneratedFunction
Child elements | Arguments Extensions Enums

See Also

XLL+ Function Schema


XlFunctionExtension Element

The XlFunctionExtension element represents a named extension applied to a function. The element will cause extra code to be generated for the function, as defined by the function extension's definition. The element may have one child element: Parameters. The element has one required attribute, name, and no optional attributes.

Attributes

name

The name of the function extension, which must match the name declared in the function extension's definition.

Element Information

Number of occurrences | Unlimited
Parent elements | Extensions
Child elements | Parameters

See Also

XLL+ Function Schema


XlFunctionExtensionParameter Element

The XlFunctionExtensionParameter element represents a single parameter value for a function extension. The element has one attribute, Value, and no child elements.

Attributes

Value

Element Information

Number of occurrences | Unlimited
Parent elements | Parameters
Child elements | (No child elements)

See Also

XLL+ Function Schema


XlValueListItem Element

The XlValueListItem element represents an enumerated value for an argument, along with a description of the value. The following attributes are required: Value, Description.

Attributes

Value

Required. The value against which the argument's value will be compared, and which will be inserted into the formula if the item is selected in the Excel Formula Wizard.

Description

Required. The string which will appear (alongside the value) in the drop-down which appears in the Excel Formula Wizard.

Element Information

Number of occurrences | 1 or more
Parent elements | ValueList
Child elements | (No child elements)

See Also

XLL+ Function Schema


Help Generator

XLL+ contains a help generator tool which will generate a complete compiled help (CHM) project for your add-in.

Topics

Generating Help (User Guide)
Help Generator Reference
Additional files in help projects
Help Builder command line utility


Additional Files

The XLL+ Help Generator lets you add your own HTML files to a help project.

You can choose to have your HTML file processed so that it gets the same look as a generated help page.

AdditionalFile element

Each HTML file that you wish to add to your project should be described in an AdditionalFile element in the help file.

If you want to have the HTML file processed to get the same look a a generated help file, set the ApplyCommonFormat attribute to true, e.g.:

CopyXML
<AdditionalFile Source="MyFile.htm"
                Title="My Topic"
                ApplyCommonFormat="true" />

The Title attribute is ignored unless ApplyCommonFormat is true. If ApplyCommonFormat is true, then the additional file will be listed in the help project's table of contents, using the Title attribute.

If you are happy with the formatting of your HTML page, you can add it to your project without further processing by setting the ApplyCommonFormat to false. The file will simply be copied to the bin directory and added to the help project. It will not be added to the table of contents.

Additional HTML files (whether processed or copied) must be in the same directory as the help file.

File format

An HTML file that is to be processed using the common format must be in XHTML, and must contain a reference to the XHTML schema. In practise this means:

  1. The following line must appear at the top of the file:

    CopyXML
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  2. All stand-alone elements must be closed. For example, you must use <br /> instead of <br>.

  3. HTML element names should be in lower case, e.g. <body>, not <BODY>.

Resource files

Your HTML files (whether processed or copied) may refer to other files, such as images or style sheets. Every such resource file must be in the same directory as the help file The help generator will include these files in the project automatically if they have one of the following extensions:

  • jpg
  • gif
  • png
  • css

You can override the list of extensions by setting the CopyFileExtensions attribute of the Help element in the help file.

Alternatively, you can specify that one or more resource files be added to the project by using a ResourceFile element.


BuildHelp utility

Overview

BUILDHELP.EXE is a command line utility that can be used to create and build XLL+ help projects outside Visual Studio. It can therefore be used as part of an automated build process.

The utility can be found in the bin sub-directory of the XLL+ installation.

Usage

CopyC++
BUILDHELP options

Options

Option | Description
-s SourceFolder | Required. The full path to the directory containing the Visual Studio project.
-t ToolsFolder | Required. The full path to the directory containing the XLL+ help resources. This is usually the bin sub-directory of the XLL+ installation directory, e.g. C:\Program Files\Planatech\XllPlus\6.0\VS8.0\bin. The directory should contain two sub-directories, files and xsl.
-c HhcExe | Required. The full path of the HTML Help Compiler, HHC.EXE, e.g.: -h "C:\Program Files\HTML Help Workshop\hhc.exe".
-b TargetBuilds | Optional. The names of the build directories to which the compiled CHM file will be copied. Multiple names should be separated by semi-colons, e.g.: Debug;Release.
-i InputFile | Required. The name of a C++ source file that contains add-in functions. At least one -i option should be used. If multiple input files contain add-in functions that are to be to documented, then multiple -i options should be used. Note that all files should reside in the SourceFolder, and that arguments must be simply file names - they may not include paths.
-e ExtensionFile | Optional. The full path to an extension file used by the add-in functions, e.g.: -e "C:\Program Files\Planatech\XllPlus\6.0\VS8.0\Include\Extensions\StringPtrHandles.xpe". Each extension file used by the add-in functions must be supported by a separate -e option.
-l language | Optional. The language to be used by the add-in. Localized.xsl contains a list of the supported languages. This setting overrides Help/@Language in the help file.
-n boolean | Optional. If true, then no logo will be displayed. If false, the program version information will be written to standard output.
-m boolean | Optional. If true, no error will be returned if the help compiler, HHC.EXE, is missing. If false (the default) an error will occur if HHC.EXE is not found.
-h | Optional. Shows help. No other action takes place and the help project is not built.

Exit codes

Exit code | Description
0 | Program completed successfully.
1 | A command line argument contained an error.
2 | An error occurred while the program was running.

Example

In the example below, the line breaks are for readability only, and should not be used as part of the command.

BUILDHELP -s C:\Files\MyAddin -t "C:\Program Files\Planatech\XllPlus\6.0\VS8.0\bin"
-h "C:\Program Files\HTML Help Workshop\hhc.exe" -b Release
-i MyAddin.cpp -i MoreSourceCode.cpp
-e "C:\Program Files\Planatech\XllPlus\6.0\VS8.0\Include\Extensions\StringPtrHandles.xpe"

Further information

Generating help (User Guide)
Help Generator Reference


Ribbon Reference

The topics below contain reference information about the XLL+ implementation of the Office Ribbon.

Deploying add-ins that use the Office Ribbon
The requirements for deploying an add-in that uses the ribbon to a user's machine.
Ribbon Manager Configuration Utility
Manual page for the command-line tool, XlpRibbonReg.exe.
Adding ribbon support to a project
How to add ribbon support to a project created without a ribbon, or to a project created with older versions of XLL+
Ribbon callback functions (listed by name)
A complete list of all the callback functions that can be used as attributes for ribbon controls.
Ribbon RunTag actions
Details about the "RunTag" action callbacks, which call directl;y from the ribbon to an add-in macro function.

See Also

The Ribbon (User guide) | CXllApp::OnRibbonEvent


Deploying add-ins that use the Office Ribbon

Deliverable files

In order for an XLL add-in with a ribbon to work properly, the following files must be delivered to a user's machine:

  1. The XLL file.

  2. The XLL+ Ribbon Manager, XlpRibbonServer.dll.

  3. The XLL+ Ribbon Manager's configuration file, XlpRibbonServer.config. This must be delivered to the XlpRibbonServer data folder (see below).

Registering the XLL+ Ribbon Manager DLL

The ribbon manager must be registered as a COM module, which can be most easily done by running:

REGSVR32 XlpRibbonServer.dll

at the command line.

Ensure that you register the correct version of the DLL: on a machine with 64-bit Excel, you should register the 64-bit version of the file, which can be found in redist\x64, whereas on a machine with 32-bit Excel, you should register the 32-bit version of the file, which can be found in redist\win32.

The manager must additionally be registered as an Excel COM add-in. This can most easily be done by running the registration file XlpRibbonServer.reg on the target machine. XlpRibbonServer.reg can be found in the Redist\win32 or Redist\x64 folder of the XLL+ installation.

Adding an add-in to the list of XLLs supported by the XLL+ Ribbon Manager

The XLL must appear in the list of XLLs in the XLL+ Ribbon Manager's configuration file, XlpRibbonServer.config.

The configuration file must reside in the Planatech\XlpRibbonServer sub-folder of the user's local application data directory, e.g. (under Windows 7): C:\Users\My Name\AppData\Local\Planatech\XlpRibbonServer.

An <addin> element must be inserted within the <addins> element of the file. The location attribute must be set to the full path of the XLL file, e.g.:

CopyXML
<?xml version="1.0" encoding="utf-8"?>
<XlpRibbonServer>
  <addins>
    <addin location="C:\DeliveryFolder\MyAddin.xll" />
    <addin location="C:\AnotherFolder\AnotherAddin.xll" />
  </addins>
</XlpRibbonServer>

The Ribbon Manager Configuration utility, XlpRibbonReg.exe, can be used to perform the XLL registration. See Ribbon Manager Configuration utility in the reference for more information.

You can also use the Ribbon Manager command on the Tools menu of the XLL Add-ins window to open the file on the development computer.

See Also

Ribbon Reference


Ribbon Manager Configuration Utility

Overview

XLPRIBBONREG.EXE is a command line utility that can be used to add entries to the XLL+ Ribbon Manager's configuration file. It is used as part of the build process within Visual Studio. It can also be used outside Visual Studio, at the command line. It can therefore be used as part of an automated build process.

The utility searches the registry for the location of the XLL+ Ribbon Manager module, XlpRibbonServer.dll. If the module is not found (and the -c option is not specified) then the program fails.

The utility attempts to open the configuration file XlpRibbonServer.config. The configuration file must reside in the Planatech\XlpRibbonServer sub-folder of the user's local application data directory, e.g. (under Windows 7): C:\Users\My Name\AppData\Local\Planatech\XlpRibbonServer. If the file is not found, it is created.

If an <addin> element is found whose location attribute has the same file name as the XLL being registered, then the element is removed. Note that this check ignores the XLL's directory, and only compares file names. So for example, if a file C:\MyAddin\Release\MyAddin.xll is being registered, and a file C:\MyAddin\Debug\MyAddin.xll is found, the element referring to the debug version will be removed before the release version is registered.

An <addin> element is added to the file as a child of the <addins> element. The element's location attribute is set to the full path of the XLL being registered.

The utility can be found in the bin sub-directory of the XLL+ installation.

Usage

XLPRIBBONREG options

Options

Option | Description
-a XllPath | Required. XllPath must be the full path of the XLL to be registered. If the path contains spaces then the path should be surrounded with quotes.
-c ConfigFile | Optional. Full path and name of configuration file. If omitted, XlpRibbonServer.config in the Planatech\XlpRibbonServer sub-folder of the user's local application data directory will be used.
-i true/false | Optional. If true, ignore a missing file for XllPath. If false or omitted, a missing file will cause an error.
-q true/false | Optional. Sets quiet mode on or off. By default, quiet mode is off.
-h | Optional. Show help. Do not run the build.

Exit codes

Exit code | Description
0 | Program completed successfully.
1 | A command line argument contained an error.
2 | An error occurred while the program was running.

Example

XLPRIBBONREG -a C:\Files\MyAddin\Release\MyAddin.xll -q true
CopyXML
<?xml version="1.0" encoding="utf-8"?>
<XlpRibbonServer>
  <addins>
    <addin location="C:\Files\MyAddin\Release\MyAddin.xll" />
    <addin location="C:\AnotherFolder\AnotherAddin.xll" />
  </addins>
</XlpRibbonServer>

Requirements

Visual Studio version: 2005 or above
XLL+ version: 7.0 or above

See Also

Ribbon Reference | Adding ribbon support to a project


Adding ribbon support to a project

AppWizard

The easiest way to add ribbon support to an XLL+ project is to select ribbon support in the AppWizard when you first create the project. If you wish to add support later, or if you want to add a ribbon to a project created with older versions of XLL+, then follow the steps below.

Create a Ribbon file

In the steps below, the instructions are for an application named MyAddin. You should replace MyAddin with the name of your add-in where appropriate.

In Visual Studio, add a new XML file to the project and save it as MyAddin.RibbonX.

Replace the contents of the file with the XML below, and save the file.

CopyXML
<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
  <ribbon>
    <tabs>
      <!-- This tab element adds its child groups to the "Add-Ins" tab.     -->
      <!-- To create a new tab element specify the id and label attributes, -->
      <!-- and remove the idMso attribute.                                  -->
      <tab idMso="TabAddIns">
        <!-- This group element creates a new region on the tab specified by its parent element. -->
        <group id="MyAddin_Group" label="My Group"
               getVisible="GetVisible">
          <!-- This large button displays an image from the resources, whose ID is "LOGO", and a  fixed label.     -->
          <!-- When the button is pressed, the application class event handler function OnRibbonEvent() is called. -->
          <button id="MyAddin_PushButton"
                  size="large"
                  image="LOGO"
                  label="My Button"
                  onAction="OnActionButton" />
        </group>
      </tab>
    </tabs>
  </ribbon>
</customUI>

Next you need to embed the ribbon definition file as a resource, as follows:

  1. Open the project's resource file, MyAddin.rc.

  2. In Resource View, right-click MyAddin.rc and click Add resource....

  3. Click on the Import... button.

  4. In the file dialog, ensure that the Files of Type dropdown contains All Files (*.*) and select MyAddin.RibbonX.

  5. In the Custom Resource dialog, enter "XML" as the resource type. Note that the quotes are required. Press OK to add the ribbon to the resource file.

  6. In Resource View select the new resource, which will be under the "XML" node, and will have a name like IDR_XML1. Press Alt+Enter to view the resource properties.

  7. In the Properties Grid, change the ID to "RIBBONX". Once again, the quotes and the capitalization are required.

Adding an image

Image files should be in PNG format, and should usually have a transparent background.

Once you have created an image file, add it to the project and then follow the steps below to embed it as a resource.

  1. Open the project's resource file, e.g. MyAddin.rc.

  2. In Resource View, right-click MyAddin.rc and click Add resource....

  3. Click on the Import... button.

  4. In the file dialog, ensure that the Files of Type dropdown contains All Files (*.*) and select the PNG file.

  5. Under Visual Studio 2005, the Custom Resource dialog appears: enter RCDATA as the resource type. Note that there no quotes around RCDATA. Press OK to add the image to the resource file.

  6. In Resource View select the new resource. Under Visual Studio 2005 the resource will will be under the RCDATA node, and will have a name like IDR_RCDATA1. Under later versions of Visual Studio, the resource will will be under the PNG node and will have a name like IDB_PNG1. Press Alt+Enter to view the resource properties.

  7. In the Properties Grid, change the ID to the ID of the image, including quotes, e.g.: "LOGO". Note that the quotes are always required. The actual ID you use should correspond to the image ID you have used for the image attribute in the ribbon file.

Add code to the application header file

In the application header file, MyAddin.h, add the following line, before the start of the class declaration.

CopyC++
#include <xlpribbon.h>

Within the class definition, in a public section, add the following method declaration:

CopyC++
virtual CXlOper OnRibbonEvent(const CRibbonEvtParams& e);

Add code to the main source file

In the main source file, MyAddin.cpp, add the following lines to InitInstance(), after the call to AddStaticFns():

CopyC++
// Select a ribbon implementation, and then inform
// the framework that the add-in contains a ribbon
SetRibbonImplementation(RibbonImplementationShared);
SetHasRibbon(true);

Add an implementation of the ribbon event handler function, as follows:

CopyC++
CXlOper CMyAddinApp::OnRibbonEvent(const CRibbonEvtParams& e)
{
    CXlOper xloResult = CXllApp::OnRibbonEvent(e);
    switch (e.GetCallback())
    {
    case RIBBONCALLBACK_GETVISIBLE:
        if (e.GetId() == _T("MyAddin_Group"))
            xloResult = true;
        break;
    case RIBBONCALLBACK_ONACTION:
        if (e.GetId() == _T("MyAddin_PushButton"))
            XlMessageBox(_T("Hello from the ribbon!"), XlMessageBoxTypeInformation);
        break;
    }
    return xloResult;
}

Registering an add-in with the XLL+ Ribbon Manager

The final step to make the project function correctly in the development environment is to add a build event to the project:

  1. In the Project Explorer, right-click the project node and select Properties.

  2. In the Configuration combo-box, select All Configurations.

  3. In the Platform combo-box, select All Platforms.

  4. In the tree view on the left, select Configuration Properties/Build Events/Post-Build Event.

  5. In the property list on the right, set Command Line to the following:

    "$(Xlp80InstallDir7)bin\XlpRibbonReg.exe" -a "$(TargetPath)" -q true

    Note the quote marks, which are essential. Under Visual Studio 2005, use Xlp80InstallDir7 in the path, as shown above. Under Visual Studio 2008, use Xlp90InstallDir7 and under Visual Studio 2010, use Xlp100InstallDir7.

  6. In the property list, set Description to the following:

    Registering XLL with Ribbon Manager...

  7. In the property list, ensure that Excluded From Build is set to No.

See Also

Ribbon Reference | Ribbon Manager Configuration Utility


Callback functions (listed by name)

Alphabetical list of ribbon callback functions

The table below contains all the ribbon control callbacks supported by the XLL+ run-time library. Using any other value for a callback attribute will result in a run-time error.

For information about the parameters passed to each callback, and the return value that is expected, see CXllApp::OnRibbonEvent.

Attribute | Callback | Applies to
getContent | GetContent | dynamicMenu
getDescription | GetDescription | button checkBox dynamicMenu gallery menu toggleButton
getEnabled | GetEnabled | button checkBox comboBox dropDown dynamicMenu editBox gallery labelControl menu splitButton toggleButton
getImage | GetImage | group button comboBox dropDown dynamicMenu editBox gallery menu toggleButton
getImageMso | GetImageMso | group button comboBox dropDown dynamicMenu editBox gallery menu toggleButton
getItemCount | GetItemCount | comboBox dropDown gallery
getItemHeight | GetItemHeight | gallery
getItemID | GetItemID | comboBox dropDown gallery
getItemImage | GetItemImage | comboBox dropDown gallery
getItemLabel | GetItemLabel | comboBox dropDown gallery
getItemScreentip | GetItemScreentip | comboBox dropDown gallery
getItemSupertip | GetItemSupertip | comboBox dropDown gallery
getItemWidth | GetItemWidth | gallery
getKeytip | GetKeytip | tab group button checkBox comboBox dropDown dynamicMenu editBox gallery menu splitButton toggleButton
getLabel | GetLabel | tab group button checkBox comboBox dropDown dynamicMenu editBox gallery labelControl menu splitButton toggleButton
getPressed | GetPressed | checkBox toggleButton
getScreentip | GetScreentip | group button checkBox comboBox dropDown dynamicMenu editBox gallery labelControl menu toggleButton
getSelectedItemID | GetSelectedItemID | dropDown gallery
getSelectedItemIndex | GetSelectedItemIndex | dropDown gallery
getShowImage | GetShowImage | button comboBox dropDown dynamicMenu editBox gallery menu toggleButton
getShowLabel | GetShowLabel | button comboBox dropDown dynamicMenu editBox gallery labelControl menu splitButton toggleButton
getSize | GetSize | button dynamicMenu gallery menu splitButton toggleButton
getSupertip | GetSupertip | group button checkBox comboBox dropDown dynamicMenu editBox gallery labelControl menu separator splitButton toggleButton
getText | GetText | comboBox editBox
getTitle | GetTitle | menuSeparator
getVisible | GetVisible | tab group box button buttonGroup checkBox comboBox dropDown dynamicMenu editBox gallery labelControl menu separator splitButton toggleButton
loadImage | LoadImage | customUI
onAction | OnActionButton | button
 | OnActionButtonRunTag | button
 | OnActionIndexed | dropDown gallery
 | OnActionIndexedRunTag | dropDown gallery
 | OnActionToggleButton | checkBox toggleButton
 | OnActionToggleButtonRunTag | checkBox toggleButton
onChange | OnChange | comboBox editBox
onLoad | OnLoad | customUI

See Also

Ribbon Reference | CXllApp::OnRibbonEvent | The Ribbon (User guide)


Ribbon RunTag actions

RunTag action callbacks

The table below lists the RunTag action callbacks which can be used to trigger a macro from a ribbon control. See Supporting earlier Excel versions for more information about RunTag action callbacks.

Control | OnAction callback | Parameters
button | OnActionButtonRunTag |
dropDown, gallery | OnActionIndexedRunTag | index, selectedItemId
checkBox, toggleButton | OnActionToggleButtonRunTag | pressed

Macro substitution

You can pass event information within the macro by using % symbols within the tag. The table below lists the event information that can be inserted, along with the method of CRibbonEvtParams that returns the equivalent information.

Symbol | Value | CRibbonEvtParams method
%c | Control ID | GetId
%i | Item ID | GetSelectedId
%n | Item index | GetIndex
%p | Pressed | GetPressed

Note that you can use multiple substitutions within a single tag.

Examples

The ribbon group defined below demonstrates the use of various macro substitutions. Note the use of single quotes for some of the tag attribute values; this allows us to put double-quotes around the string arguments.

CopyXML
<group id="TagGroup" label="RunTag callbacks">
  <buttonGroup id="StyleGroup">
    <button id="SG_Left" imageMso="AlignLeft" label="Left"
            onAction="OnActionButtonRunTag" tag='SetStyle("%c")'/>
    <button id="SG_Center" imageMso="AlignCenter" label="Center"
            onAction="OnActionButtonRunTag" tag='SetStyle("%c")'/>
    <button id="SG_Right" imageMso="AlignRight" label="Right"
            onAction="OnActionButtonRunTag" tag='SetStyle("%c")'/>
  </buttonGroup>
  <dropDown id="MyDropDown" label="DropDown"
            onAction="OnActionIndexedRunTag" tag='SetStyle("%i")'>
    <item id="Item0" label="Left" imageMso="AlignLeft"/>
    <item id="Item1" label="Center" imageMso="AlignCenter"/>
    <item id="Item2" label="Right" imageMso="AlignRight"/>
  </dropDown>
  <separator id="Separator1" />
  <toggleButton id="Toggle" label="Toggle" imageMso="Bold" size="large"
                onAction="OnActionToggleButtonRunTag" tag="SetBold(%p)"/>
</group>

The table below lists the actual macros that will be invoked:

Control | Item/State | Macro
SG_Left |  | SetStyle("SG_Left")
SG_Center |  | SetStyle("SG_Center")
SG_Right |  | SetStyle("SG_Right")
MyDropDown | Item0 | SetStyle("Item0")
MyDropDown | Item1 | SetStyle("Item1")
MyDropDown | Item2 | SetStyle("Item2")
Toggle | Pressed | SetBold(TRUE)
Toggle | Not pressed | SetBold(FALSE)


XnReflect utility

Overview

XNREFLECT.EXE is a command line utility that can be used to generate C++ code for XLL add-in functions from .NET assemblies. It is used as part of the build process within Visual Studio. It can also be used outside Visual Studio, at the command line. It can therefore be used as part of an automated build process.

The utility can be found in the bin sub-directory of the XLL+ installation.

Usage

XNREFLECT options

Options

Option | Description
-t SettingsFile | Optional. Full name of template settings file.
-i InputFile [DocFile] | Required (at least 1). File name (including path) of .NET assembly. DocFile is optional. If provided, it should be the file name (including path) of a .NET compiled comment file. If omitted, a file with an xml extension in the same directory as InputFile will be used.
-o OutputFile | Optional. Full path of output file.
-a true or false | Optional. If false, no header will be written to output file.
-d DefaultsFile | Optional. Full path of file containing FunctionModel defaults.
-v OverridesFile | Optional. Full path of file containing attribute overrides.
-n boolean | Optional. If true, no logo will be displayed. If false or omitted, the program version information will be written to standard output.
-c ControlFile | Optional. Contents of control file will be read as options. Note that paths in control file may be relative (to control file). Control file should be in .ini file format.
-x ControlFile | Optional. Contents of control file will be read as options. Note that paths in control file may be relative (to control file). Control file should be in XML file format.
-f Configuration | Optional. Ignore portions of control file that are not in the section for the named Configuration. Ignored without -c or -x.
-p ExtensionsPath | Optional. List of directories, semi-colon separated, which will be searched for extension files.
-h | Optional. Shows help. No other action takes place and the help project is not built.

Exit codes

Exit code | Description
0 | Program completed successfully.
1 | A command line argument contained an error.
2 | An error occurred while the program was running.

Control files

If a control file is provided, using either -c or -x, then the options contained in it will override any other options on the command line.

Example

XNREFLECT -x C:\Files\MyAddin\MyLib.import.xml -f Debug

Further information

Importing .NET Assemblies

Requirements

Visual Studio version: 2005 or above
XLL+ version: 6.2 or above


XlpGen utility

Overview

XLPGEN.EXE is a command line utility that can be used to generate C++ code for XLL add-in functions from XML files containing function definitions. It can be used as part of an automated build process.

The utility can be found in the bin sub-directory of the XLL+ installation.

Usage

XLPGEN options

Options

Option | Description
-i InputFile | Required. File name (including path) of XML file.
-t SettingsFile | Optional. Full name of template settings file.
-o OutputFile | Optional. Full path of output file. If omitted, the output will be directed to standard output.
-d TargetDirectory | Optional. The directory to which output file will be written. Ignored if -o is used and is rooted, or if -o is not used. The default value is the directory containing InputFile. If present and not rooted, it will be treated as relative to directory containing InputFile.
-c HeaderFile | Optional. The specified header file will be added to the head of the output file in a #include statement, surrounded by quotes, e.g. #include "myfile.h". Multiple header files can be specified, separated by semi-colons.
-g HeaderFile | Optional. The specified header file will be added to the head of the output file in a #include statement, surrounded by angle brackets, e.g. #include <myfile.h>. Multiple header files can be specified, separated by semi-colons.
-e ExtensionFile | Optional. The full path to an extension file used by the add-in functions, e.g.: -e "C:\Program Files\Planatech\XllPlus\6.0\VS8.0\Include\Extensions\StringPtrHandles.xpe". Each extension file used by the add-in functions must be supported by a separate -e option.
-a true or false | Optional. If false, no header will be written to output file.
-n true or false | Optional. If true, no logo will be displayed. If false or omitted, the program version information will be written to standard output.
-h | Optional. Shows help. No other action takes place and the C++ code file is not generated.

Exit codes

Exit code | Description
0 | Program completed successfully.
1 | A command line argument contained an error.
2 | An error occurred while the program was running.

Example

XLPGEN -i C:\Files\MyAddin\MyLib.xml -o MyLib_gen.cpp

See also the code and the project's custom tool settings in the XlpGenDemo sample project.

Input format

The input file contains definitions of function signatures in the standard export format, and can also optionally contain the code that will be inserted into the generated functions.

  • XLL+ Function Schema contains the full schema for input files.
  • The Export to XML can be used to convert the signatures of existing C++ add-in functions to the same XML format.

The XML code below contains a complete function, including the code that will be inserted into the generated add-in function.

CopyXML
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Functions>
    <XlFunction Flags="HideInFormulaWizard DoNotCatchStructuredExceptions"
                ExportedName="MyAdd" Category="14" Description="Adds two numbers"
                SourceFile="C:\Source\XlpGenDemo\XlpGenDemo.cpp" SourceLine="90"
                CategoryForLocale="User Defined" CategoryUSEnglish="User Defined"
                SafeName="MyAdd">
      <Arguments>
        <XlArgument Name="x" Description="is a number">
          <Signature Type="Double">
            <Bounds />
            <ExtendedParameters />
          </Signature>
        </XlArgument>
        <XlArgument Name="y" Description="is a number">
          <Signature Type="Double">
            <Bounds />
            <ExtendedParameters />
          </Signature>
        </XlArgument>
      </Arguments>
      <Extensions />
      <Enums />
    </XlFunction>
  </Functions>
  <CodeBodies>
    <CodeBody ExportedName="MyAdd">
      <InsertedCode>    xloResult = x + y;</InsertedCode>
    </CodeBody>
  </CodeBodies>
</Project>

Notice that there are two sections within the main Project element: Functions contains the definitions of the function signatures and CodeBodies contains the actual code that will be inserted within the generated function. The two parts are paired together by their matching ExportedName attribute.

Hint: If you need to see how the XML for a particular feature is expressed, and you cannot find sufficient detail in the schema, you should use the XLL+ Function Wizard to set up a function's signature and features and then use the Export to XML command and inspect the resulting XML.

Generated code

In this case the following code (or something similar) will be generated:

CopyC++
// Generated by XlpGen tool at 21/01/2013 4:32:05 PM.
#ifdef XLL_LIB_MFC
#include "stdafx.h"
#endif
#include <xllplus.h>

// Function:    MyAdd
// Purpose:     Adds two numbers

//{{XLP_SRC(MyAdd)
    // NOTE - the FunctionWizard will add and remove mapping code here.
    //    DO NOT EDIT what you see in these blocks of generated code!

#pragma region MyAdd support code
IMPLEMENT_XLLFN4(MyAdd, MyAdd_4, MyAdd_12, "RBB", "UBB", L"MyAdd", 0, L"x,y", 0,
    L"14", 0, L"Adds two numbers", 0, L"is a number\0is a number\0", 0, 0,
    L"{MyAdd,,,Adds two numbers,14,1,258,U,{{0,{x,Double,0,,is a number,,,,}},"
    L"{0,{y,Double,0,,is a number,,,,}}},{},3,,0,0,,,,0,0}", 1, 0, 0)
CXlOper* MyAdd_Impl(CXlOper&, double, double);
extern "C" __declspec(dllexport)
LPXLOPER12 MyAdd_12(double x, double y)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    if (CXllApp::IsInFormulaWizard())
    {
        xloResult = xlerrNA;
        return xloResult.Ret12();
    }
    try {
        xloResult.HandleResult(MyAdd_Impl(xloResult, x, y));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret12();
}
extern "C" __declspec(dllexport)
LPXLOPER4 MyAdd_4(double x, double y)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
    if (CXllApp::IsInFormulaWizard())
    {
        xloResult = xlerrNA;
        return xloResult.Ret4();
    }
    try {
        xloResult.HandleResult(MyAdd_Impl(xloResult, x, y));
    }
    catch(const CXlRuntimeException& ex) {
        CXllApp::Instance()->DisplayException(xloResult, ex);
    }
    XLP_CATCH_CLR_EXCEPTIONS_TO(xloResult)
    return xloResult.Ret4();
}

#pragma endregion

CXlOper* MyAdd_Impl(CXlOper& xloResult, double x, double y)
{

    xloResult = x + y;
    return xloResult.Ret();
}
    // End of generated code
//}}XLP_SRC

The first few lines of the generated code contain header information, which is included once only at the top of an output file. The source for this code can be found in the header template, XlpGen_Header.tpl. Note that any additional header files which are specified on the command line (using the -c or -p options) will be included here.

The header lines are followed by the code for each function. Notice that the code from the matching CodeBody element is inserted into the body of the implementation function (MyAdd_Impl).

Requirements

Visual Studio version: 2005 or above
XLL+ version: 7.0.4 or above


.NET Runtime Libraries

The XLL+ .NET Runtime library namespaces are listed below.

XllPlus Namespace
The XllPlus namespace contains attributes and associated classes which are used by the XLL+ Reflector when it exports .NET methods and properties as Excel add-in functions.


XllPlus Namespace

[image]

XLL+ .NET Runtime Class Library
XllPlus Namespace
Send Feedback
The XllPlus namespace contains attributes and associated classes which are used by the XLL+ Reflector when it exports .NET methods and properties as Excel add-in functions.

Classes

Class | Description
XllArgumentAttribute | Controls the export and marshalling of a single argument of an exported Excel add-in function.
XllAssemblyExportAttribute | Controls the export of the methods and properties in an entire assembly.
XllAttributeOverrides | A collection of overrides for exporting reflected members from an Assembly. XllAttributeOverrides contains a map connecting zero or more reflected members and a set of override attributes each held in a XllAttributes object.
XllAttributeOverrides..::.Pair | Internal class used during serialization.
XllAttributes | Holds a complete set of XLL export attributes for a member.
XllClassExportAttribute | Controls the export of a class' methods and properties as Excel add-in functions.
XllFunctionAttribute | Controls the export of a specific method or property as an Excel add-in function.
XllIgnoreAttribute | Prevents a method or property from being exported.
XllMacroAttribute | Declares a method to be available as a command macro in Excel.

Enumerations

Enumeration | Description
TriValue | A boolean value which can also take the value Default, in which case the value is inherited from a parent object (if any) or from a system default.
XlArgumentFlags | Flag values governing the behavior of an argument during conversion from Excel form to C++ form.
XlCategory | Describes the built-in function catageries which appear in the Excel Formula Wizard.
XlExportFilter | Defines which class members are exported to Excel by default
XlFunctionAvailability | Describes the availability of an add-in function within Excel.
XlFunctionFlags | Flags controlling the behaviour of an add-in function, including its signature flags (Volatile, ThreadSafe, DeferRecal) and its UI behavior (HideInFormulaWizard), as well as code generation effects (UsesApplicationData, CanFail).
XlVersions | Describes the versions for which code will be specifically generated.


TriValue Enumeration

[image]

XLL+ .NET Runtime Class Library
TriValue Enumeration
See Also Send Feedback
A boolean value which can also take the value Default, in which case the value is inherited from a parent object (if any) or from a system default.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public enum TriValue
Visual Basic (Declaration)
Public Enumeration TriValue
Visual C++
public enum class TriValue

Members

Member name | Description
False | Always false.
True | Always true.
Default | Unspecified. Value is derived from a parent object or a system default.

See Also

XllPlus Namespace


XlArgumentFlags Enumeration

[image]

XLL+ .NET Runtime Class Library
XlArgumentFlags Enumeration
See Also Send Feedback
Flag values governing the behavior of an argument during conversion from Excel form to C++ form.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
[FlagsAttribute]
public enum XlArgumentFlags
Visual Basic (Declaration)
<FlagsAttribute> _
Public Enumeration XlArgumentFlags
Visual C++
[FlagsAttribute]
public enum class XlArgumentFlags

Members

Member name | Description
None | No flags specified.
Optional | Argument is optional. If omitted, empty or blank, a default value will be supplied. The values of NilToDefault, NonNumericToDefault and BlankToDefault further control the behavior of empty or blank cells respectively.
BlankToDefault | Blank cells are treated as missing
NonNumericToDefault | Convert non-numeric cells to the default value
ZeroToDefault | Convert zero values to the default value
TruncateOnNil | Array is truncated at first empty cell. If FillUsedArea is used, array is truncated at last empty cell, searching backwards.
TruncateOnBlank | Array is truncated at first blank cell. If FillUsedArea is used, array is truncated at last blank cell, searching backwards.
TruncateOnZero | Array is truncated at first zero cell. If FillUsedArea is used, array is truncated at last zero cell, searching backwards.
TruncateOnNonNumeric | Array is truncated at first non-numeric cell. If FillUsedArea is used, array is truncated at last non-numeric cell, searching backwards.
VectorIsRow | Vector argument must be a row
VectorIsColumn | Vector argument must be a column
FillUsedArea | Fill the missing cells in the non-truncated area with the default cell value.
FillAll | Fill all missing cells with the default cell value.
TransposeMatrix | Transpose the rows and columns of the matrix.
FlatMatrixStorage | Store matrix data in a continuous, "flat", form. The default is a vector of pointers to uniform vectors.
RejectNullArray | Fail if an array is empty after truncation.
UpperBoundInner | Ignored
UpperBoundAuto | Ignored
CellEmptyToDefault | If a Fill flag is specified, convert empty cells to the default cell value.
CellBlankToDefault | If a Fill flag is specified, convert blank cells to the default cell value.
CellZeroToDefault | If a Fill flag is specified, convert zero cells to the default cell value.
CellNonNumericToDefault | If a Fill flag is specified, convert non-numeric cells to the default cell value.
IgnoreValidation | Do not filter flag values during validation.
CoreFlagFilter | Flags excluded by this filter will not be passed on to the XLL+ function model. They may be used by the reflector.
ValueListIsExclusive | If true, then any input value that is not in the value list will be rejected at run-time.
ShowValueListInFormulaWizard | If true, then the value list will be displayed in a drop-down list in the Excel Formula Wizard.

See Also

XllPlus Namespace


XlCategory Enumeration

[image]

XLL+ .NET Runtime Class Library
XlCategory Enumeration
See Also Send Feedback
Describes the built-in function catageries which appear in the Excel Formula Wizard.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public enum XlCategory
Visual Basic (Declaration)
Public Enumeration XlCategory
Visual C++
public enum class XlCategory

Members

Member name | Description
Default | The default setting, as specified in an assembly or class attribute.
Financial | Financial functions
DateAndTime | Date & time functions
MathAndTrig | Mathematics & trigonometry functions
Statistical | Statistical functions
LookupAndReference | Lookup & reference functions
Database | Database functions
Text | Text functions
Logical | Logical functions
Information | Infomation functions
Commands | Commands, available from menus, toolbars and macros.
Customizing | Customizing commands (not recommended)
MacroControl | Macro control functions (not recommended)
DdeExternal | External data functions, inluding dynamic data exchange functions.
UserDefined | User defined functions

See Also

XllPlus Namespace


XlExportFilter Enumeration

[image]

XLL+ .NET Runtime Class Library
XlExportFilter Enumeration
See Also Send Feedback
Defines which class members are exported to Excel by default

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
[FlagsAttribute]
public enum XlExportFilter
Visual Basic (Declaration)
<FlagsAttribute> _
Public Enumeration XlExportFilter
Visual C++
[FlagsAttribute]
public enum class XlExportFilter

Members

Member name | Description
None | No methods or properties are automatically exported
StaticMethods | Static methods are automatically exported
StaticProperties | Static properties are automatically exported
InstanceMethods | Object methods are automatically exported
InstanceProperties | Object properties are automatically exported
Default | For a Type, the setting is inherited from the Assembly settings. For an Assembly, the setting is the same as None.

See Also

XllPlus Namespace


XlFunctionAvailability Enumeration

[image]

XLL+ .NET Runtime Class Library
XlFunctionAvailability Enumeration
See Also Send Feedback
Describes the availability of an add-in function within Excel.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public enum XlFunctionAvailability
Visual Basic (Declaration)
Public Enumeration XlFunctionAvailability
Visual C++
public enum class XlFunctionAvailability

Members

Member name | Description
Hidden | The function is available from worksheets or from macros, but it does not appear in the Excel Formula Wizard.
Worksheet | The function is available from worksheets or from macros, and appears in the Excel Formula Wizard.
Macro | The function is only available from a macro command, and does not appear in the Excel Formula Wizard.
Default | The default settting: Worksheet for properties and for methods which return a value; Macro for methods which have a void return type.

See Also

XllPlus Namespace


XlFunctionFlags Enumeration

[image]

XLL+ .NET Runtime Class Library
XlFunctionFlags Enumeration
See Also Send Feedback
Flags controlling the behaviour of an add-in function, including its signature flags (Volatile, ThreadSafe, DeferRecal) and its UI behavior (HideInFormulaWizard), as well as code generation effects (UsesApplicationData, CanFail).

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
[FlagsAttribute]
public enum XlFunctionFlags
Visual Basic (Declaration)
<FlagsAttribute> _
Public Enumeration XlFunctionFlags
Visual C++
[FlagsAttribute]
public enum class XlFunctionFlags

Members

Member name | Description
None | No flags are applied. The behavior of the function will be normal.
ThreadSafe | If true, then the symbol "$" is appended to the signature. Ignored under XL4.
DoNotCallInFormulaWizard | If true, then the function will return early if called from the Excel Formula Wizard, and will always return a value of #VALUE!.
UsesApplicationData | If true, then the function uses application-level data. (Deprecated.)
Volatile | Specifies whether the function is volatile, and will therefore be recalculated every time any cell in the same sheet is calculated
DeferRecalc | Specifies whether the function can defer recalculation
CanFail | If this flag is true, then the execution of the function can fail. This is entirely separate from the issue of whether input processing can fail. If the flag is true, then the return type of the function is constrained to be Reference, so that it can return an error instead of a value.
CacheResults | Specifies whether the function's results should be cached, to improve performance of expensive calculations.
ArgumentValueHasPrefix | If this flag is true, then the Oper input's name will be the name of the argument, and the calculated value's name will be "val" + the name of the argument. If it is false, then the Oper input's name will be the name of the argument followed by "_oper", and the calculated value's name will be just the name of the argument. Old-style functions that have been upgraded will have this flag set. By default, it is off.
DoNotCatchStructuredExceptions | If this flag is true, then the SEH instance will not be inserted into the wrapper functions. By default, is is off.
CreateAsyncVersion | Specifies that an asynchronous version of the function should also be created.
CoreFlagFilter | Flags excluded by this filter will not be passed on to the XLL+ function model. They may be used by the reflector.

See Also

XllPlus Namespace


XllArgumentAttribute Class

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute Class
Members See Also Send Feedback
Controls the export and marshalling of a single argument of an exported Excel add-in function.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public class XllArgumentAttribute : Attribute,
    IComparable, ICloneable
Visual Basic (Declaration)
Public Class XllArgumentAttribute _
    Inherits Attribute _
    Implements IComparable, ICloneable
Visual C++
public ref class XllArgumentAttribute : public Attribute,
    IComparable, ICloneable

Inheritance Hierarchy

System..::.Object
System..::.Attribute
XllPlus..::.XllArgumentAttribute

See Also

XllArgumentAttribute Members
XllPlus Namespace


XllArgumentAttribute Members

[image] [image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute Members
XllArgumentAttribute Class Constructors Methods Properties See Also Send Feedback

The XllArgumentAttribute type exposes the following members.

Constructors

Name | Description
XllArgumentAttribute | Overloaded.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.
Compare | Compares two XllArgumentAttribute instances.
CompareTo | Compares two XllArgumentAttribute instances.
IsDefault | Returns whether the attribute's properties are all set to default values.

Properties

Name | Description
DefaultValue | The default value for the argument, which will be used if the user omits the argument. Ignored if Flags does not contain Optional.
Description | Help text for the argument. This will appear in the Excel Formula Wizard.
ExportedName | The name of the argument as it will appear in Excel.
Flags | A set of flags controlling the behavior and appearance of the argument in Excel.
Handle | Controls whether the argument must be passed as a handle, rather than as a value.
IsIterable | Ignored.
NameToUpperCase | Sets whether the exported name is forced to upper case.
Tag | A string value which will be passed to the code generator. (Internal use.)
ValueList | A list of the values of which the argument's value may or must be a member. Items in the list are separated by semi-colons. Each item is a value+description pair, separated by a comma. e.g. 1,One;2,Two;3,Three.

See Also

XllArgumentAttribute Class
XllPlus Namespace


XllArgumentAttribute Constructor

[image] [image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute Constructor
XllArgumentAttribute Class See Also Send Feedback

Overload List

Name | Description
XllArgumentAttribute()()() | Creates a new XllArgumentAttribute object.
XllArgumentAttribute(String) | Creates a new XllArgumentAttribute object.
XllArgumentAttribute(XlArgumentFlags) | Creates a new XllArgumentAttribute object.
XllArgumentAttribute(String, XlArgumentFlags) | Creates a new XllArgumentAttribute object.
XllArgumentAttribute(String, XlArgumentFlags, String) | Creates a new XllArgumentAttribute object.

See Also

XllArgumentAttribute Class
XllArgumentAttribute Members
XllPlus Namespace


XllArgumentAttribute Constructor

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute Constructor
XllArgumentAttribute Class See Also Send Feedback
Creates a new XllArgumentAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllArgumentAttribute()
Visual Basic (Declaration)
Public Sub New
Visual C++
public:
XllArgumentAttribute()

See Also

XllArgumentAttribute Class
XllArgumentAttribute Overload
XllPlus Namespace


XllArgumentAttribute Constructor (String)

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute Constructor (String)
XllArgumentAttribute Class See Also Send Feedback
Creates a new XllArgumentAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllArgumentAttribute(
    string exportedName
)
Visual Basic (Declaration)
Public Sub New ( _
    exportedName As String _
)
Visual C++
public:
XllArgumentAttribute(
    String^ exportedName
)

Parameters

exportedName
Type: System..::.String
The name of the argument as it will appear in Excel.

See Also

XllArgumentAttribute Class
XllArgumentAttribute Overload
XllPlus Namespace


XllArgumentAttribute Constructor (XlArgumentFlags)

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute Constructor (XlArgumentFlags)
XllArgumentAttribute Class See Also Send Feedback
Creates a new XllArgumentAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllArgumentAttribute(
    XlArgumentFlags flags
)
Visual Basic (Declaration)
Public Sub New ( _
    flags As XlArgumentFlags _
)
Visual C++
public:
XllArgumentAttribute(
    XlArgumentFlags flags
)

Parameters

flags
Type: XllPlus..::.XlArgumentFlags
A set of flags controlling the behavior and appearance of the argument in Excel.

See Also

XllArgumentAttribute Class
XllArgumentAttribute Overload
XllPlus Namespace


XllArgumentAttribute Constructor (String, XlArgumentFlags)

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute Constructor (String, XlArgumentFlags)
XllArgumentAttribute Class See Also Send Feedback
Creates a new XllArgumentAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllArgumentAttribute(
    string exportedName,
    XlArgumentFlags flags
)
Visual Basic (Declaration)
Public Sub New ( _
    exportedName As String, _
    flags As XlArgumentFlags _
)
Visual C++
public:
XllArgumentAttribute(
    String^ exportedName,
    XlArgumentFlags flags
)

Parameters

exportedName
Type: System..::.String
The name of the argument as it will appear in Excel.
flags
Type: XllPlus..::.XlArgumentFlags
A set of flags controlling the behavior and appearance of the argument in Excel.

See Also

XllArgumentAttribute Class
XllArgumentAttribute Overload
XllPlus Namespace


XllArgumentAttribute Constructor (String, XlArgumentFlags, String)

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute Constructor (String, XlArgumentFlags, String)
XllArgumentAttribute Class See Also Send Feedback
Creates a new XllArgumentAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllArgumentAttribute(
    string exportedName,
    XlArgumentFlags flags,
    string description
)
Visual Basic (Declaration)
Public Sub New ( _
    exportedName As String, _
    flags As XlArgumentFlags, _
    description As String _
)
Visual C++
public:
XllArgumentAttribute(
    String^ exportedName,
    XlArgumentFlags flags,
    String^ description
)

Parameters

exportedName
Type: System..::.String
The name of the argument as it will appear in Excel.
flags
Type: XllPlus..::.XlArgumentFlags
A set of flags controlling the behavior and appearance of the argument in Excel.
description
Type: System..::.String
Help text for the argument. This will appear in the Excel Formula Wizard.

See Also

XllArgumentAttribute Class
XllArgumentAttribute Overload
XllPlus Namespace


XllArgumentAttribute Methods

[image] [image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute Methods
XllArgumentAttribute Class See Also Send Feedback

The XllArgumentAttribute type exposes the following members.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.
Compare | Compares two XllArgumentAttribute instances.
CompareTo | Compares two XllArgumentAttribute instances.
IsDefault | Returns whether the attribute's properties are all set to default values.

See Also

XllArgumentAttribute Class
XllPlus Namespace


Clone Method

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute..::.Clone Method
XllArgumentAttribute Class See Also Send Feedback
Returns a deep copy of the current instance.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public Object Clone()
Visual Basic (Declaration)
Public Function Clone As Object
Visual C++
public:
virtual Object^ Clone() sealed

Return Value

A new XllArgumentAttribute object, whose properties are all equal in value to this.

Implements

ICloneable..::.Clone()()()

See Also

XllArgumentAttribute Class
XllPlus Namespace


Compare Method

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute..::.Compare Method
XllArgumentAttribute Class See Also Send Feedback
Compares two XllArgumentAttribute instances.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public int Compare(
    XllArgumentAttribute other
)
Visual Basic (Declaration)
Public Function Compare ( _
    other As XllArgumentAttribute _
) As Integer
Visual C++
public:
int Compare(
    XllArgumentAttribute^ other
)

Parameters

other
Type: XllPlus..::.XllArgumentAttribute
A second instance to be compared to this.

Return Value

-1 if this is less than other. 0 if the two are equal. 1 if this is greater than other.

See Also

XllArgumentAttribute Class
XllPlus Namespace


CompareTo Method

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute..::.CompareTo Method
XllArgumentAttribute Class See Also Send Feedback
Compares two XllArgumentAttribute instances.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public int CompareTo(
    Object other
)
Visual Basic (Declaration)
Public Function CompareTo ( _
    other As Object _
) As Integer
Visual C++
public:
virtual int CompareTo(
    Object^ other
) sealed

Parameters

other
Type: System..::.Object
A second instance to be compared to this.

Return Value

-1 if this is less than other. 0 if the two are equal. 1 if this is greater than other.

Implements

IComparable..::.CompareTo(Object)

See Also

XllArgumentAttribute Class
XllPlus Namespace


IsDefault Method

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute..::.IsDefault Method
XllArgumentAttribute Class See Also Send Feedback
Returns whether the attribute's properties are all set to default values.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public bool IsDefault()
Visual Basic (Declaration)
Public Function IsDefault As Boolean
Visual C++
public:
bool IsDefault()

Return Value

True if all properties are at their default values. False if any property has a non-default value.

See Also

XllArgumentAttribute Class
XllPlus Namespace


XllArgumentAttribute Properties

[image] [image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute Properties
XllArgumentAttribute Class See Also Send Feedback

The XllArgumentAttribute type exposes the following members.

Properties

Name | Description
DefaultValue | The default value for the argument, which will be used if the user omits the argument. Ignored if Flags does not contain Optional.
Description | Help text for the argument. This will appear in the Excel Formula Wizard.
ExportedName | The name of the argument as it will appear in Excel.
Flags | A set of flags controlling the behavior and appearance of the argument in Excel.
Handle | Controls whether the argument must be passed as a handle, rather than as a value.
IsIterable | Ignored.
NameToUpperCase | Sets whether the exported name is forced to upper case.
Tag | A string value which will be passed to the code generator. (Internal use.)
ValueList | A list of the values of which the argument's value may or must be a member. Items in the list are separated by semi-colons. Each item is a value+description pair, separated by a comma. e.g. 1,One;2,Two;3,Three.

See Also

XllArgumentAttribute Class
XllPlus Namespace


DefaultValue Property

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute..::.DefaultValue Property
XllArgumentAttribute Class See Also Send Feedback
The default value for the argument, which will be used if the user omits the argument. Ignored if Flags does not contain Optional.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string DefaultValue { get; set; }
Visual Basic (Declaration)
Public Property DefaultValue As String
Visual C++
public:
property String^ DefaultValue {
    String^ get ();
    void set (String^ value);
}

See Also

XllArgumentAttribute Class
XllPlus Namespace


Description Property

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute..::.Description Property
XllArgumentAttribute Class See Also Send Feedback
Help text for the argument. This will appear in the Excel Formula Wizard.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string Description { get; set; }
Visual Basic (Declaration)
Public Property Description As String
Visual C++
public:
property String^ Description {
    String^ get ();
    void set (String^ value);
}

See Also

XllArgumentAttribute Class
XllPlus Namespace


ExportedName Property

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute..::.ExportedName Property
XllArgumentAttribute Class See Also Send Feedback
The name of the argument as it will appear in Excel.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string ExportedName { get; set; }
Visual Basic (Declaration)
Public Property ExportedName As String
Visual C++
public:
property String^ ExportedName {
    String^ get ();
    void set (String^ value);
}

See Also

XllArgumentAttribute Class
XllPlus Namespace


Flags Property

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute..::.Flags Property
XllArgumentAttribute Class See Also Send Feedback
A set of flags controlling the behavior and appearance of the argument in Excel.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XlArgumentFlags Flags { get; set; }
Visual Basic (Declaration)
Public Property Flags As XlArgumentFlags
Visual C++
public:
property XlArgumentFlags Flags {
    XlArgumentFlags get ();
    void set (XlArgumentFlags value);
}

See Also

XllArgumentAttribute Class
XllPlus Namespace


Handle Property

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute..::.Handle Property
XllArgumentAttribute Class See Also Send Feedback
Controls whether the argument must be passed as a handle, rather than as a value.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public TriValue Handle { get; set; }
Visual Basic (Declaration)
Public Property Handle As TriValue
Visual C++
public:
property TriValue Handle {
    TriValue get ();
    void set (TriValue value);
}

See Also

XllArgumentAttribute Class
XllPlus Namespace


IsIterable Property

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute..::.IsIterable Property
XllArgumentAttribute Class See Also Send Feedback
Ignored.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public bool IsIterable { get; set; }
Visual Basic (Declaration)
Public Property IsIterable As Boolean
Visual C++
public:
property bool IsIterable {
    bool get ();
    void set (bool value);
}

See Also

XllArgumentAttribute Class
XllPlus Namespace


NameToUpperCase Property

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute..::.NameToUpperCase Property
XllArgumentAttribute Class See Also Send Feedback
Sets whether the exported name is forced to upper case.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public TriValue NameToUpperCase { get; set; }
Visual Basic (Declaration)
Public Property NameToUpperCase As TriValue
Visual C++
public:
property TriValue NameToUpperCase {
    TriValue get ();
    void set (TriValue value);
}

See Also

XllArgumentAttribute Class
XllPlus Namespace


Tag Property

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute..::.Tag Property
XllArgumentAttribute Class See Also Send Feedback
A string value which will be passed to the code generator. (Internal use.)

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string Tag { get; set; }
Visual Basic (Declaration)
Public Property Tag As String
Visual C++
public:
property String^ Tag {
    String^ get ();
    void set (String^ value);
}

See Also

XllArgumentAttribute Class
XllPlus Namespace


ValueList Property

[image]

XLL+ .NET Runtime Class Library
XllArgumentAttribute..::.ValueList Property
XllArgumentAttribute Class See Also Send Feedback
A list of the values of which the argument's value may or must be a member. Items in the list are separated by semi-colons. Each item is a value+description pair, separated by a comma. e.g. 1,One;2,Two;3,Three.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string ValueList { get; set; }
Visual Basic (Declaration)
Public Property ValueList As String
Visual C++
public:
property String^ ValueList {
    String^ get ();
    void set (String^ value);
}

See Also

XllArgumentAttribute Class
XllPlus Namespace


XllAssemblyExportAttribute Class

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute Class
Members See Also Send Feedback
Controls the export of the methods and properties in an entire assembly.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public class XllAssemblyExportAttribute : Attribute,
    IComparable, ICloneable
Visual Basic (Declaration)
Public Class XllAssemblyExportAttribute _
    Inherits Attribute _
    Implements IComparable, ICloneable
Visual C++
public ref class XllAssemblyExportAttribute : public Attribute,
    IComparable, ICloneable

Inheritance Hierarchy

System..::.Object
System..::.Attribute
XllPlus..::.XllAssemblyExportAttribute

See Also

XllAssemblyExportAttribute Members
XllPlus Namespace


XllAssemblyExportAttribute Members

[image] [image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute Members
XllAssemblyExportAttribute Class Constructors Methods Properties See Also Send Feedback

The XllAssemblyExportAttribute type exposes the following members.

Constructors

Name | Description
XllAssemblyExportAttribute | Overloaded.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.
Compare | Compares two XllAssemblyExportAttribute instances.
IsDefault | Returns whether the attribute's properties are all set to default values.

Properties

Name | Description
Category | The standard Excel category to which all exported functions will belong (unless individually specified).
CategoryText | The non-standard Excel category to which all exported functions will belong (unless individually specified).
Filter | The set of eligible methods that will be exported by default (unless they are marked with a XllFunctionAttribute as ShouldExport=false).
NamesToUpperCase | Sets whether all exported names are forced to upper case.
Prefix | The prefix applied to the Excel names of all exported members.
Versions | The Excel versions for which code will be generated.

See Also

XllAssemblyExportAttribute Class
XllPlus Namespace


XllAssemblyExportAttribute Constructor

[image] [image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute Constructor
XllAssemblyExportAttribute Class See Also Send Feedback

Overload List

Name | Description
XllAssemblyExportAttribute()()() | Creates a new XllAssemblyExportAttribute object.
XllAssemblyExportAttribute(String) | Creates a new XllAssemblyExportAttribute object.
XllAssemblyExportAttribute(XlExportFilter) | Creates a new XllAssemblyExportAttribute object.
XllAssemblyExportAttribute(String, XlExportFilter) | Creates a new XllAssemblyExportAttribute object.
XllAssemblyExportAttribute(String, String, XlExportFilter, TriValue, XlVersions) | Creates a new XllAssemblyExportAttribute object.

See Also

XllAssemblyExportAttribute Class
XllAssemblyExportAttribute Members
XllPlus Namespace


XllAssemblyExportAttribute Constructor

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute Constructor
XllAssemblyExportAttribute Class See Also Send Feedback
Creates a new XllAssemblyExportAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllAssemblyExportAttribute()
Visual Basic (Declaration)
Public Sub New
Visual C++
public:
XllAssemblyExportAttribute()

See Also

XllAssemblyExportAttribute Class
XllAssemblyExportAttribute Overload
XllPlus Namespace


XllAssemblyExportAttribute Constructor (String)

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute Constructor (String)
XllAssemblyExportAttribute Class See Also Send Feedback
Creates a new XllAssemblyExportAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllAssemblyExportAttribute(
    string categoryText
)
Visual Basic (Declaration)
Public Sub New ( _
    categoryText As String _
)
Visual C++
public:
XllAssemblyExportAttribute(
    String^ categoryText
)

Parameters

categoryText
Type: System..::.String
The category to which exported functions will belong.

See Also

XllAssemblyExportAttribute Class
XllAssemblyExportAttribute Overload
XllPlus Namespace


XllAssemblyExportAttribute Constructor (XlExportFilter)

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute Constructor (XlExportFilter)
XllAssemblyExportAttribute Class See Also Send Feedback
Creates a new XllAssemblyExportAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllAssemblyExportAttribute(
    XlExportFilter filter
)
Visual Basic (Declaration)
Public Sub New ( _
    filter As XlExportFilter _
)
Visual C++
public:
XllAssemblyExportAttribute(
    XlExportFilter filter
)

Parameters

filter
Type: XllPlus..::.XlExportFilter
The set of methods or properties which will be exported without further instructions.

See Also

XllAssemblyExportAttribute Class
XllAssemblyExportAttribute Overload
XllPlus Namespace


XllAssemblyExportAttribute Constructor (String, XlExportFilter)

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute Constructor (String, XlExportFilter)
XllAssemblyExportAttribute Class See Also Send Feedback
Creates a new XllAssemblyExportAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllAssemblyExportAttribute(
    string categoryText,
    XlExportFilter filter
)
Visual Basic (Declaration)
Public Sub New ( _
    categoryText As String, _
    filter As XlExportFilter _
)
Visual C++
public:
XllAssemblyExportAttribute(
    String^ categoryText,
    XlExportFilter filter
)

Parameters

categoryText
Type: System..::.String
The category to which exported functions will belong.
filter
Type: XllPlus..::.XlExportFilter
The set of methods or properties which will be exported without further instructions.

See Also

XllAssemblyExportAttribute Class
XllAssemblyExportAttribute Overload
XllPlus Namespace


XllAssemblyExportAttribute Constructor (String, String, XlExportFilter, TriValue, XlVersions)

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute Constructor (String, String, XlExportFilter, TriValue, XlVersions)
XllAssemblyExportAttribute Class See Also Send Feedback
Creates a new XllAssemblyExportAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllAssemblyExportAttribute(
    string categoryText,
    string prefix,
    XlExportFilter filter,
    TriValue namesToUpperCase,
    XlVersions versions
)
Visual Basic (Declaration)
Public Sub New ( _
    categoryText As String, _
    prefix As String, _
    filter As XlExportFilter, _
    namesToUpperCase As TriValue, _
    versions As XlVersions _
)
Visual C++
public:
XllAssemblyExportAttribute(
    String^ categoryText,
    String^ prefix,
    XlExportFilter filter,
    TriValue namesToUpperCase,
    XlVersions versions
)

Parameters

categoryText
Type: System..::.String
The category to which exported functions will belong.
prefix
Type: System..::.String
The prefix to be applied to the names of all exported functions.
filter
Type: XllPlus..::.XlExportFilter
The set of methods or properties which will be exported without further instructions.
namesToUpperCase
Type: XllPlus..::.TriValue
Controls whether all function names are exported to Excel in upper case.
versions
Type: XllPlus..::.XlVersions
The Excel versions for which code will be generated.

See Also

XllAssemblyExportAttribute Class
XllAssemblyExportAttribute Overload
XllPlus Namespace


XllAssemblyExportAttribute Methods

[image] [image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute Methods
XllAssemblyExportAttribute Class See Also Send Feedback

The XllAssemblyExportAttribute type exposes the following members.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.
Compare | Compares two XllAssemblyExportAttribute instances.
IsDefault | Returns whether the attribute's properties are all set to default values.

See Also

XllAssemblyExportAttribute Class
XllPlus Namespace


Clone Method

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute..::.Clone Method
XllAssemblyExportAttribute Class See Also Send Feedback
Returns a deep copy of the current instance.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public Object Clone()
Visual Basic (Declaration)
Public Function Clone As Object
Visual C++
public:
virtual Object^ Clone() sealed

Return Value

A new XllAssemblyExportAttribute object, whose properties are all equal in value to this.

Implements

ICloneable..::.Clone()()()

See Also

XllAssemblyExportAttribute Class
XllPlus Namespace


Compare Method

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute..::.Compare Method
XllAssemblyExportAttribute Class See Also Send Feedback
Compares two XllAssemblyExportAttribute instances.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public int Compare(
    XllAssemblyExportAttribute other
)
Visual Basic (Declaration)
Public Function Compare ( _
    other As XllAssemblyExportAttribute _
) As Integer
Visual C++
public:
int Compare(
    XllAssemblyExportAttribute^ other
)

Parameters

other
Type: XllPlus..::.XllAssemblyExportAttribute
A second instance to be compared to this.

Return Value

-1 if this is less than other. 0 if the two are equal. 1 if this is greater than other.

See Also

XllAssemblyExportAttribute Class
XllPlus Namespace


IsDefault Method

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute..::.IsDefault Method
XllAssemblyExportAttribute Class See Also Send Feedback
Returns whether the attribute's properties are all set to default values.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public bool IsDefault()
Visual Basic (Declaration)
Public Function IsDefault As Boolean
Visual C++
public:
bool IsDefault()

Return Value

True if all properties are at their default values. False if any property has a non-default value.

See Also

XllAssemblyExportAttribute Class
XllPlus Namespace


XllAssemblyExportAttribute Properties

[image] [image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute Properties
XllAssemblyExportAttribute Class See Also Send Feedback

The XllAssemblyExportAttribute type exposes the following members.

Properties

Name | Description
Category | The standard Excel category to which all exported functions will belong (unless individually specified).
CategoryText | The non-standard Excel category to which all exported functions will belong (unless individually specified).
Filter | The set of eligible methods that will be exported by default (unless they are marked with a XllFunctionAttribute as ShouldExport=false).
NamesToUpperCase | Sets whether all exported names are forced to upper case.
Prefix | The prefix applied to the Excel names of all exported members.
Versions | The Excel versions for which code will be generated.

See Also

XllAssemblyExportAttribute Class
XllPlus Namespace


Category Property

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute..::.Category Property
XllAssemblyExportAttribute Class See Also Send Feedback
The standard Excel category to which all exported functions will belong (unless individually specified).

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XlCategory Category { get; set; }
Visual Basic (Declaration)
Public Property Category As XlCategory
Visual C++
public:
property XlCategory Category {
    XlCategory get ();
    void set (XlCategory value);
}

See Also

XllAssemblyExportAttribute Class
XllPlus Namespace


CategoryText Property

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute..::.CategoryText Property
XllAssemblyExportAttribute Class See Also Send Feedback
The non-standard Excel category to which all exported functions will belong (unless individually specified).

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string CategoryText { get; set; }
Visual Basic (Declaration)
Public Property CategoryText As String
Visual C++
public:
property String^ CategoryText {
    String^ get ();
    void set (String^ value);
}

See Also

XllAssemblyExportAttribute Class
XllPlus Namespace


Filter Property

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute..::.Filter Property
XllAssemblyExportAttribute Class See Also Send Feedback
The set of eligible methods that will be exported by default (unless they are marked with a XllFunctionAttribute as ShouldExport=false).

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XlExportFilter Filter { get; set; }
Visual Basic (Declaration)
Public Property Filter As XlExportFilter
Visual C++
public:
property XlExportFilter Filter {
    XlExportFilter get ();
    void set (XlExportFilter value);
}

See Also

XllAssemblyExportAttribute Class
XllPlus Namespace


NamesToUpperCase Property

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute..::.NamesToUpperCase Property
XllAssemblyExportAttribute Class See Also Send Feedback
Sets whether all exported names are forced to upper case.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public TriValue NamesToUpperCase { get; set; }
Visual Basic (Declaration)
Public Property NamesToUpperCase As TriValue
Visual C++
public:
property TriValue NamesToUpperCase {
    TriValue get ();
    void set (TriValue value);
}

See Also

XllAssemblyExportAttribute Class
XllPlus Namespace


Prefix Property

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute..::.Prefix Property
XllAssemblyExportAttribute Class See Also Send Feedback
The prefix applied to the Excel names of all exported members.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string Prefix { get; set; }
Visual Basic (Declaration)
Public Property Prefix As String
Visual C++
public:
property String^ Prefix {
    String^ get ();
    void set (String^ value);
}

See Also

XllAssemblyExportAttribute Class
XllPlus Namespace


Versions Property

[image]

XLL+ .NET Runtime Class Library
XllAssemblyExportAttribute..::.Versions Property
XllAssemblyExportAttribute Class See Also Send Feedback
The Excel versions for which code will be generated.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XlVersions Versions { get; set; }
Visual Basic (Declaration)
Public Property Versions As XlVersions
Visual C++
public:
property XlVersions Versions {
    XlVersions get ();
    void set (XlVersions value);
}

See Also

XllAssemblyExportAttribute Class
XllPlus Namespace


XllAttributeOverrides Class

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides Class
Members See Also Send Feedback
A collection of overrides for exporting reflected members from an Assembly. XllAttributeOverrides contains a map connecting zero or more reflected members and a set of override attributes each held in a XllAttributes object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public class XllAttributeOverrides : ICloneable
Visual Basic (Declaration)
Public Class XllAttributeOverrides _
    Implements ICloneable
Visual C++
public ref class XllAttributeOverrides : ICloneable

Inheritance Hierarchy

System..::.Object
XllPlus..::.XllAttributeOverrides

See Also

XllAttributeOverrides Members
XllPlus Namespace


XllAttributeOverrides Members

[image] [image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides Members
XllAttributeOverrides Class Constructors Methods Fields Properties See Also Send Feedback

The XllAttributeOverrides type exposes the following members.

Constructors

Name | Description
XllAttributeOverrides | Creates a new XllAttributeOverrides object.

Methods

Name | Description
Add | Adds the specified item to the collection.
Clone | Returns a deep copy of the collection and its items.
ContainsKey | Returns true if the specified key exists in the collection.
Merge | Merges this collection with another.
Normalize | Normalizes each of the items in the collection, and removes any that contain only default values.
Remove | Removes the specified item from the collection.

Fields

Name | Description
XmlNamespace | Namespace used in XML serialization.

Properties

Name | Description
ArchiveVersion | The file version of the saved data.
AssemblyFile | The full path of the reflected assembly file.
Entries | Internal property used during serialization.
Item | Returns the XllAttributes object for the specified Assembly.

See Also

XllAttributeOverrides Class
XllPlus Namespace


XllAttributeOverrides Constructor

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides Constructor
XllAttributeOverrides Class See Also Send Feedback
Creates a new XllAttributeOverrides object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllAttributeOverrides()
Visual Basic (Declaration)
Public Sub New
Visual C++
public:
XllAttributeOverrides()

See Also

XllAttributeOverrides Class
XllPlus Namespace


XllAttributeOverrides Fields

[image] [image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides Fields
XllAttributeOverrides Class See Also Send Feedback

The XllAttributeOverrides type exposes the following members.

Fields

Name | Description
XmlNamespace | Namespace used in XML serialization.

See Also

XllAttributeOverrides Class
XllPlus Namespace


XmlNamespace Field

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.XmlNamespace Field
XllAttributeOverrides Class See Also Send Feedback
Namespace used in XML serialization.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public const string XmlNamespace
Visual Basic (Declaration)
Public Const XmlNamespace As String
Visual C++
public:
literal String^ XmlNamespace

See Also

XllAttributeOverrides Class
XllPlus Namespace


XllAttributeOverrides Methods

[image] [image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides Methods
XllAttributeOverrides Class See Also Send Feedback

The XllAttributeOverrides type exposes the following members.

Methods

Name | Description
Add | Adds the specified item to the collection.
Clone | Returns a deep copy of the collection and its items.
ContainsKey | Returns true if the specified key exists in the collection.
Merge | Merges this collection with another.
Normalize | Normalizes each of the items in the collection, and removes any that contain only default values.
Remove | Removes the specified item from the collection.

See Also

XllAttributeOverrides Class
XllPlus Namespace


Add Method

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.Add Method
XllAttributeOverrides Class See Also Send Feedback
Adds the specified item to the collection.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public void Add(
    XllAttributes attributes,
    string key
)
Visual Basic (Declaration)
Public Sub Add ( _
    attributes As XllAttributes, _
    key As String _
)
Visual C++
public:
void Add(
    XllAttributes^ attributes,
    String^ key
)

Parameters

attributes
Type: XllPlus..::.XllAttributes
The set of export attributes which will be applied to the The documentation key for a reflected object. reflected object.
key
Type: System..::.String

[Missing <param name="key"/> documentation for "M:XllPlus.XllAttributeOverrides.Add(XllPlus.XllAttributes,System.String)"]

See Also

XllAttributeOverrides Class
XllPlus Namespace


Clone Method

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.Clone Method
XllAttributeOverrides Class See Also Send Feedback
Returns a deep copy of the collection and its items.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public Object Clone()
Visual Basic (Declaration)
Public Function Clone As Object
Visual C++
public:
virtual Object^ Clone() sealed

Return Value

A new XllAttributeOverrides object, whose properties and items are all equal in value to this.

Implements

ICloneable..::.Clone()()()

See Also

XllAttributeOverrides Class
XllPlus Namespace


ContainsKey Method

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.ContainsKey Method
XllAttributeOverrides Class See Also Send Feedback
Returns true if the specified key exists in the collection.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public bool ContainsKey(
    string key
)
Visual Basic (Declaration)
Public Function ContainsKey ( _
    key As String _
) As Boolean
Visual C++
public:
bool ContainsKey(
    String^ key
)

Parameters

key
Type: System..::.String
The documentation key for a reflected object.

Return Value

true if the key exists in the collection. false if it does not.

See Also

XllAttributeOverrides Class
XllPlus Namespace


Merge Method

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.Merge Method
XllAttributeOverrides Class See Also Send Feedback
Merges this collection with another.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public bool Merge(
    XllAttributeOverrides source
)
Visual Basic (Declaration)
Public Function Merge ( _
    source As XllAttributeOverrides _
) As Boolean
Visual C++
public:
bool Merge(
    XllAttributeOverrides^ source
)

Parameters

source
Type: XllPlus..::.XllAttributeOverrides
Another collection of overrides. If a member exists in both collections, then the value in source will be ignored.

Return Value

true if any changes were made to this collection by the merge. false if the collection was unaffected.

See Also

XllAttributeOverrides Class
XllPlus Namespace


Normalize Method

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.Normalize Method
XllAttributeOverrides Class See Also Send Feedback
Normalizes each of the items in the collection, and removes any that contain only default values.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public void Normalize()
Visual Basic (Declaration)
Public Sub Normalize
Visual C++
public:
void Normalize()

See Also

XllAttributeOverrides Class
XllPlus Namespace
XllAttributes..::.Normalize()()()


Remove Method

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.Remove Method
XllAttributeOverrides Class See Also Send Feedback
Removes the specified item from the collection.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public void Remove(
    string key
)
Visual Basic (Declaration)
Public Sub Remove ( _
    key As String _
)
Visual C++
public:
void Remove(
    String^ key
)

Parameters

key
Type: System..::.String
The documentation key for a reflected object.

See Also

XllAttributeOverrides Class
XllPlus Namespace


XllAttributeOverrides Properties

[image] [image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides Properties
XllAttributeOverrides Class See Also Send Feedback

The XllAttributeOverrides type exposes the following members.

Properties

Name | Description
ArchiveVersion | The file version of the saved data.
AssemblyFile | The full path of the reflected assembly file.
Entries | Internal property used during serialization.
Item | Returns the XllAttributes object for the specified Assembly.

See Also

XllAttributeOverrides Class
XllPlus Namespace


ArchiveVersion Property

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.ArchiveVersion Property
XllAttributeOverrides Class See Also Send Feedback
The file version of the saved data.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public int ArchiveVersion { get; set; }
Visual Basic (Declaration)
Public Property ArchiveVersion As Integer
Visual C++
public:
property int ArchiveVersion {
    int get ();
    void set (int value);
}

See Also

XllAttributeOverrides Class
XllPlus Namespace


AssemblyFile Property

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.AssemblyFile Property
XllAttributeOverrides Class See Also Send Feedback
The full path of the reflected assembly file.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string AssemblyFile { get; set; }
Visual Basic (Declaration)
Public Property AssemblyFile As String
Visual C++
public:
property String^ AssemblyFile {
    String^ get ();
    void set (String^ value);
}

See Also

XllAttributeOverrides Class
XllPlus Namespace


Entries Property

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.Entries Property
XllAttributeOverrides Class See Also Send Feedback
Internal property used during serialization.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllAttributeOverrides..::.Pair[] Entries { get; set; }
Visual Basic (Declaration)
Public Property Entries As XllAttributeOverrides..::.Pair()
Visual C++
public:
property array<XllAttributeOverrides..::.Pair^>^ Entries {
    array<XllAttributeOverrides..::.Pair^>^ get ();
    void set (array<XllAttributeOverrides..::.Pair^>^ value);
}

See Also

XllAttributeOverrides Class
XllPlus Namespace


Item Property

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.Item Property
XllAttributeOverrides Class See Also Send Feedback
Returns the XllAttributes object for the specified Assembly.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllAttributes this[
    string key
] { get; }
Visual Basic (Declaration)
Public ReadOnly Default Property Item ( _
    key As String _
) As XllAttributes
Visual C++
public:
property XllAttributes^ default[String^ key] {
    XllAttributes^ get (String^ key);
}

Parameters

key
Type: System..::.String
The documentation key for a reflected object.

Return Value

A XllAttributes object for the specified object, if any exists. Otherwise null.

See Also

XllAttributeOverrides Class
XllPlus Namespace


XllAttributeOverrides.Pair Class

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.Pair Class
XllAttributeOverrides Class Members See Also Send Feedback
Internal class used during serialization.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public class Pair
Visual Basic (Declaration)
Public Class Pair
Visual C++
public ref class Pair

Inheritance Hierarchy

System..::.Object
XllPlus..::.XllAttributeOverrides..::.Pair

See Also

XllAttributeOverrides..::.Pair Members
XllPlus Namespace


XllAttributeOverrides.Pair Members

[image] [image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.Pair Members
XllAttributeOverrides..::.Pair Class Properties See Also Send Feedback

A collection of overrides for exporting reflected members from an Assembly. XllAttributeOverrides contains a map connecting zero or more reflected members and a set of override attributes each held in a XllAttributes object.

The XllAttributeOverrides..::.Pair type exposes the following members.

Properties

Name | Description
Key | String key to reflected member.
Value | Export attributes applied to a reflected member.

See Also

XllAttributeOverrides..::.Pair Class
XllPlus Namespace


XllAttributeOverrides.Pair Properties

[image] [image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.Pair Properties
XllAttributeOverrides..::.Pair Class See Also Send Feedback

The XllAttributeOverrides..::.Pair type exposes the following members.

Properties

Name | Description
Key | String key to reflected member.
Value | Export attributes applied to a reflected member.

See Also

XllAttributeOverrides..::.Pair Class
XllPlus Namespace


Key Property

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.Pair..::.Key Property
XllAttributeOverrides..::.Pair Class See Also Send Feedback
String key to reflected member.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string Key { get; set; }
Visual Basic (Declaration)
Public Property Key As String
Visual C++
public:
property String^ Key {
    String^ get ();
    void set (String^ value);
}

See Also

XllAttributeOverrides..::.Pair Class
XllPlus Namespace


Value Property

[image]

XLL+ .NET Runtime Class Library
XllAttributeOverrides..::.Pair..::.Value Property
XllAttributeOverrides..::.Pair Class See Also Send Feedback
Export attributes applied to a reflected member.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllAttributes Value { get; set; }
Visual Basic (Declaration)
Public Property Value As XllAttributes
Visual C++
public:
property XllAttributes^ Value {
    XllAttributes^ get ();
    void set (XllAttributes^ value);
}

See Also

XllAttributeOverrides..::.Pair Class
XllPlus Namespace


XllAttributes Class

[image]

XLL+ .NET Runtime Class Library
XllAttributes Class
Members See Also Send Feedback
Holds a complete set of XLL export attributes for a member.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public class XllAttributes : IComparable,
    ICloneable
Visual Basic (Declaration)
Public Class XllAttributes _
    Implements IComparable, ICloneable
Visual C++
public ref class XllAttributes : IComparable,
    ICloneable

Remarks

The properties of the class include optional instances of each of the XLL export attributes: XllAssemblyExportAttribute, XllClassExportAttribute, XllFunctionAttribute, XllMacroAttribute and XllArgumentAttribute. XllIgnoreAttribute is reperesented by a boolean property.

Inheritance Hierarchy

System..::.Object
XllPlus..::.XllAttributes

See Also

XllAttributes Members
XllPlus Namespace


XllAttributes Members

[image] [image]

XLL+ .NET Runtime Class Library
XllAttributes Members
XllAttributes Class Constructors Methods Properties See Also Send Feedback

The XllAttributes type exposes the following members.

Constructors

Name | Description
XllAttributes | Creates a new instance of XllAttributes.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.
Compare | Compares two XllAttributes instances.
CompareTo | Compares two XllAttributes instances.
IsDefault | Returns whether the XllAttributes' properties are all set to default values.
Normalize | Removes all properties which conain default values.

Properties

Name | Description
XllArgument | Applies to the current parameter. Ignored if the XllAttributes set is not applied to the parameter of a method or indexed property.
XllAssembly | Applies to all classes in the current assembly. Ignored if the XllAttributes set is not applied to an assembly.
XllClassExport | Applies to all classes in the current type. Ignored if the XllAttributes set is not applied to a type.
XllFunction | Applies to the current method or property. Ignored if the XllAttributes set is not applied to a method or property.
XllIgnore | Applies to the current method or property. Ignored if the XllAttributes set is not applied to a method or property.
XllMacro | Applies to the current method. Ignored if the XllAttributes set is not applied to a method, or if the method has a return value.

See Also

XllAttributes Class
XllPlus Namespace


XllAttributes Constructor

[image]

XLL+ .NET Runtime Class Library
XllAttributes Constructor
XllAttributes Class See Also Send Feedback
Creates a new instance of XllAttributes.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllAttributes()
Visual Basic (Declaration)
Public Sub New
Visual C++
public:
XllAttributes()

Remarks

All properties will be set to their default values, null or false.

See Also

XllAttributes Class
XllPlus Namespace


XllAttributes Methods

[image] [image]

XLL+ .NET Runtime Class Library
XllAttributes Methods
XllAttributes Class See Also Send Feedback

The XllAttributes type exposes the following members.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.
Compare | Compares two XllAttributes instances.
CompareTo | Compares two XllAttributes instances.
IsDefault | Returns whether the XllAttributes' properties are all set to default values.
Normalize | Removes all properties which conain default values.

See Also

XllAttributes Class
XllPlus Namespace


Clone Method

[image]

XLL+ .NET Runtime Class Library
XllAttributes..::.Clone Method
XllAttributes Class See Also Send Feedback
Returns a deep copy of the current instance.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public Object Clone()
Visual Basic (Declaration)
Public Function Clone As Object
Visual C++
public:
virtual Object^ Clone() sealed

Return Value

A new XllAttributes object, whose properties are all equal in value to this.

Implements

ICloneable..::.Clone()()()

See Also

XllAttributes Class
XllPlus Namespace


Compare Method

[image]

XLL+ .NET Runtime Class Library
XllAttributes..::.Compare Method
XllAttributes Class See Also Send Feedback
Compares two XllAttributes instances.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public int Compare(
    XllAttributes other
)
Visual Basic (Declaration)
Public Function Compare ( _
    other As XllAttributes _
) As Integer
Visual C++
public:
int Compare(
    XllAttributes^ other
)

Parameters

other
Type: XllPlus..::.XllAttributes
A second instance to be compared to this.

Return Value

-1 if this is less than other. 0 if the two are equal. 1 if this is greater than other.

See Also

XllAttributes Class
XllPlus Namespace


CompareTo Method

[image]

XLL+ .NET Runtime Class Library
XllAttributes..::.CompareTo Method
XllAttributes Class See Also Send Feedback
Compares two XllAttributes instances.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public int CompareTo(
    Object other
)
Visual Basic (Declaration)
Public Function CompareTo ( _
    other As Object _
) As Integer
Visual C++
public:
virtual int CompareTo(
    Object^ other
) sealed

Parameters

other
Type: System..::.Object
A second instance to be compared to this.

Return Value

-1 if this is less than other. 0 if the two are equal. 1 if this is greater than other.

Implements

IComparable..::.CompareTo(Object)

See Also

XllAttributes Class
XllPlus Namespace


IsDefault Method

[image]

XLL+ .NET Runtime Class Library
XllAttributes..::.IsDefault Method
XllAttributes Class See Also Send Feedback
Returns whether the XllAttributes' properties are all set to default values.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public bool IsDefault()
Visual Basic (Declaration)
Public Function IsDefault As Boolean
Visual C++
public:
bool IsDefault()

Return Value

True if all properties are at their default values (null or false). False if any property has a non-default value.

See Also

XllAttributes Class
XllPlus Namespace


Normalize Method

[image]

XLL+ .NET Runtime Class Library
XllAttributes..::.Normalize Method
XllAttributes Class See Also Send Feedback
Removes all properties which conain default values.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public void Normalize()
Visual Basic (Declaration)
Public Sub Normalize
Visual C++
public:
void Normalize()

Remarks

Any non-null property whose values are all default values will be removed, and set to null.

See Also

XllAttributes Class
XllPlus Namespace


XllAttributes Properties

[image] [image]

XLL+ .NET Runtime Class Library
XllAttributes Properties
XllAttributes Class See Also Send Feedback

The XllAttributes type exposes the following members.

Properties

Name | Description
XllArgument | Applies to the current parameter. Ignored if the XllAttributes set is not applied to the parameter of a method or indexed property.
XllAssembly | Applies to all classes in the current assembly. Ignored if the XllAttributes set is not applied to an assembly.
XllClassExport | Applies to all classes in the current type. Ignored if the XllAttributes set is not applied to a type.
XllFunction | Applies to the current method or property. Ignored if the XllAttributes set is not applied to a method or property.
XllIgnore | Applies to the current method or property. Ignored if the XllAttributes set is not applied to a method or property.
XllMacro | Applies to the current method. Ignored if the XllAttributes set is not applied to a method, or if the method has a return value.

See Also

XllAttributes Class
XllPlus Namespace


XllArgument Property

[image]

XLL+ .NET Runtime Class Library
XllAttributes..::.XllArgument Property
XllAttributes Class See Also Send Feedback
Applies to the current parameter. Ignored if the XllAttributes set is not applied to the parameter of a method or indexed property.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllArgumentAttribute XllArgument { get; set; }
Visual Basic (Declaration)
Public Property XllArgument As XllArgumentAttribute
Visual C++
public:
property XllArgumentAttribute^ XllArgument {
    XllArgumentAttribute^ get ();
    void set (XllArgumentAttribute^ value);
}

See Also

XllAttributes Class
XllPlus Namespace


XllAssembly Property

[image]

XLL+ .NET Runtime Class Library
XllAttributes..::.XllAssembly Property
XllAttributes Class See Also Send Feedback
Applies to all classes in the current assembly. Ignored if the XllAttributes set is not applied to an assembly.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllAssemblyExportAttribute XllAssembly { get; set; }
Visual Basic (Declaration)
Public Property XllAssembly As XllAssemblyExportAttribute
Visual C++
public:
property XllAssemblyExportAttribute^ XllAssembly {
    XllAssemblyExportAttribute^ get ();
    void set (XllAssemblyExportAttribute^ value);
}

See Also

XllAttributes Class
XllPlus Namespace


XllClassExport Property

[image]

XLL+ .NET Runtime Class Library
XllAttributes..::.XllClassExport Property
XllAttributes Class See Also Send Feedback
Applies to all classes in the current type. Ignored if the XllAttributes set is not applied to a type.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllClassExportAttribute XllClassExport { get; set; }
Visual Basic (Declaration)
Public Property XllClassExport As XllClassExportAttribute
Visual C++
public:
property XllClassExportAttribute^ XllClassExport {
    XllClassExportAttribute^ get ();
    void set (XllClassExportAttribute^ value);
}

See Also

XllAttributes Class
XllPlus Namespace


XllFunction Property

[image]

XLL+ .NET Runtime Class Library
XllAttributes..::.XllFunction Property
XllAttributes Class See Also Send Feedback
Applies to the current method or property. Ignored if the XllAttributes set is not applied to a method or property.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllFunctionAttribute XllFunction { get; set; }
Visual Basic (Declaration)
Public Property XllFunction As XllFunctionAttribute
Visual C++
public:
property XllFunctionAttribute^ XllFunction {
    XllFunctionAttribute^ get ();
    void set (XllFunctionAttribute^ value);
}

See Also

XllAttributes Class
XllPlus Namespace


XllIgnore Property

[image]

XLL+ .NET Runtime Class Library
XllAttributes..::.XllIgnore Property
XllAttributes Class See Also Send Feedback
Applies to the current method or property. Ignored if the XllAttributes set is not applied to a method or property.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public bool XllIgnore { get; set; }
Visual Basic (Declaration)
Public Property XllIgnore As Boolean
Visual C++
public:
property bool XllIgnore {
    bool get ();
    void set (bool value);
}

See Also

XllAttributes Class
XllPlus Namespace


XllMacro Property

[image]

XLL+ .NET Runtime Class Library
XllAttributes..::.XllMacro Property
XllAttributes Class See Also Send Feedback
Applies to the current method. Ignored if the XllAttributes set is not applied to a method, or if the method has a return value.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllMacroAttribute XllMacro { get; set; }
Visual Basic (Declaration)
Public Property XllMacro As XllMacroAttribute
Visual C++
public:
property XllMacroAttribute^ XllMacro {
    XllMacroAttribute^ get ();
    void set (XllMacroAttribute^ value);
}

See Also

XllAttributes Class
XllPlus Namespace


XllClassExportAttribute Class

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute Class
Members See Also Send Feedback
Controls the export of a class' methods and properties as Excel add-in functions.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public class XllClassExportAttribute : Attribute,
    IComparable, ICloneable
Visual Basic (Declaration)
Public Class XllClassExportAttribute _
    Inherits Attribute _
    Implements IComparable, ICloneable
Visual C++
public ref class XllClassExportAttribute : public Attribute,
    IComparable, ICloneable

Inheritance Hierarchy

System..::.Object
System..::.Attribute
XllPlus..::.XllClassExportAttribute

See Also

XllClassExportAttribute Members
XllPlus Namespace


XllClassExportAttribute Members

[image] [image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute Members
XllClassExportAttribute Class Constructors Methods Properties See Also Send Feedback

The XllClassExportAttribute type exposes the following members.

Constructors

Name | Description
XllClassExportAttribute | Overloaded.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.
Compare | Compares two XllClassExportAttribute instances.
IsDefault | Returns whether the attribute's properties are all set to default values.

Properties

Name | Description
Category | The standard Excel category to which all exported functions will belong (unless individually specified).
CategoryText | The non-standard Excel category to which all exported functions will belong (unless individually specified).
Filter | The set of methods that will be exported by default (unless they are marked with a XllFunctionAttribute as ShouldExport=false).
MenuCaption | Not supported.
NamesToUpperCase | Sets whether all exported names are forced to upper case.
Prefix | The prefix applied to the Excel names of all exported members
Versions | The Excel versions for which code will be generated.

See Also

XllClassExportAttribute Class
XllPlus Namespace


XllClassExportAttribute Constructor

[image] [image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute Constructor
XllClassExportAttribute Class See Also Send Feedback

Overload List

Name | Description
XllClassExportAttribute()()() | Creates a new XllClassExportAttribute object.
XllClassExportAttribute(String) | Creates a new XllClassExportAttribute object.
XllClassExportAttribute(XlExportFilter) | Creates a new XllClassExportAttribute object.
XllClassExportAttribute(String, XlExportFilter) | Creates a new XllClassExportAttribute object.
XllClassExportAttribute(String, XlExportFilter, TriValue) | Creates a new XllClassExportAttribute object.

See Also

XllClassExportAttribute Class
XllClassExportAttribute Members
XllPlus Namespace


XllClassExportAttribute Constructor

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute Constructor
XllClassExportAttribute Class See Also Send Feedback
Creates a new XllClassExportAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllClassExportAttribute()
Visual Basic (Declaration)
Public Sub New
Visual C++
public:
XllClassExportAttribute()

See Also

XllClassExportAttribute Class
XllClassExportAttribute Overload
XllPlus Namespace


XllClassExportAttribute Constructor (String)

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute Constructor (String)
XllClassExportAttribute Class See Also Send Feedback
Creates a new XllClassExportAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllClassExportAttribute(
    string prefix
)
Visual Basic (Declaration)
Public Sub New ( _
    prefix As String _
)
Visual C++
public:
XllClassExportAttribute(
    String^ prefix
)

Parameters

prefix
Type: System..::.String
The prefix applied to the Excel names of all exported members.

See Also

XllClassExportAttribute Class
XllClassExportAttribute Overload
XllPlus Namespace


XllClassExportAttribute Constructor (XlExportFilter)

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute Constructor (XlExportFilter)
XllClassExportAttribute Class See Also Send Feedback
Creates a new XllClassExportAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllClassExportAttribute(
    XlExportFilter filter
)
Visual Basic (Declaration)
Public Sub New ( _
    filter As XlExportFilter _
)
Visual C++
public:
XllClassExportAttribute(
    XlExportFilter filter
)

Parameters

filter
Type: XllPlus..::.XlExportFilter
The set of methods or properties which will be exported without further instructions.

See Also

XllClassExportAttribute Class
XllClassExportAttribute Overload
XllPlus Namespace


XllClassExportAttribute Constructor (String, XlExportFilter)

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute Constructor (String, XlExportFilter)
XllClassExportAttribute Class See Also Send Feedback
Creates a new XllClassExportAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllClassExportAttribute(
    string prefix,
    XlExportFilter filter
)
Visual Basic (Declaration)
Public Sub New ( _
    prefix As String, _
    filter As XlExportFilter _
)
Visual C++
public:
XllClassExportAttribute(
    String^ prefix,
    XlExportFilter filter
)

Parameters

prefix
Type: System..::.String
The prefix applied to the Excel names of all exported members.
filter
Type: XllPlus..::.XlExportFilter
The set of methods or properties which will be exported without further instructions.

See Also

XllClassExportAttribute Class
XllClassExportAttribute Overload
XllPlus Namespace


XllClassExportAttribute Constructor (String, XlExportFilter, TriValue)

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute Constructor (String, XlExportFilter, TriValue)
XllClassExportAttribute Class See Also Send Feedback
Creates a new XllClassExportAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllClassExportAttribute(
    string prefix,
    XlExportFilter filter,
    TriValue namesToUpperCase
)
Visual Basic (Declaration)
Public Sub New ( _
    prefix As String, _
    filter As XlExportFilter, _
    namesToUpperCase As TriValue _
)
Visual C++
public:
XllClassExportAttribute(
    String^ prefix,
    XlExportFilter filter,
    TriValue namesToUpperCase
)

Parameters

prefix
Type: System..::.String
The prefix applied to the Excel names of all exported members.
filter
Type: XllPlus..::.XlExportFilter
The set of methods or properties which will be exported without further instructions.
namesToUpperCase
Type: XllPlus..::.TriValue
Controls whether all function names are exported to Excel in upper case.

See Also

XllClassExportAttribute Class
XllClassExportAttribute Overload
XllPlus Namespace


XllClassExportAttribute Methods

[image] [image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute Methods
XllClassExportAttribute Class See Also Send Feedback

The XllClassExportAttribute type exposes the following members.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.
Compare | Compares two XllClassExportAttribute instances.
IsDefault | Returns whether the attribute's properties are all set to default values.

See Also

XllClassExportAttribute Class
XllPlus Namespace


Clone Method

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute..::.Clone Method
XllClassExportAttribute Class See Also Send Feedback
Returns a deep copy of the current instance.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public Object Clone()
Visual Basic (Declaration)
Public Function Clone As Object
Visual C++
public:
virtual Object^ Clone() sealed

Return Value

A new XllClassExportAttribute object, whose properties are all equal in value to this.

Implements

ICloneable..::.Clone()()()

See Also

XllClassExportAttribute Class
XllPlus Namespace


Compare Method

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute..::.Compare Method
XllClassExportAttribute Class See Also Send Feedback
Compares two XllClassExportAttribute instances.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public int Compare(
    XllClassExportAttribute other
)
Visual Basic (Declaration)
Public Function Compare ( _
    other As XllClassExportAttribute _
) As Integer
Visual C++
public:
int Compare(
    XllClassExportAttribute^ other
)

Parameters

other
Type: XllPlus..::.XllClassExportAttribute
A second instance to be compared to this.

Return Value

-1 if this is less than other. 0 if the two are equal. 1 if this is greater than other.

See Also

XllClassExportAttribute Class
XllPlus Namespace


IsDefault Method

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute..::.IsDefault Method
XllClassExportAttribute Class See Also Send Feedback
Returns whether the attribute's properties are all set to default values.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public bool IsDefault()
Visual Basic (Declaration)
Public Function IsDefault As Boolean
Visual C++
public:
bool IsDefault()

Return Value

True if all properties are at their default values. False if any property has a non-default value.

See Also

XllClassExportAttribute Class
XllPlus Namespace


XllClassExportAttribute Properties

[image] [image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute Properties
XllClassExportAttribute Class See Also Send Feedback

The XllClassExportAttribute type exposes the following members.

Properties

Name | Description
Category | The standard Excel category to which all exported functions will belong (unless individually specified).
CategoryText | The non-standard Excel category to which all exported functions will belong (unless individually specified).
Filter | The set of methods that will be exported by default (unless they are marked with a XllFunctionAttribute as ShouldExport=false).
MenuCaption | Not supported.
NamesToUpperCase | Sets whether all exported names are forced to upper case.
Prefix | The prefix applied to the Excel names of all exported members
Versions | The Excel versions for which code will be generated.

See Also

XllClassExportAttribute Class
XllPlus Namespace


Category Property

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute..::.Category Property
XllClassExportAttribute Class See Also Send Feedback
The standard Excel category to which all exported functions will belong (unless individually specified).

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XlCategory Category { get; set; }
Visual Basic (Declaration)
Public Property Category As XlCategory
Visual C++
public:
property XlCategory Category {
    XlCategory get ();
    void set (XlCategory value);
}

See Also

XllClassExportAttribute Class
XllPlus Namespace


CategoryText Property

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute..::.CategoryText Property
XllClassExportAttribute Class See Also Send Feedback
The non-standard Excel category to which all exported functions will belong (unless individually specified).

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string CategoryText { get; set; }
Visual Basic (Declaration)
Public Property CategoryText As String
Visual C++
public:
property String^ CategoryText {
    String^ get ();
    void set (String^ value);
}

See Also

XllClassExportAttribute Class
XllPlus Namespace


Filter Property

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute..::.Filter Property
XllClassExportAttribute Class See Also Send Feedback
The set of methods that will be exported by default (unless they are marked with a XllFunctionAttribute as ShouldExport=false).

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XlExportFilter Filter { get; set; }
Visual Basic (Declaration)
Public Property Filter As XlExportFilter
Visual C++
public:
property XlExportFilter Filter {
    XlExportFilter get ();
    void set (XlExportFilter value);
}

See Also

XllClassExportAttribute Class
XllPlus Namespace


MenuCaption Property

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute..::.MenuCaption Property
XllClassExportAttribute Class See Also Send Feedback
Not supported.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string MenuCaption { get; set; }
Visual Basic (Declaration)
Public Property MenuCaption As String
Visual C++
public:
property String^ MenuCaption {
    String^ get ();
    void set (String^ value);
}

See Also

XllClassExportAttribute Class
XllPlus Namespace


NamesToUpperCase Property

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute..::.NamesToUpperCase Property
XllClassExportAttribute Class See Also Send Feedback
Sets whether all exported names are forced to upper case.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public TriValue NamesToUpperCase { get; set; }
Visual Basic (Declaration)
Public Property NamesToUpperCase As TriValue
Visual C++
public:
property TriValue NamesToUpperCase {
    TriValue get ();
    void set (TriValue value);
}

See Also

XllClassExportAttribute Class
XllPlus Namespace


Prefix Property

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute..::.Prefix Property
XllClassExportAttribute Class See Also Send Feedback
The prefix applied to the Excel names of all exported members

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string Prefix { get; set; }
Visual Basic (Declaration)
Public Property Prefix As String
Visual C++
public:
property String^ Prefix {
    String^ get ();
    void set (String^ value);
}

See Also

XllClassExportAttribute Class
XllPlus Namespace


Versions Property

[image]

XLL+ .NET Runtime Class Library
XllClassExportAttribute..::.Versions Property
XllClassExportAttribute Class See Also Send Feedback
The Excel versions for which code will be generated.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XlVersions Versions { get; set; }
Visual Basic (Declaration)
Public Property Versions As XlVersions
Visual C++
public:
property XlVersions Versions {
    XlVersions get ();
    void set (XlVersions value);
}

See Also

XllClassExportAttribute Class
XllPlus Namespace


XllFunctionAttribute Class

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute Class
Members See Also Send Feedback
Controls the export of a specific method or property as an Excel add-in function.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public class XllFunctionAttribute : Attribute,
    IComparable, ICloneable
Visual Basic (Declaration)
Public Class XllFunctionAttribute _
    Inherits Attribute _
    Implements IComparable, ICloneable
Visual C++
public ref class XllFunctionAttribute : public Attribute,
    IComparable, ICloneable

Inheritance Hierarchy

System..::.Object
System..::.Attribute
XllPlus..::.XllFunctionAttribute
XllPlus..::.XllIgnoreAttribute
XllPlus..::.XllMacroAttribute

See Also

XllFunctionAttribute Members
XllPlus Namespace


XllFunctionAttribute Members

[image] [image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute Members
XllFunctionAttribute Class Constructors Methods Properties See Also Send Feedback

The XllFunctionAttribute type exposes the following members.

Constructors

Name | Description
XllFunctionAttribute | Overloaded.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.
Compare | Compares two XllFunctionAttribute instances.
CompareTo | Compares two XllFunctionAttribute instances.
CreateDefault | Creates a new instance containing all default values.
IsDefault | Returns whether the attribute's properties are all set to default values.

Properties

Name | Description
Availability | Controls whether the function will be available for a worksheet cell or only from a command.
Category | The standard Excel category to which the function will belong.
CategoryText | The non-standard Excel category to which the function will belong.
Default | An instance of XllFunctionAttribute which contains all default values.
Description | The help text for the function. This will appear in the Excel Formula Wizard.
ExportedName | The name of the function as it will appear in Excel.
Flags | The set of flags that control the behavior of the exported add-in function.
NameToUpperCase | Sets whether the exported name is forced to upper case.
Prefix | The prefix that will appear before the function's name in Excel.
ReturnsHandle | Controls whether the function will return a handle instead of a standard value or array of values.
ShouldExport | Controls whether the function is exported.
Tag | A string value which is passed to the code generator. (For internal use only.)
TemplateName | The name of the code template to be used in generating this add-in function. (For internal use only.)
Versions | The Excel versions for which code will be generated.

See Also

XllFunctionAttribute Class
XllPlus Namespace


XllFunctionAttribute Constructor

[image] [image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute Constructor
XllFunctionAttribute Class See Also Send Feedback

Overload List

Name | Description
XllFunctionAttribute()()() | Creates a new XllFunctionAttribute object.
XllFunctionAttribute(String) | Creates a new XllFunctionAttribute object.
XllFunctionAttribute(XlFunctionFlags) | Creates a new XllFunctionAttribute object.
XllFunctionAttribute(String, XlFunctionFlags) | Creates a new XllFunctionAttribute object.
XllFunctionAttribute(String, XlFunctionFlags, String, Boolean, String) | Creates a new XllFunctionAttribute object.

See Also

XllFunctionAttribute Class
XllFunctionAttribute Members
XllPlus Namespace


XllFunctionAttribute Constructor

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute Constructor
XllFunctionAttribute Class See Also Send Feedback
Creates a new XllFunctionAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllFunctionAttribute()
Visual Basic (Declaration)
Public Sub New
Visual C++
public:
XllFunctionAttribute()

See Also

XllFunctionAttribute Class
XllFunctionAttribute Overload
XllPlus Namespace


XllFunctionAttribute Constructor (String)

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute Constructor (String)
XllFunctionAttribute Class See Also Send Feedback
Creates a new XllFunctionAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllFunctionAttribute(
    string exportedName
)
Visual Basic (Declaration)
Public Sub New ( _
    exportedName As String _
)
Visual C++
public:
XllFunctionAttribute(
    String^ exportedName
)

Parameters

exportedName
Type: System..::.String
The name of the function in Excel.

See Also

XllFunctionAttribute Class
XllFunctionAttribute Overload
XllPlus Namespace


XllFunctionAttribute Constructor (XlFunctionFlags)

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute Constructor (XlFunctionFlags)
XllFunctionAttribute Class See Also Send Feedback
Creates a new XllFunctionAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllFunctionAttribute(
    XlFunctionFlags flags
)
Visual Basic (Declaration)
Public Sub New ( _
    flags As XlFunctionFlags _
)
Visual C++
public:
XllFunctionAttribute(
    XlFunctionFlags flags
)

Parameters

flags
Type: XllPlus..::.XlFunctionFlags
A set of flags controlling the behavior of the function.

See Also

XllFunctionAttribute Class
XllFunctionAttribute Overload
XllPlus Namespace


XllFunctionAttribute Constructor (String, XlFunctionFlags)

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute Constructor (String, XlFunctionFlags)
XllFunctionAttribute Class See Also Send Feedback
Creates a new XllFunctionAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllFunctionAttribute(
    string exportedName,
    XlFunctionFlags flags
)
Visual Basic (Declaration)
Public Sub New ( _
    exportedName As String, _
    flags As XlFunctionFlags _
)
Visual C++
public:
XllFunctionAttribute(
    String^ exportedName,
    XlFunctionFlags flags
)

Parameters

exportedName
Type: System..::.String
The name of the function in Excel.
flags
Type: XllPlus..::.XlFunctionFlags
A set of flags controlling the behavior of the function.

See Also

XllFunctionAttribute Class
XllFunctionAttribute Overload
XllPlus Namespace


XllFunctionAttribute Constructor (String, XlFunctionFlags, String, Boolean, String)

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute Constructor (String, XlFunctionFlags, String, Boolean, String)
XllFunctionAttribute Class See Also Send Feedback
Creates a new XllFunctionAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllFunctionAttribute(
    string exportedName,
    XlFunctionFlags flags,
    string prefix,
    bool shouldExport,
    string description
)
Visual Basic (Declaration)
Public Sub New ( _
    exportedName As String, _
    flags As XlFunctionFlags, _
    prefix As String, _
    shouldExport As Boolean, _
    description As String _
)
Visual C++
public:
XllFunctionAttribute(
    String^ exportedName,
    XlFunctionFlags flags,
    String^ prefix,
    bool shouldExport,
    String^ description
)

Parameters

exportedName
Type: System..::.String
The name of the function in Excel.
flags
Type: XllPlus..::.XlFunctionFlags
A set of flags controlling the behavior of the function.
prefix
Type: System..::.String
A prefix which preceds the name of the function in Excel.
shouldExport
Type: System..::.Boolean
Whether the function shoud be exported.
description
Type: System..::.String
The help text for the function, which will appear in the Excel Formula Wizard.

See Also

XllFunctionAttribute Class
XllFunctionAttribute Overload
XllPlus Namespace


XllFunctionAttribute Methods

[image] [image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute Methods
XllFunctionAttribute Class See Also Send Feedback

The XllFunctionAttribute type exposes the following members.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.
Compare | Compares two XllFunctionAttribute instances.
CompareTo | Compares two XllFunctionAttribute instances.
CreateDefault | Creates a new instance containing all default values.
IsDefault | Returns whether the attribute's properties are all set to default values.

See Also

XllFunctionAttribute Class
XllPlus Namespace


Clone Method

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.Clone Method
XllFunctionAttribute Class See Also Send Feedback
Returns a deep copy of the current instance.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public Object Clone()
Visual Basic (Declaration)
Public Function Clone As Object
Visual C++
public:
virtual Object^ Clone() sealed

Return Value

A new XllFunctionAttribute object, whose properties are all equal in value to this.

Implements

ICloneable..::.Clone()()()

See Also

XllFunctionAttribute Class
XllPlus Namespace


Compare Method

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.Compare Method
XllFunctionAttribute Class See Also Send Feedback
Compares two XllFunctionAttribute instances.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public int Compare(
    XllFunctionAttribute other
)
Visual Basic (Declaration)
Public Function Compare ( _
    other As XllFunctionAttribute _
) As Integer
Visual C++
public:
int Compare(
    XllFunctionAttribute^ other
)

Parameters

other
Type: XllPlus..::.XllFunctionAttribute
A second instance to be compared to this.

Return Value

-1 if this is less than other. 0 if the two are equal. 1 if this is greater than other.

See Also

XllFunctionAttribute Class
XllPlus Namespace


CompareTo Method

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.CompareTo Method
XllFunctionAttribute Class See Also Send Feedback
Compares two XllFunctionAttribute instances.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public int CompareTo(
    Object other
)
Visual Basic (Declaration)
Public Function CompareTo ( _
    other As Object _
) As Integer
Visual C++
public:
virtual int CompareTo(
    Object^ other
) sealed

Parameters

other
Type: System..::.Object
A second instance to be compared to this.

Return Value

-1 if this is less than other. 0 if the two are equal. 1 if this is greater than other.

Implements

IComparable..::.CompareTo(Object)

See Also

XllFunctionAttribute Class
XllPlus Namespace


CreateDefault Method

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.CreateDefault Method
XllFunctionAttribute Class See Also Send Feedback
Creates a new instance containing all default values.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public static XllFunctionAttribute CreateDefault()
Visual Basic (Declaration)
Public Shared Function CreateDefault As XllFunctionAttribute
Visual C++
public:
static XllFunctionAttribute^ CreateDefault()

Return Value

A new instance of XllFunctionAttribute.

See Also

XllFunctionAttribute Class
XllPlus Namespace


IsDefault Method

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.IsDefault Method
XllFunctionAttribute Class See Also Send Feedback
Returns whether the attribute's properties are all set to default values.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public bool IsDefault()
Visual Basic (Declaration)
Public Function IsDefault As Boolean
Visual C++
public:
bool IsDefault()

Return Value

True if all properties are at their default values. False if any property has a non-default value.

See Also

XllFunctionAttribute Class
XllPlus Namespace


XllFunctionAttribute Properties

[image] [image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute Properties
XllFunctionAttribute Class See Also Send Feedback

The XllFunctionAttribute type exposes the following members.

Properties

Name | Description
Availability | Controls whether the function will be available for a worksheet cell or only from a command.
Category | The standard Excel category to which the function will belong.
CategoryText | The non-standard Excel category to which the function will belong.
Default | An instance of XllFunctionAttribute which contains all default values.
Description | The help text for the function. This will appear in the Excel Formula Wizard.
ExportedName | The name of the function as it will appear in Excel.
Flags | The set of flags that control the behavior of the exported add-in function.
NameToUpperCase | Sets whether the exported name is forced to upper case.
Prefix | The prefix that will appear before the function's name in Excel.
ReturnsHandle | Controls whether the function will return a handle instead of a standard value or array of values.
ShouldExport | Controls whether the function is exported.
Tag | A string value which is passed to the code generator. (For internal use only.)
TemplateName | The name of the code template to be used in generating this add-in function. (For internal use only.)
Versions | The Excel versions for which code will be generated.

See Also

XllFunctionAttribute Class
XllPlus Namespace


Availability Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.Availability Property
XllFunctionAttribute Class See Also Send Feedback
Controls whether the function will be available for a worksheet cell or only from a command.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XlFunctionAvailability Availability { get; set; }
Visual Basic (Declaration)
Public Property Availability As XlFunctionAvailability
Visual C++
public:
property XlFunctionAvailability Availability {
    XlFunctionAvailability get ();
    void set (XlFunctionAvailability value);
}

See Also

XllFunctionAttribute Class
XllPlus Namespace


Category Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.Category Property
XllFunctionAttribute Class See Also Send Feedback
The standard Excel category to which the function will belong.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XlCategory Category { get; set; }
Visual Basic (Declaration)
Public Property Category As XlCategory
Visual C++
public:
property XlCategory Category {
    XlCategory get ();
    void set (XlCategory value);
}

See Also

XllFunctionAttribute Class
XllPlus Namespace


CategoryText Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.CategoryText Property
XllFunctionAttribute Class See Also Send Feedback
The non-standard Excel category to which the function will belong.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string CategoryText { get; set; }
Visual Basic (Declaration)
Public Property CategoryText As String
Visual C++
public:
property String^ CategoryText {
    String^ get ();
    void set (String^ value);
}

See Also

XllFunctionAttribute Class
XllPlus Namespace


Default Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.Default Property
XllFunctionAttribute Class See Also Send Feedback
An instance of XllFunctionAttribute which contains all default values.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public static XllFunctionAttribute Default { get; }
Visual Basic (Declaration)
Public Shared ReadOnly Property Default As XllFunctionAttribute
Visual C++
public:
static property XllFunctionAttribute^ Default {
    XllFunctionAttribute^ get ();
}

Remarks

Note that this is not equal to an instance created using the parameterless constructor, but instead is equal to an instance created using CreateDefault()()().

See Also

XllFunctionAttribute Class
XllPlus Namespace


Description Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.Description Property
XllFunctionAttribute Class See Also Send Feedback
The help text for the function. This will appear in the Excel Formula Wizard.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string Description { get; set; }
Visual Basic (Declaration)
Public Property Description As String
Visual C++
public:
property String^ Description {
    String^ get ();
    void set (String^ value);
}

See Also

XllFunctionAttribute Class
XllPlus Namespace


ExportedName Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.ExportedName Property
XllFunctionAttribute Class See Also Send Feedback
The name of the function as it will appear in Excel.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string ExportedName { get; set; }
Visual Basic (Declaration)
Public Property ExportedName As String
Visual C++
public:
property String^ ExportedName {
    String^ get ();
    void set (String^ value);
}

See Also

XllFunctionAttribute Class
XllPlus Namespace


Flags Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.Flags Property
XllFunctionAttribute Class See Also Send Feedback
The set of flags that control the behavior of the exported add-in function.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XlFunctionFlags Flags { get; set; }
Visual Basic (Declaration)
Public Property Flags As XlFunctionFlags
Visual C++
public:
property XlFunctionFlags Flags {
    XlFunctionFlags get ();
    void set (XlFunctionFlags value);
}

See Also

XllFunctionAttribute Class
XllPlus Namespace


NameToUpperCase Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.NameToUpperCase Property
XllFunctionAttribute Class See Also Send Feedback
Sets whether the exported name is forced to upper case.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public TriValue NameToUpperCase { get; set; }
Visual Basic (Declaration)
Public Property NameToUpperCase As TriValue
Visual C++
public:
property TriValue NameToUpperCase {
    TriValue get ();
    void set (TriValue value);
}

See Also

XllFunctionAttribute Class
XllPlus Namespace


Prefix Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.Prefix Property
XllFunctionAttribute Class See Also Send Feedback
The prefix that will appear before the function's name in Excel.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string Prefix { get; set; }
Visual Basic (Declaration)
Public Property Prefix As String
Visual C++
public:
property String^ Prefix {
    String^ get ();
    void set (String^ value);
}

See Also

XllFunctionAttribute Class
XllPlus Namespace


ReturnsHandle Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.ReturnsHandle Property
XllFunctionAttribute Class See Also Send Feedback
Controls whether the function will return a handle instead of a standard value or array of values.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public TriValue ReturnsHandle { get; set; }
Visual Basic (Declaration)
Public Property ReturnsHandle As TriValue
Visual C++
public:
property TriValue ReturnsHandle {
    TriValue get ();
    void set (TriValue value);
}

See Also

XllFunctionAttribute Class
XllPlus Namespace


ShouldExport Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.ShouldExport Property
XllFunctionAttribute Class See Also Send Feedback
Controls whether the function is exported.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public TriValue ShouldExport { get; set; }
Visual Basic (Declaration)
Public Property ShouldExport As TriValue
Visual C++
public:
property TriValue ShouldExport {
    TriValue get ();
    void set (TriValue value);
}

See Also

XllFunctionAttribute Class
XllPlus Namespace


Tag Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.Tag Property
XllFunctionAttribute Class See Also Send Feedback
A string value which is passed to the code generator. (For internal use only.)

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string Tag { get; set; }
Visual Basic (Declaration)
Public Property Tag As String
Visual C++
public:
property String^ Tag {
    String^ get ();
    void set (String^ value);
}

See Also

XllFunctionAttribute Class
XllPlus Namespace


TemplateName Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.TemplateName Property
XllFunctionAttribute Class See Also Send Feedback
The name of the code template to be used in generating this add-in function. (For internal use only.)

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string TemplateName { get; set; }
Visual Basic (Declaration)
Public Property TemplateName As String
Visual C++
public:
property String^ TemplateName {
    String^ get ();
    void set (String^ value);
}

See Also

XllFunctionAttribute Class
XllPlus Namespace


Versions Property

[image]

XLL+ .NET Runtime Class Library
XllFunctionAttribute..::.Versions Property
XllFunctionAttribute Class See Also Send Feedback
The Excel versions for which code will be generated.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XlVersions Versions { get; set; }
Visual Basic (Declaration)
Public Property Versions As XlVersions
Visual C++
public:
property XlVersions Versions {
    XlVersions get ();
    void set (XlVersions value);
}

See Also

XllFunctionAttribute Class
XllPlus Namespace


XllIgnoreAttribute Class

[image]

XLL+ .NET Runtime Class Library
XllIgnoreAttribute Class
Members See Also Send Feedback
Prevents a method or property from being exported.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public class XllIgnoreAttribute : XllFunctionAttribute,
    ICloneable
Visual Basic (Declaration)
Public Class XllIgnoreAttribute _
    Inherits XllFunctionAttribute _
    Implements ICloneable
Visual C++
public ref class XllIgnoreAttribute : public XllFunctionAttribute,
    ICloneable

Remarks

Use this attribue to prevent the export of a method or property that would otherwise be exported due to the fileter settings of the declaring type or containing assembly.

Inheritance Hierarchy

System..::.Object
System..::.Attribute
XllPlus..::.XllFunctionAttribute
XllPlus..::.XllIgnoreAttribute

See Also

XllIgnoreAttribute Members
XllPlus Namespace


XllIgnoreAttribute Members

[image] [image]

XLL+ .NET Runtime Class Library
XllIgnoreAttribute Members
XllIgnoreAttribute Class Constructors Methods See Also Send Feedback

The XllIgnoreAttribute type exposes the following members.

Constructors

Name | Description
XllIgnoreAttribute | Creates a new XllIgnoreAttribute object.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.

See Also

XllIgnoreAttribute Class
XllPlus Namespace


XllIgnoreAttribute Constructor

[image]

XLL+ .NET Runtime Class Library
XllIgnoreAttribute Constructor
XllIgnoreAttribute Class See Also Send Feedback
Creates a new XllIgnoreAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllIgnoreAttribute()
Visual Basic (Declaration)
Public Sub New
Visual C++
public:
XllIgnoreAttribute()

See Also

XllIgnoreAttribute Class
XllPlus Namespace


XllIgnoreAttribute Methods

[image] [image]

XLL+ .NET Runtime Class Library
XllIgnoreAttribute Methods
XllIgnoreAttribute Class See Also Send Feedback

The XllIgnoreAttribute type exposes the following members.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.

See Also

XllIgnoreAttribute Class
XllPlus Namespace


Clone Method

[image]

XLL+ .NET Runtime Class Library
XllIgnoreAttribute..::.Clone Method
XllIgnoreAttribute Class See Also Send Feedback
Returns a deep copy of the current instance.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public Object Clone()
Visual Basic (Declaration)
Public Function Clone As Object
Visual C++
public:
virtual Object^ Clone() sealed

Return Value

A new XllIgnoreAttribute object, whose properties are all equal in value to this.

Implements

ICloneable..::.Clone()()()

See Also

XllIgnoreAttribute Class
XllPlus Namespace


XllMacroAttribute Class

[image]

XLL+ .NET Runtime Class Library
XllMacroAttribute Class
Members See Also Send Feedback
Declares a method to be available as a command macro in Excel.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public class XllMacroAttribute : XllFunctionAttribute,
    IComparable, ICloneable
Visual Basic (Declaration)
Public Class XllMacroAttribute _
    Inherits XllFunctionAttribute _
    Implements IComparable, ICloneable
Visual C++
public ref class XllMacroAttribute : public XllFunctionAttribute,
    IComparable, ICloneable

Inheritance Hierarchy

System..::.Object
System..::.Attribute
XllPlus..::.XllFunctionAttribute
XllPlus..::.XllMacroAttribute

See Also

XllMacroAttribute Members
XllPlus Namespace


XllMacroAttribute Members

[image] [image]

XLL+ .NET Runtime Class Library
XllMacroAttribute Members
XllMacroAttribute Class Constructors Methods Properties See Also Send Feedback

The XllMacroAttribute type exposes the following members.

Constructors

Name | Description
XllMacroAttribute | Overloaded.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.
Compare | Compares two XllMacroAttribute instances.
IsDefault | Returns whether the attribute's properties are all set to default values.

Properties

Name | Description
MenuCaption | Text of the menu item for the command.
MenuResourceId | Resource ID of the text resource for the menu item.

See Also

XllMacroAttribute Class
XllPlus Namespace


XllMacroAttribute Constructor

[image] [image]

XLL+ .NET Runtime Class Library
XllMacroAttribute Constructor
XllMacroAttribute Class See Also Send Feedback

Overload List

Name | Description
XllMacroAttribute()()() | Creates a new XllMacroAttribute object.
XllMacroAttribute(String) | Creates a new XllMacroAttribute object.
XllMacroAttribute(String, Int32, String) | Creates a new XllMacroAttribute object.

See Also

XllMacroAttribute Class
XllMacroAttribute Members
XllPlus Namespace


XllMacroAttribute Constructor

[image]

XLL+ .NET Runtime Class Library
XllMacroAttribute Constructor
XllMacroAttribute Class See Also Send Feedback
Creates a new XllMacroAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllMacroAttribute()
Visual Basic (Declaration)
Public Sub New
Visual C++
public:
XllMacroAttribute()

See Also

XllMacroAttribute Class
XllMacroAttribute Overload
XllPlus Namespace


XllMacroAttribute Constructor (String)

[image]

XLL+ .NET Runtime Class Library
XllMacroAttribute Constructor (String)
XllMacroAttribute Class See Also Send Feedback
Creates a new XllMacroAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllMacroAttribute(
    string menuCaption
)
Visual Basic (Declaration)
Public Sub New ( _
    menuCaption As String _
)
Visual C++
public:
XllMacroAttribute(
    String^ menuCaption
)

Parameters

menuCaption
Type: System..::.String
Text of the menu item for the command.

See Also

XllMacroAttribute Class
XllMacroAttribute Overload
XllPlus Namespace


XllMacroAttribute Constructor (String, Int32, String)

[image]

XLL+ .NET Runtime Class Library
XllMacroAttribute Constructor (String, Int32, String)
XllMacroAttribute Class See Also Send Feedback
Creates a new XllMacroAttribute object.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllMacroAttribute(
    string menuCaption,
    int menuResourceId,
    string description
)
Visual Basic (Declaration)
Public Sub New ( _
    menuCaption As String, _
    menuResourceId As Integer, _
    description As String _
)
Visual C++
public:
XllMacroAttribute(
    String^ menuCaption,
    int menuResourceId,
    String^ description
)

Parameters

menuCaption
Type: System..::.String
Text of the menu item for the command.
menuResourceId
Type: System..::.Int32
Resource ID of the text resource for the menu item.
description
Type: System..::.String
Help text for the command.

See Also

XllMacroAttribute Class
XllMacroAttribute Overload
XllPlus Namespace


XllMacroAttribute Methods

[image] [image]

XLL+ .NET Runtime Class Library
XllMacroAttribute Methods
XllMacroAttribute Class See Also Send Feedback

The XllMacroAttribute type exposes the following members.

Methods

Name | Description
Clone | Returns a deep copy of the current instance.
Compare | Compares two XllMacroAttribute instances.
IsDefault | Returns whether the attribute's properties are all set to default values.

See Also

XllMacroAttribute Class
XllPlus Namespace


Clone Method

[image]

XLL+ .NET Runtime Class Library
XllMacroAttribute..::.Clone Method
XllMacroAttribute Class See Also Send Feedback
Returns a deep copy of the current instance.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public Object Clone()
Visual Basic (Declaration)
Public Function Clone As Object
Visual C++
public:
virtual Object^ Clone() sealed

Return Value

A new XllMacroAttribute object, whose properties are all equal in value to this.

Implements

ICloneable..::.Clone()()()

See Also

XllMacroAttribute Class
XllPlus Namespace


Compare Method

[image]

XLL+ .NET Runtime Class Library
XllMacroAttribute..::.Compare Method
XllMacroAttribute Class See Also Send Feedback
Compares two XllMacroAttribute instances.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public int Compare(
    XllMacroAttribute other
)
Visual Basic (Declaration)
Public Function Compare ( _
    other As XllMacroAttribute _
) As Integer
Visual C++
public:
int Compare(
    XllMacroAttribute^ other
)

Parameters

other
Type: XllPlus..::.XllMacroAttribute
A second instance to be compared to this.

Return Value

-1 if this is less than other. 0 if the two are equal. 1 if this is greater than other.

See Also

XllMacroAttribute Class
XllPlus Namespace


IsDefault Method

[image]

XLL+ .NET Runtime Class Library
XllMacroAttribute..::.IsDefault Method
XllMacroAttribute Class See Also Send Feedback
Returns whether the attribute's properties are all set to default values.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public bool IsDefault()
Visual Basic (Declaration)
Public Function IsDefault As Boolean
Visual C++
public:
bool IsDefault()

Return Value

True if all properties are at their default values. False if any property has a non-default value.

See Also

XllMacroAttribute Class
XllPlus Namespace


XllMacroAttribute Properties

[image] [image]

XLL+ .NET Runtime Class Library
XllMacroAttribute Properties
XllMacroAttribute Class See Also Send Feedback

The XllMacroAttribute type exposes the following members.

Properties

Name | Description
MenuCaption | Text of the menu item for the command.
MenuResourceId | Resource ID of the text resource for the menu item.

See Also

XllMacroAttribute Class
XllPlus Namespace


MenuCaption Property

[image]

XLL+ .NET Runtime Class Library
XllMacroAttribute..::.MenuCaption Property
XllMacroAttribute Class See Also Send Feedback
Text of the menu item for the command.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public string MenuCaption { get; set; }
Visual Basic (Declaration)
Public Property MenuCaption As String
Visual C++
public:
property String^ MenuCaption {
    String^ get ();
    void set (String^ value);
}

See Also

XllMacroAttribute Class
XllPlus Namespace


MenuResourceId Property

[image]

XLL+ .NET Runtime Class Library
XllMacroAttribute..::.MenuResourceId Property
XllMacroAttribute Class See Also Send Feedback
Resource ID of the text resource for the menu item.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public int MenuResourceId { get; set; }
Visual Basic (Declaration)
Public Property MenuResourceId As Integer
Visual C++
public:
property int MenuResourceId {
    int get ();
    void set (int value);
}

See Also

XllMacroAttribute Class
XllPlus Namespace


XlVersions Enumeration

[image]

XLL+ .NET Runtime Class Library
XlVersions Enumeration
See Also Send Feedback
Describes the versions for which code will be specifically generated.

Namespace: XllPlus
Assembly: Psl.XL7.XnReflect.Runtime (in Psl.XL7.XnReflect.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public enum XlVersions
Visual Basic (Declaration)
Public Enumeration XlVersions
Visual C++
public enum class XlVersions

Members

Member name | Description
Excel2003AndBelow | Excel 2003 and below (including Excel XP, Excel 2000 and Excel 97).
Excel2007AndAbove | Excel 2007 and above.
AllExcelVersions | All versions of Excel.
Default | The default setting, as specified in an assembly or class attribute.

See Also

XllPlus Namespace


XLL Wrapper Generator

[image]

XLL Wrapper
XLL Wrapper Generator
See Also Send Feedback

This toolkit contains tools, a runtime library, samples and documentation to help with the development of COM modules and .NET assemblies that wrap Excel XLL add-ins. The add-in functions in the library are available as COM and .NET methods to client programs that use the wrapper modules.

The wrapper objects can be used by clients written in any development environment that supports COM or .NET, including C++, Java, C#, Visual Basic and VBA.

Each add-in library is wrapped in a single class, which has one public method for each add-in function. For example, an XLL add-in named MatrixTools.xll, containing 3 methods, might produce a .NET class such as:

CopyC#
class MatrixTools
{
    public bool MatrixIsSkewSymmetric(double[,] M);
    public double[,] LUDecomposition(double[,] A, double[,] L, double[,] U);
    public double EuroDateDiff(DateTime Start, DateTime End);
}

The wrapped methods can have strongly-typed signatures that are more precise than the Excel add-in functions that they wrap. In the examples above:

  • Inputs can be dates - rather than just the numbers used in Excel.
  • Return types can be specified.
  • Where an add-in function might return "#VALUE!" for an error, the wrapper function can instead throw an exception.

In This Section

Getting Started
A guide to get you started using XLL Wrapper Generator.
Walkthroughs
Walkthroughs that show you how to create, build and test wrapper libraries.
Samples
Sample applications.
Information files
Information files are used to control the wrapper code generator. An information file can be used to override and fine-tune the signatures and behavior of the generated wrapper functions.
Tools
References for the XLL wrapper command-line tools.

See Also

Reference

XllPlus.ComWrappers.Runtime


Getting Started with XLL Wrapper Generator

[image]

XLL Wrapper
Getting Started with XLL Wrapper Generator
See Also Send Feedback

The topics listed below contain the essentials for getting you started with XLL Wrapper Generator.

You may prefer to follow the guided walkthroughs that show you step-by-step how to create, build and use an XLL wrapper library.

In This Section

Creating a wrapper project
How to create a Visual Studio project for a wrapper library.
Model files
How to create a model file, which defines the functions in an XLL add-in.
Wrapper classes
An introduction to the wrapper classes, and how to use them.
Client applications
How to develop client applications that call the wrapper classes.
Information files
An introduction to wrapper information files, which can be used by the developer to fine-tune and enrich the wrapper functions that are generated.
The build process
Describes the process used to generate code and build the wrapper library.
Deploying wrapper libraries
Lists the requirements for deploying wrapper libraries to users' machines.

See Also

Other Resources

XLL Wrapper Generator


Creating a wrapper project
See Also Send Feedback

Use the XLL+ Wrapper Project Wizard to create the XLL wrapper project.

Creating a wrapper project

  1. Open an XLL+ add-in project.

  2. In the Project Explorer, right-click on the Solution node, and select Add/New Project....

    Add New Project to Solution

  3. In the Add New Project dialog, select the Visual C#/XLL+ node in the Project Types tree, and select XLL+ Wrapper in the Templates list.

    Name the project and click OK.

  4. In the XLL+ Wrapper Wizard, eneter your preferred names for the wrapper class and its namespace, and click OK.

  5. You will see that a new project, containing one C# file and two XML files, has been created and added to the solution.

The next step is to save a Model file.

See Also

Other Resources

Model files
XLL Wrapper Generator
Getting Started


Model files

[image]

XLL Wrapper
Model files
See Also Send Feedback

The model file is an XML file which contains details of the signatures of add-in functions, along with the help text for functions and their arguments.

You should never make changes by hand to the model file, since it will be overwritten each time it is exported.

The Wizard creates an empty model file when the wrapper project is created; it is the developer's responsibility to update it.

Saving a model file for an XLL+ project

A model file can be generated from an XLL+ project by using the "Tools/Export to XML…" command in the XLL Add-ins window.

The model file should be saved as [XllProjectName].model.xml (where [XllProjectName] is the name of the C++ project containing the add-in functions), in the directory containing the COM wrapper project, overwriting the existing file.

Updating the model file

  1. Open a C++ source file from the XLL+ Add-in project.

  2. Activate the XLL Add-ins window. If it is not currently visible, use the menu command View/Other Windows/XLL Add-ins Window to display it.

  3. Click the Set Help topic identifiers command in the Tools menu of the XLL Add-ins window.

  4. Click the Export to XML... command in the Tools menu of the XLL Add-ins window.

  5. In the Export to XML window, click on the browse (...) button in the Save As panel.

    Navigate to the wrapper project directory and save the file as [WrapperProjectName].model.xml (substituting the correct wrapper project name); click Yes when you are asked whether you want to replace the existing file.

  6. In the Export to XML window, press OK to generate the model file.

    After the file is saved, you will be asked whether you want to open the file. Unless you are interested in inspecting the XML file at this point, click No.

  7. You should repeat this process whenever you add a new add-in function to the Excel add-in, or change the signature of an existing function.

The wrapper project is now complete. You can now build and test the wrapper library.

Creating a model file for an XLL from any other source

Model files can also be generated for XLL's from other sources, by using the XLLQUERY command-line tool.

See Also

Other Resources

Wrapper classes
XLL Wrapper Generator
Getting Started


Wrapper classes

[image]

XLL Wrapper
Wrapper classes
See Also Send Feedback

This topic contains the following sections.

  • Overview of wrapper classes
  • Engine
  • Initializing the engine
  • Output files
  • See Also

Overview of wrapper classes

For each XLL which is to be called from a client application, a wrapper library is generated.

The command line tool CWGENCLS generates all the code for the wrapper library. For each XLL, two classes are generated: one is for use from Visual Basic for Applications (VBA) - which has a limited implementation of the COM interface - and the other is for use from all other development environments. The add-in functions of the XLL are exposed as methods of each wrapper class.

Wrapper libraries are authored in C#. A simple wrapper class might look like this:

CopyC#
namespace Planatech.Demos
{
    /// <summary>
    /// A lightweight wrapper object which supports calls to a set of Excel add-in functions.
    /// </summary>
    /// <remarks>
    /// This class is designed for use by standard COM clients.
    /// </remarks>
    [ComVisible(true)]
    [Guid("2d42a1e1-3659-4869-81fc-36e7ad4b0889")]
    [ComDefaultInterface(typeof(IApiTest))]
    [Description("A lightweight wrapper class which supports calls to a set of Excel add-in functions.")]
    public class ApiTest : AddinWrapperBase, IApiTest
    {
        #region Construction
        /// <summary>
        /// Constructs a new instance of ApiTest.
        /// </summary>
        /// <remarks>
        /// The object is not ready for use until the Engine property has been set.
        /// </remarks>
        public ApiTest() { }
        #endregion

        #region Error handling
        private string[] errorPrefixes = new string[] { "#Error:" };
        #endregion

        #region Wrapped Excel add-in functions

        /// <summary>
        /// Returns the sum of two numbers
        /// </summary>
        /// <param name="A">is the first number</param>
        /// <param name="B">is the second number</param>
        /// <exception cref="XllWrapperException">Will be thrown if any errors occur in the call to Excel,
        /// or if the add-in function returns an error value.</exception>
        [Description("Returns the sum of two numbers")]
        [DispId(1002)]
        public double ScalarAdd(double A, double B)
        {
            CheckEngine();
            object res__ = Engine.CallExcelWithErrorCheck("ScalarAdd", true, errorPrefixes, A, B);
            return (double)Unwrap(res__, typeof(double));
        }

        #endregion
    }
}

Notice that all the help text from the add-in functions has been copied into the C# comments, so that developers who use the wrapper class will get the benefit of on-line help and Intellisense.

A number of COM attributes are set for the class, to make it fully available in COM client environments, as well as from .NET clients.

Every wrapper class is derived from AddinWrapperBase, which contains a number of methods used for doing common tasks and one important property: Engine.

Engine

Each of the wrapper methods delegates the actual work of calling the XLL method to an engine, which is represented by the IWrapperEngine interface. There are two available implementations of IWrapperEngine available:

  1. XllPlus.ComWrappers.Runtime..::.ExcelWrapperEngine uses an instance of Excel to execute the XLL add-in function. The Excel instance is fully controlled by the engine: it is invisible to the user, and it is closed by the engine when it is no longer required.
  2. XllHostWrapperEngine uses an instance of XLL Host. This engine should be used when Excel cannot be available on a computer or when Excel is considered too unstable to be part of an application stack.

The code in the wrapper class is ignorant of which engine is being used; the same wrapper classes can be used with any engine class that implements IWrapperEngine.

A wrapper class cannot be used until its Engine property has been set to a valid instance of IWrapperEngine. A typical pattern of use for a wrapper class (which is a very light-weight object) is shown below.

CopyC#
ExcelWrapperEngine theEngine = new ExcelWrapperEngine();

...

using (ApiTest wrapper = new ApiTest())
{
    wrapper.Engine = theEngine;
    try
    {
        double dResult = wrapper.ScalarAdd(1.23, 4.56);
        ...
    }
    catch(XllWrapperException ex)
    {
        ...
    }
}

The wrapper object is automatically disposed at the end of the using block.

Initializing the engine

ExcelWrapperEngine is a heavy-weight object, (since it can own an invisible instance of Excel) and so it should be created and destroyed with care.

It must be initialized before it can be used with a wrapper object. In environments other than VBA, a typical pattern is:

CopyC#
ExcelWrapperEngine theEngine = new ExcelWrapperEngine();
theEngine.Create();
theEngine.LoadXll(theXllFileName);

... Use the engine ...

theEngine.Destroy();

A wrapper object cannot be used until the XLL containing its add-in functions has been loaded. LoadXll is used for this purpose. The developer is responsible for specifying the full path to the XLL file. If the XLL is deployed to the same directory as the wrapper assembly, then for an XLL named ApiTest.xll and a wrapper class named ApiTest you can use code such as this:

CopyC#
string theXllFileName = Path.Combine(
    Path.GetDirectoryName(typeof(ApiTest).Assembly.Location),
    "ApiTest.xll");

Output files

When the add-in project is built, there are three output files of interest:

Assembly
This is a .NET assembly that contains the code for the wrapper. For a wrapper library named ApiTest, the file is named ApiTest.dll.
Type library
This is a COM type library file that exports all the function definitions for COM clients, including VBA. It has the extension "tlb", e.g. ApiTest.tlb.
Documentation
This is an XML file that contains the documentation for the wrapper library. This will be available to .NET client application developers as Intellisense help in Visual Studio. It has the extension "xml", e.g. ApiTest.xml.

See Also

Other Resources

Information files
Getting Started


Information files

[image]

XLL Wrapper
Information files
See Also Send Feedback

An information file contains instructions for the CWGENCLS utility. When you create a new XLL Wrapper project, an information file is created for you, and is added to the project.

For full details see the Schema reference.

This topic contains the following sections.

  • Purpose of an information file
  • Example of an information file
  • Content
  • See Also

Purpose of an information file

An information file allows the developer to fine-tune the signature and behavior of a wrapped add-in function.

Return type and Error handling

Excel add-in functions typically do not have a fixed return type, since they can often return error values. Methods in other programming environments should have fixed return types, and should throw an exception if an error occurs.

By using the ReturnType attribute of the Function element, a developer can enforce this behavior. If the add-in function returns the expected return type, it will be converted and returned to the caller of the wrapper function. If the return type is an error value, or a string containing an error message, then an exception of type XllWrapperException will be thrown.

CopyXML
<Function ExportedName="COEFF.EXPAND"
          ReturnType="double"/>

If there are any special string return values that you wish to treat as errors, use the ErrorPrefix element:

CopyXML
<Function ExportedName="Code2Name">
    <ErrorPrefixes>
        <ErrorPrefix>Not found</ErrorPrefix>
        <ErrorPrefix>#ERROR</ErrorPrefix>
    </ErrorPrefixes>
</Function>

Names

The name and namespace of the wrapper classes can be controlled with the Client element.

CopyXML
<Client Type="COM"
        Namespace="MyCompany.Analytics"
        Class="Materials"
        ... />

The name of a wrapper function and of its arguments can be controlled using the WrappedName attribute.

CopyXML
<Function ExportedName="COEFF.EXPAND" WrappedName="CoefficientOfExpansion">
  <Argument Name="X" WrappedName="xCoord"/>
</Function>

Signature

The types of each argument can be overridden using the Argument element's IsDate or Type attributes.

CopyXML
<Function ExportedName="DateMatrix" ReturnType="DateTime[,]">
  <Argument Name="Dates" IsDate="1"/>
</Function>

Example of an information file

A simple example of an information file is shown below.

CopyXML
<?xml version="1.0" encoding="utf-8"?>
<XllWrapper Name="MyAddin">
  <Clients>
    <Client Type="COM"
            Namespace="MyNamespace"
            Class=" MyAddin"
            ClassGuid="51922C8E-F57D-485F-91AD-7B6FB01E046B"
            Interface="IMyAddin"
            InterfaceGuid="F665828B-9914-41E5-9B74-42505F67A88D"/>
    <Client Type="VBA"
            Namespace="MyNamespace"
            Class="MyAddinVba"
            ClassGuid="14636546-A5DE-40F9-B02B-1847BC47C9E5"
            Interface="IMyAddinVba"
            InterfaceGuid="7CBD1C10-C089-4D34-8BC4-633B729C49C1"/>
  </Clients>
  <Functions>
    <Function ExportedName="MyAddin_VersionInfo"
              Wrap="Always"
              ReturnType="string[,]"/>
  </Functions>
</XllWrapper>

Content

Client element

The Client element defines a single wrapper class that will be generated.

An instruction file normally contains two Client elements, one with type VBA - for use in Visual Basic for Applications - and other with type COM - for use with all other COM and .NET clients.

The developer can change the class name of the wrapper class, and also the namespace.

Guids (globally unique identifiers) are supplied when the information file is created, and should not usually be changed afterwards.

See also Client element in the schema reference.

Function element

The Function element contains instructions for wrapping a single add-in function. These instructions will enrich or override the data in the model file. Some of the attributes of the function element are summarized below.

The element can also contain any number of Argument elements and, optionally, an ErrorPrefixes element.

Attribute | Required | Description | Examples
ExportedName | Required | The name of the function , as it appears in the model file. | NORMSINV2
Wrap Optional One of: Always, Never, Default. Controls whether the specified function will be wrapped. If omitted, Default will be assumed.

Always

Never

Default
ReturnType Optional The expected return type of the add-in function. This should be a C# scalar type or array type.

string

double[]

int[,]
WrappedName | Optional | The name of the function as it will appear in the wrapper method. | NormsInv2

See also Function element in the schema reference.

Argument element

An Argument element is an optional element which controls the wrapping of a single named argument. These instructions will enrich or override the data in the model file. Some of the attributes of the argument element are summarized below.

Attribute | Required | Description | Example(s)
Name | Required | The name of the argument as it appears in the Name attribute of the XlArgument element in the model file. | X
IsDate Optional One of: 0, 1. If 1, then the argument will be treated as a date (or an array of dates). In the wrapper class, the argument's type will be DateTime (or DateTime[] or DateTime[,] for an array). If 0 or omitted, then the argument's type will be treated normally.

0

1
WrappedName | Optional | The name of the function as it will appear in the wrapper method. | nItemCount
Type Optional

The argument type, as it will appear in the C# wrapper function.

Only the following basic types are supported: bool, DateTime, double, int, string, object. The type may be a scalar (e.g. int), a vector (e.g. int[]) or a matrix (e.g. int[,]).

An argument that accepts a vector or matrix of mixed types should use object[] or object[,] respectively. An argument that accepts a variety of different input types should use object.

string

double[]

int[,]

See also Argument element in the schema reference.

See Also

Other Resources

The build process
Getting Started
Information file schema reference


The build process

[image]

XLL Wrapper
The build process
See Also Send Feedback

The wrapper project contains a special build step, which calls the command-line tool CWGENCLS. This combines the model file with the instructions in the information file and generates a C# source code file containing the wrapper functions.

This step will be run as part of the build:

  • If the model file has changed. Thus, if you add a new function to your add-in, or change the signature of an existing function, you should update the model file, and the wrapper library will be synchronized next time the project is built.
  • If the information file has changed.
  • If the project is fully built with "Rebuild".

See Also

Other Resources

Client applications
Getting Started


Client applications

[image]

XLL Wrapper
Client applications
See Also Send Feedback

This topic examines the requirements for client applications that use XLL wrapper assemblies.

This topic contains the following sections.

  • .NET clients
  • COM clients
  • VBA clients
  • See Also

.NET clients

The XLL wrapper assembly is a well-behaved .NET assembly. It can be used just like any other .NET DLL assembly.

References

Applications that use wrapper objects need two references: one for the wrapper library, and one for the XLL+ wrapper support classes. In each case the reference should be to the assembly (.dll) file.

In Visual Studio, Use the Add Reference... menu to open the Add Reference dialog. Select the Browse tab, and navigate to the directory containing the assembly.

The wrapper objects' assembly will be in the wrapper project's output directory (either bin\release or bin\debug), and will have the extension .dll, e.g. MyAddin.dll.

A copy of the XLL+ wrapper support classes' assembly, XllPlus.ComWrappers.Runtime.dll, can be found in the same directory as the wrapper assembly.

Initializing the engine

You should initialize the engine using Create. Remember that the engine will create an invisible instance of Excel, so do not create and destroy When you have finished with the engine, call Destroy.

CopyC#
using XllPlus.ComWrappers.Runtime;

ExcelWrapperEngine engine = new ExcelWrapperEngine();
engine.Create();
engine.LoadXll(theXllFile);

// ... Use the engine ...

engine.Destroy();
Caution:

Remember that the engine will create an invisible instance of Excel, so do not create and destroy engines more often than necessary.

.NET wrapper classes

After creating an instance of a wrapper class, remember to set its Engine property to an initialized engine:

CopyC#
using XllPlus.ComWrappers.Runtime;

ExcelWrapperEngine engine = new ExcelWrapperEngine();

ApiTest api = new ApiTest();
api.Engine = engine;

// ... Use the wrapper class ...

api.Dispose();

Wrapper classes are lightweight, and they support IDisposable, so it is often convenient to put them within a using block:

CopyC#
using XllPlus.ComWrappers.Runtime;

ExcelWrapperEngine engine = new ExcelWrapperEngine();

using (ApiTest api = new ApiTest())
{
    api.Engine = engine;

    // ... Use the wrapper class ...
}

The wrapper object will be disposed automatically at the end of the using block.

For more details see the ApiTest sample.

COM clients

Wrapper assemblies are COM-visible, and all their public methods are also legal COM methods. The instructions below are for COM clients written in Microsoft C++; the implementation details will vary for other client environments and languages.

References

Applications that use wrapper objects need two references: one for the wrapper library, and one for the XLL+ wrapper support classes. In each case the reference should be to the type library (.tlb) file, not to the assembly (.dll) file.

The XLL+ wrapper support classes' type library file, XllPlus.ComWrappers.Runtime.tlb, can be found in the bin sub-directory of the XLL+ installation (e.g. C:\Program Files\Planatech\XllPlus\6.0\VS9.0\bin\XllPlus.ComWrappers.Runtime.tlb). A line such as the following will import it to the C++ application:

CopyC++
#import "C:\Program Files\Planatech\XllPlus\6.0\VS9.0\bin\XllPlus.ComWrappers.Runtime.tlb"

Alternatively, you may prefer to make a copy of the type library in your client project directory, so that you can simply write:

CopyC++
#import "XllPlus.ComWrappers.Runtime.tlb"

The wrapper objects' type library will be in the same directory as the assembly, and will have the extension .tlb, e.g. MyAddin.tlb. You can use code like the following to import it:

CopyC++
#import "..\ApiTestLib\bin\Release\ApiTestLib.tlb"

Initializing the engine

You should initialize the engine using Create. Remember that the engine will create an invisible instance of Excel, so do not create and destroy When you have finished with the engine, call Destroy.

Note:

As usual with COM objects, your pointers should reference the primary interface of the object, i.e. IExcelWrapperEngine.

CopyC++
using namespace XllPlus_ComWrappers_Runtime;

IExcelWrapperEnginePtr engineInstance(__uuidof(ExcelWrapperEngine));
engineInstance->Create();
engineInstance->LoadXll(theXllFile);

// ... Use the engine ...

engineInstance->Destroy();
Caution:

Remember that the engine will create an invisible instance of Excel, so do not create and destroy engines more often than necessary.

COM wrapper classes

The wrapper classes each implement a default interface. The interface's name is, by default, the class name prefixed with I, e.g. IMyAddin for a class MyAddin. As usual in C++ COM programming, your pointers should be to the default interface, not the object.

Special consideration is also needed for the Engine property. You must cast the IExcelWrapperEngine interface to a IWrapperEngine interface explicitly. Take care to drop the reference when it is no longer required.

CopyC++
using namespace XllPlus_ComWrappers_Runtime;

IExcelWrapperEnginePtr engineInstance(__uuidof(ExcelWrapperEngine));
engineInstance->Create();
engineInstance->LoadXll(theXllFile);

// Create IWrapperEngine pointer
IWrapperEnginePtr engine(engineInstance);

try
{
    ApiTestLib::IApiTestPtr api(__uuidof(ApiTestLib::ApiTest));
    api->Engine = engine;

    // ... Use the wrapper object ...
}
catch(_com_error e)
{
    _tprintf(_T("%s\n"), (LPCTSTR)e.Description());
}

engine.Detach();
engineInstance->Destroy();

For more details see the ApiTest sample.

VBA clients

Visual Basic for Applications (VBA), provided as part of Office and Excel, as well as some other applications, requires slightly different handling from standard COM clients.

References

Modules that use wrapper objects need two references: one for the wrapper library, and one for the XLL+ wrapper support classes. In each case the reference should be to the type library (.tlb) file, not to the assembly (.dll) file.

Use the Tools/References... menu to open the References dialog. Then use the Browse... button to navigate to the directory containing the type library.

The XLL+ wrapper support classes' type library file, XllPlus.ComWrappers.Runtime.tlb, will be in the bin sub-directory of the XLL+ installation (e.g. C:\Program Files\Planatech\XllPlus\6.0\VS9.0\bin\XllPlus.ComWrappers.Runtime.tlb).

The wrapper objects' type library will be in the same directory as the assembly, and will have the extension .tlb, e.g. MyAddin.tlb.

Initializing the engine

If you are calling the wrapper library from Excel VBA, then you should initialize the engine using Attach, passing the existing instance of Excel. When you have finished with the engine, call Detach.

CopyVBA
Dim engine As New ExcelWrapperEngine
engine.Attach Application
engine.LoadXll strXllFile

'... Use the engine ...

engine.Detach
Important Note:

You should not call Create from Excel VBA. This will create a new hidden instance of Excel instead of using the current instance.

VBA wrapper classes

VBA supports only a subset of COM's capabilities, so methods designed for use in VBA have to provide special handling for (among other things) arrays and dates. Alongside each wrapper class, a second version, designed only for use from VBA is also generated. If the standard wrapper class is named MyAddin, then the VBA version will be named MyAddinVba.

CopyVBScript
Dim engine As New ExcelWrapperEngine

'... Initialize the engine ...

Dim wrapper As New ApiTestVba
Set wrapper.engine = engine

'... Use the wrapper object ...

For more details see the ApiTest sample.

See Also

Other Resources

Deploying wrapper libraries
Getting Started


Deploying wrapper libraries

[image]

XLL Wrapper
Deploying wrapper libraries
See Also Send Feedback

To deploy the wrapper libraries to a user’s machine you need to deploy the following files:

  1. The XLL add-in (.xll) and its compiled help file (.chm).
  2. The wrapper assembly (.dll).
  3. The wrapper assembly’s type library (.tlb).
  4. XLL+ Wrapper runtime files: XllPlus.ComWrapper.Runtime.dll and XllPlus.ComWrapper.Runtime.tlb.

XLL Add-in

The compiled help file (.chm) should always be delivered to the same directory as the XLL file.

It is often convenient to deploy the XLL to the same directory as the wrapper assembly. Then you can use simple code to find it when it needs to be loaded, e.g.:

CopyC#
string theXllFileName = Path.Combine(
    Path.GetDirectoryName(typeof(ApiTest).Assembly.Location),
    "ApiTest.xll");

Wrapper assemblies

If you are calling the wrapper assembly from a COM client, you should usually distribute the type library file (.tlb) alongside the assembly (.dll) file.

If you are calling the wrapper assembly from a COM client, you must register the assembly as a COM module using regasm. Depending on your security policies, you may also need to sign the wrapper assembly, or add it to the GAC.

Runtime libraries

You must make the runtime library XllPlus.ComWrapper.Runtime.dll available.

If you are calling the wrapper assembly from a COM client, you should usually distribute the runtime type library file XllPlus.ComWrapper.Runtime.tlb alongside the assembly file.

If you are calling the wrapper assembly from a COM client, you must register the runtime assembly as a COM module using regasm.

You may find it convenient to add the runtime assembly to the GAC. If not, you should ensure a copy of the assembly is accessible to the client program (usually by placing it in the same directory as the client application).

Excel

A program that uses the ExcelWrapperEngine engine must run on a computer with Excel 2003 or above installed.

You will also need to enable the user’s version of Excel to use the .NET version 2 run-time libraries. See Loading the correct .NET runtime version for more information.

Finally, the Microsoft Office Primary Interop Assemblies, version 11, must be installed on the user’s machine.

See Also

Other Resources

Getting Started


Walkthroughs

[image]

XLL Wrapper
Walkthroughs
See Also Send Feedback

This section contains walkthroughs that show you step-by-step how to create, build and use an XLL wrapper library.

In This Section

Creating a wrapper for an add-in built using XLL+
How to create a wrapper library for an Excel add-in developed using the XLL+ toolkit.

See Also

Other Resources

Samples
Getting Started


Creating a wrapper for an add-in built using XLL+

[image]

XLL Wrapper
Creating a wrapper for an add-in built using XLL+
See Also Send Feedback

If you have developed an Excel add-in using the XLL+ toolkit, follow the steps below to create a wrapper library for the add-in.

You will also learn how to improve the signatures of the wrapper functions, and how to write a client application that uses the wrapper objects and functions.

This topic contains the following sections.

  • Setting up a wrapper project
  • Customizing the information file
  • Client application
  • See Also

Setting up a wrapper project

Creating a wrapper project

  1. Open an XLL+ add-in project. For the purposes of this walk-through, we will use the Tutorial1 sample project.

    In Visual Studio, open the solution Tutorial1.sln, which can be found in the samples\Tutorial1 sub-directory of your XLL+ installation.

  2. In the Project Explorer, right-click on the Solution node, and select Add/New Project....

    Add New Project to Solution

  3. In the Add New Project dialog, select the Visual C#/XLL+ node in the Project Types tree, and select XLL+ Wrapper in the Templates list.

    Name the project Tutorial1Wrapper and click OK.

  4. In the XLL+ Wrapper Wizard, click OK.

  5. You will see that a new project, containing one C# file and two XML files, has been created and added to the solution.

Updating the model file

  1. Open the file Tutorial1.cpp in the Tutorial1 project.

  2. Activate the XLL Add-ins window. If it is not currently visible, use the menu command View/Other Windows/XLL Add-ins Window to display it.

  3. Click the Set Help topic identifiers command in the Tools menu of the XLL Add-ins window.

  4. Click the Export to XML... command in the Tools menu of the XLL Add-ins window.

  5. In the Export to XML window, click on the browse (...) button in the Save As panel.

    Navigate to the Tutorial1Wrapper project directory and save the file as Tutorial1.model.xml, clicking Yes when you are asked whether you want to replace the existing file.

  6. In the Export to XML window, press OK to generate the model file.

    After the file is saved, you will be asked whether you want to open the file. Unless you are interested in inspecting the XML file at this point, click No.

  7. You should repeat this process whenever you add a new add-in function to the Excel add-in, or change the signature of an existing function.

The wrapper project is now complete. You can now build and test the wrapper library. Make sure that the build is set to either "Win32" or "x64"; avoid "Mixed Platforms". Also, if necessary, use the Build/Configuration Manager... command to open the solution configuration window, and ensure that both projects have a tick in the "Build" column.

Customizing the information file

Specifying the return type of a function

  1. Open the file Tutorial1.cs in the Tutorial1Wrapper project. This contains the generated wrapper classes and their methods.

    Caution:

    You should never edit this file, because it will be overwritten every time the add-in project is changed.

    Within class Tutorial1, locate the wrapper method NORMSINV2. At present it looks as follows:

    CopyC#
    public object NORMSINV2(double Probability)
{
    CheckEngine();
    return Engine.CallExcelWithErrorCheck("NORMSINV2", true, errorPrefixes, Probability);
}

    The add-in function returns either a number, or an error message. The preferred behavior outside Excel is to always return a type double, and throw an exception if an error message is returned. We can edit the information file to get this behavior.

  2. Open the file Tutorial1.wrapper.xml in the Tutorial1Wrapper project. You will see that within the outer element <XllWrapper> there are three sections:

    1. A <Clients> element contains specifications of the C# wrapper classes that will be generated.
    2. An <ErrorPrefixes> element contains a list of return values that will be treated as errors.
    3. The <Functions> element contains a list of named functions, whose signature and behavior can be controlled.

  3. At the end of the <Functions> element add a new <Function> element for NORMSINV2, as follows:

    CopyXML
    <Functions>
  <Function ExportedName="Tutorial1_VersionInfo" Wrap="Never" ReturnType="string[,]"/>
  <Function ExportedName="NORMSINV2" ReturnType="double"/>
</Functions>

  4. Press Shift+Ctrl+B to rebuild the project. The code in Tutorial1.cs will be regenerated. If we inspect the wrapper method NORMSINV2 again, we will see that it now looks as follows:

    CopyC#
    public double NORMSINV2(double Probability)
{
    CheckEngine();
    object res__ = Engine.CallExcelWithErrorCheck("NORMSINV2", true, errorPrefixes, Probability);
    return (double)Unwrap(res__, typeof(double));
}

    With this change, the wrapper function is now much more useful, since it is strongly typed and handles errors as expected. If the function fails for any reason, an exception of type XllWrapperException will be thrown.

Omitting functions

  1. Open Tutorial1.wrapper.xml, and add three more elements just before the end of the <Functions> element as shown below.

    CopyXML
    <Functions>
  <Function ExportedName="Tutorial1_VersionInfo" Wrap="Never" ReturnType="string[,]"/>
  <Function ExportedName="NORMSINV2" ReturnType="double"/>
  <Function ExportedName="FindReplace" Wrap="Never"/>
  <Function ExportedName="FillRange" Wrap="Never"/>
  <Function ExportedName="SETDATE" Wrap="Never"/>
</Functions>
    Tip:

    Notice that while you edit the file, Visual Studio uses IntelliSense to prompt you with lists of expected syntax as you type:

    Also, if you hover over an element, help will pop up:

  2. Build the project. The three methods FindReplace, FillRange and SETDATE no longer appear in Tutorial1.cs.

Date/Time arguments

  1. Open file Tutorial1.wrapper.xml. Add a new <Function> element for GroupedFn, as shown below:

    CopyXML
    <Function ExportedName="GroupedFn">
  <Argument Name="StartDate" IsDate="1"/>
  <Argument Name="EndDate" IsDate="1"/>
  <Argument Name="PaymentDate" IsDate="1"/>
</Function>

    These <Argument> elements indicate that the named arguments - represented in Excel as integers, or vectors of integers - are actually dates.

  2. Build the project, and inspect GroupedFn, which will now have a more useful signature:

    CopyC#
    public object GroupedFn(DateTime StartDate, DateTime EndDate, string AccountType,
    int PaymentDays, DateTime[] PaymentDate, double[] PaymentAmount)
{
    CheckEngine();
    double StartDate_xldate = DateToExcel(StartDate);
    double EndDate_xldate = DateToExcel(EndDate);
    double[] PaymentDate_xldate = DatesToExcel1d(PaymentDate);
    object[] PaymentDetails = new object[] { StartDate_xldate, EndDate_xldate,
        AccountType, PaymentDays };
    object[,] PaymentSchedule = CombineVectorGroup("PaymentDate", PaymentDate_xldate,
        "PaymentAmount", PaymentAmount);
    return Engine.CallExcelWithErrorCheck("GroupedFn", true, errorPrefixes,
        PaymentDetails, PaymentSchedule);
}

Client application

We will build a simple C# test application which uses the wrapper classes. The application needs two references: one to the wrapper library and another to the run-time support library, XllPlus.ComWrappers.Runtime.dll.

Create the client application

  1. In the Project Explorer, right-click on the Solution node, and select Add/New Project....

  2. In the Add New Project dialog, select the Visual C# node in the Project Types tree, and select Console Application in the Templates list.

    Name the project Tutorial1TestApp and click OK.

  3. You will see that a new project, containing one C# file (Program.cs), has been created and added to the solution.

  4. In the Project Explorer, right-click on the Tutorial1TestApp/References node, and select Add Reference....

    In the Add Reference dialog, go to the Projects tab, select Tutorial1Wrapper, and click OK.

  5. In the Project Explorer, right-click on the Tutorial1TestApp/References node, and select Add Reference....

    In the Add Reference dialog, go to the Browse tab, navigate to the XLL+ installation directory and then to the bin sub-directory, e.g.: C:\Program Files\Planatech\XllPlus\6.0\VS8.0\bin. Select XllPlus.ComWrappers.Runtime.dll, and click OK.

Using the wrapper classes

  1. Open Program.cs in the Tutorial1TestApp project and replace all the code with the code below:

    CopyC#
    using System;
using System.Collections.Generic;
using XllPlus.ComWrappers.Runtime;
using Tutorial1Wrapper;

namespace Tutorial1TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Create a wrapper engine
                using (ExcelWrapperEngine engine = new ExcelWrapperEngine())
                {
                    // Create a hidden instance of Excel, controlled by this wrapper engine
                    engine.Create();

                    // Load the XLL
                    engine.LoadXll(@"C:\Program Files\Planatech\XllPlus\7.0\VS8.0\samples\Tutorial1\Debug\Tutorial1.xll");

                    // Create a wrapper object
                    using (Tutorial1 wrapper = new Tutorial1())
                    {
                        // Attach the wrapper to the engine before use
                        wrapper.Engine = engine;

                        double d = wrapper.NORMSINV2(0.5);
                        Console.Out.WriteLine(String.Format("NORMSINV2(0.5)={0}", d));

                        try
                        {
                            d = wrapper.NORMSINV2(2.0);
                        }
                        catch (XllWrapperException ex)
                        {
                            Console.Out.WriteLine(ex.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.ToString());
            }
            Console.Out.WriteLine("Press Enter to exit...");
            Console.In.ReadLine();
        }
    }
}

  2. Change the argument of engine.LoadXll to the actual path to the XLL file Tutorial1.xll on your installation.

  3. In Project Explorer, right-click the project node for Tutorial1TestApp, and click Set as Startup Project. Press F5 to build and run the application.

The following points are important in the code above:

  • Before any wrapper classes can be used, an instance of ExcelWrapperEngine is created.
  • The ExcelWrapperEngine object is heavy-weight - it owns a hidden instance of Excel. Therefore it is important to create only as many instances as are needed (preferably only one) and also to destroy each instance as soon as it is no longer needed. The using syntax achieves this, because ExcelWrapperEngine implements IDisposable.
  • The engine must be initialized using Create or Attach before it can be used.
  • LoadXll is used to load the XLL into Excel. Unless the XLL has been loaded, all the wrapper object methods will fail. Note that it is the responsibility of the caller to specify the full path to the XLL file.
  • Before the wrapper object can be used, it's Engine property must be set. Wrapper objects use the engine to do all the heavy work, and cannot be used without a valid and initialized engine.
  • The second call to NORMSINV throws an exception when it fails. This is the correct and expected behavior.
  • The engine is automatically destroyed when it goes out of scope at the end of the using block. If you debug the application, and put breakpoints inside and outside the using block, you will be able to use the Processes tab of Windows Task Manager to observe when the instance of Excel is started and terminated.

For more examples of client applications, including C++ and VBA, see the ApiTest sample.

See Also

Other Resources

Walkthroughs
Samples
Getting Started


Samples

[image]

XLL Wrapper
Samples
See Also Send Feedback

This section contains samples that demonstrate the use of XLL wrapper libraries.

In This Section

ApiTest sample
An XLL add-in, a wrapper library and three clients: a C++ COM client, a C# .NET client and a VBA spreadsheet client.

See Also

Other Resources

Walkthroughs
Client applications


ApiTest sample

[image]

XLL Wrapper
ApiTest sample
See Also Send Feedback

The ApiTest sample demonstrates how you can call the functions of an XLL from other environments, including .NET, VBA and C++.

This sample contains several components:

ApiTest
XLL+ add-in project. It contains functions which use a wide variety of return types and argument types.
ApiTestLib
XLL wrapper project. It contains wrapper classes generated from the ApiTest add-in.
CsClient
C# console application which uses the wrapper classes, via .NET assemblies.
CppClient
C++ console application which uses the wrapper classes, via COM interfaces.
VbaClient
Excel spreadsheet which uses the wrapper classes, via COM interfaces and Visual Basic for Applications.

Open the solution file ApiTest.sln to see and use the four Visual Studio projects.

ApiTest: XLL+ Add-in

This add-in contains a variety of add-in functions which serve to test the various features of the XLL Wrapper Generator.

The functions' names (e.g. ScalarAdd, UseCallback) reflect their purpose.

ApiTestLib: XLL Wrapper Library

This wrapper library was generated from a model file exported from the ApiTest add-in, ApiTest.model.xml.

A number of changes were made to the information file ApiTest.wrapper.xml.

Namespace

The namespace used for the wrapper classes was changed to Planatech.Demos, by changing the Namespace attribute of the Client elements:

CopyXML
<Clients>
  <Client Type="COM"
          Namespace="Planatech.Demos"
          Class="ApiTest"
          ClassGuid="2d42a1e1-3659-4869-81fc-36e7ad4b0889"
          Interface="IApiTest"
          InterfaceGuid="fe36ae91-b9e2-4794-8d47-5a204e3e06ea"/>
  <Client .../>
</Clients>

Excluding a function

The version information function was excluded from the list of exported functions:

CopyXML
<Function ExportedName="ApiTest_VersionInfo" Wrap="Never"/>

Function return types

A return type was specified for functions which, within Excel, return a variable type - they may return an error value or an error string if the functions fail for some reason.

Specifying the return type has two effects:

  1. The wrapper function's signature specifies a useful type, rather than object.
  2. if the add-in function fails the wrapped function will throw an exception with an appropriate error message.
CopyXML
<Function ExportedName="ScalarAdd" ReturnType="double"/>
<Function ExportedName="StringAdd" ReturnType="string"/>
<Function ExportedName="VectorAdd" ReturnType="double[]"/>
<Function ExportedName="MatrixAdd" ReturnType="double[,]"/>

In each case, the wrapper function's code handles the appropriate conversion and validation:

CopyC#
/// <summary>
/// Adds two vectors
/// </summary>
/// <param name="A">is the first vector</param>
/// <param name="B">is the second vector</param>
/// <exception cref="XllWrapperException">Will be thrown if any errors
/// occur in the call to Excel,
/// or if the add-in function returns an error value.</exception>
[Description("Adds two vectors")]
[DispId(1005)]
public double[] VectorAdd(double[] A, double[] B)
{
    CheckEngine();
    object res__ = Engine.CallExcelWithErrorCheck("VectorAdd", true,
        errorPrefixes, A, B);
    return Unwrap(res__, typeof(double[])) as double[];
}

Dates

Excel add-in functions treat dates as numbers. It is useful for wrapper functions to know that they are in fact dates. The IsDate attribute of the Argument element can be used for this purpose:

CopyXML
<Function ExportedName="StartOfMonth" ReturnType="DateTime">
  <Argument Name="dt" IsDate="1" WrappedName="Date"/>
</Function>
CopyC#
/// <summary>
/// Returns the start of the month for the specified date
/// </summary>
/// <param name="Date">is a numeric date</param>
/// <exception cref="XllWrapperException">Will be thrown if any errors occur in the call to Excel,
/// or if the add-in function returns an error value.</exception>
[Description("Returns the start of the month for the specified date")]
[DispId(1010)]
public DateTime StartOfMonth(DateTime Date)
{
    CheckEngine();
    double Date_xldate = DateToExcel(Date);
    object res__ = Engine.CallExcelWithErrorCheck("StartOfMonth", true, errorPrefixes, Date_xldate);
    return (DateTime)Unwrap(res__, typeof(DateTime));
}

Names

The WrappedName attribute of the Argument element was used to change the argument names visible in the wrapper function, perhaps to follow standards. Thus X in Excel becomes dtX in C#.

CopyXML
<Function ExportedName="MinDates" ReturnType="DateTime[]">
  <Argument Name="X" IsDate="1" WrappedName="dtX"/>
  <Argument Name="Y" IsDate="1" WrappedName="dtY"/>
</Function>
CopyC#
public DateTime[] MinDates(DateTime[] dtX, DateTime[] dtY)
{
    CheckEngine();
    double[] dtX_xldate = DatesToExcel1d(dtX);
    double[] dtY_xldate = DatesToExcel1d(dtY);
    object res__ = Engine.CallExcelWithErrorCheck("MinDates", true, errorPrefixes, dtX_xldate, dtY_xldate);
    return Unwrap(res__, typeof(DateTime[])) as DateTime[];
}

Name changes using the WrappedName attribute can also be useful for avoiding reserved words, and other naming conflicts. The WrappedName attribute can also be applied to function names.

CsClient: C# console application

The code for the CsClient test application can be found in the CsClient sub-directory.

References

The application has references to two assemblies: the wrapper library ApiTestLib.dll and the XLL+ wrapper support classes XllPlus.ComWrappers.Runtime.dll.

Note:

In each case the reference is to the assembly (.dll) file; the type library file (.tlb) is not used by .NET clients.

A copy of the XLL+ wrapper support classes' assembly, XllPlus.ComWrappers.Runtime.dll, can be found in the same directory as the wrapper assembly. It is placed there by Visual Studio.

Initializing the engine

The engine initalization and termination takes place in TestContext.RunWithExcel(). The engine is initialized using Create. and terminated when Dispose() is called at the end of the using block. Alternatively, Destroy could be called to terminate the engine.

CopyC#
public void RunWithExcel(string[] args)
{
    using (ExcelWrapperEngine engine = new ExcelWrapperEngine())
    {
        engine.Create();
        engine.LoadXll(GetXllPath());
        TestRunner run = new TestRunner(args);
        run.Run(engine);
    }
}
private string GetXllPath()
{
    return Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location),
                "ApiTest.xll");
}

GetXllPath() uses a standard technique to find the XLL file - it looks in the same directory as the wrapper assembly.

.NET wrapper classes

Immediately after a wrapper object is created, its Engine property is set.

CopyC#
private void TestScalarAdd(IWrapperEngine engine)
{
    try
    {
        using (ApiTest api = new ApiTest())
        {
            api.Engine = engine;
            Console.Out.WriteLine("ScalarAdd(1.2, 2.3)={0}", api.ScalarAdd(1.2, 2.3));
        }
    }
    catch (XllWrapperException ex)
    {
        Console.Out.WriteLine(ex.ToString());
    }
}

Wrapper classes are lightweight, and they support IDisposable, so it is convenient to put them within a using block. The wrapper object is disposed automatically at the end of the using block.

CppClient: C++ console application using COM

The code for the CppClient test application can be found in the CppClient sub-directory.

References

The application contains two references to COM modules: one for the wrapper library, and one for the XLL+ wrapper support classes. In each case the reference is to the type library (.tlb) file, not to the assembly (.dll) file.

CopyC++
#import "..\..\..\bin\XllPlus.ComWrappers.Runtime.tlb"
#import "..\ApiTestLib\bin\Release\ApiTestLib.tlb"

Initializing the engine

The engine initialization takes place in TestRunner::Run().

The engine is terminated using Destroy.

Note:

As usual with COM objects, the pointers reference the primary interface of the object, i.e. IExcelWrapperEngine rather than the class.

Special consideration is also needed for the value used for the wrapper class's Engine property. The IExcelWrapperEngine interface is cast to a to a IWrapperEngine interface explicitly. The reference is dropped when it is no longer required.

CopyC++
void Run()
{
    try
    {
        IExcelWrapperEnginePtr engineInstance(__uuidof(ExcelWrapperEngine));
        engineInstance->Create();
        engineInstance->LoadXll(GetXllPath());
        IWrapperEnginePtr engine(engineInstance);

        // ... Use the engine ...

        engine.Detach();
        engineInstance->Destroy();
    }
    catch(_com_error e)
    {
        _tprintf(_T("%s\n"), (LPCTSTR)e.Description());
    }
}

COM wrapper classes

The wrapper class implements a default interface, IApiTest. As usual in C++ COM programming, pointers are for the default interface, not the object.

CopyC++
void TestScalarAdd(IWrapperEnginePtr& engine)
{
    try
    {
        ApiTestLib::IApiTestPtr api(__uuidof(ApiTestLib::ApiTest));
        api->Engine = engine;
        _tprintf(_T("ScalarAdd(1.2, 2.3)=%lf\n"), api->ScalarAdd(1.2, 2.3));
    }
    catch(_com_error e)
    {
        _tprintf(_T("%s\n"), (LPCTSTR)e.Description());
    }
}

Array arguments

Array arguments are represented as SAFEARRAY types in the COM code. The sample code uses a few array helper methods to ease the task of reading and writing COM arrays.

VbaClient: VBA module in Excel spreadsheet

VbaClient.xls can be found in the VbaClient sub-directory of the sample.

References

The Tools/References... menu was used to open the References dialog. Then the Browse... button was used to navigate to the directories containing each type library.

In each case the reference was made to the type library (.tlb file), not the assembly (.dll) file.

The XLL+ wrapper support classes' type library file, XllPlus.ComWrappers.Runtime.tlb, is in the bin sub-directory of the XLL+ installation (e.g. C:\Program Files\Planatech\XllPlus\6.0\VS9.0\bin\XllPlus.ComWrappers.Runtime.tlb).

The wrapper objects' type library is in the same directory as the wrapper assembly: ..\ApiTestLib\bin\release\ApiTestLib.tlb.

Initializing the engine

Because the wrapper library is being used from Excel VBA, the engine is initialized using Attach, passing the existing instance of Excel. When the engine is no longer required, Detach is called.

CopyVBA
Public Sub Run()
    Dim engine As New ExcelWrapperEngine
    engine.Attach Application
    engine.LoadXll GetXllPath

    ' ...

    engine.Detach
End Sub
Important Note:

You should not call Create from Excel VBA. This will create a new hidden instance of Excel instead of using the current instance.

The full path to the XLL file is calculated by GetXllPath:

CopyVBA
Private Function GetXllPath() As String
    GetXllPath = ThisWorkbook.Path & "\..\Debug\ApiTest.xll"
End Function

Wrapper classes

The VBA wrapper class ApiTestVba was used instead of the standard wrapper class, to deal with the special issues arising from the VBA implementation of COM.

CopyVBA
Private Sub TestScalarAdd(engine As IWrapperEngine)
    Err.Clear
    On Error Resume Next
    Dim api As New ApiTestVba
    Set api.Engine = engine
    If Err.Number <> 0 Then
        Debug.Print Err.Description
    Else
        Debug.Print "ScalarAdd(1.2, 2.3)";
        Dim result As Double
        result = api.ScalarAdd(1.2, 2.3)
        If Err.Number <> 0 Then
            Debug.Print " throws "; Err.Description
        Else
            Debug.Print "="; result
        End If
    End If
End Sub

See Also

Other Resources

Client applications
Samples
Getting Started
Walkthroughs


Information files

[image]

XLL Wrapper
Information files
See Also Send Feedback

An information file allows the developer to fine-tune the signature and behavior of a wrapped add-in function. Excel add-in functions typically do not have a fixed return type, since they can often return error values. Methods in other programming environments should have fixed return types, and should throw an exception if an error occurs. An information file contains instructions for the CWGENCLS utility. When you create a new XLL Wrapper project, an information file is created for you, and is added to the project.

In This Section

XllWrapper element
The document element, XllWrapper.
Function element
The Function element, which lets the developer control the behavior of a single add-in function.
Argument element
The Argument element, which controls the type, name and behavior of a single argument.
Client element
The Client element, which controls the class definitions for a generated wrapper class, including namespace, public name and GUIDs.

See Also

Other Resources

Getting Started: Information files
CWGENCLS


XllWrapper element

[image]

XLL Wrapper
XllWrapper element
See Also Send Feedback

XllWrapper is the root element of an information file. It contains up to three elements: Clients, ErrorPrefixes and Functions. It has one mandatory attribute: Name.

Child elements

Element | Required | Description
Clients | Required | The Clients element should contain one or more Client elements. Each Client element will be transformed to a wrapper class designed for the specified client type.
ErrorPrefixes | Optional | The ErrorPrefixes element contains the standard error prefixes to be used for all add-in functions in the project.
Functions | Optional | The Functions element should contain zero or more Function elements. Each Function element will modify the code generation for a single wrapper method.

Attributes

Attribute | Required | Description | Example(s)
Name | Required | The name of the wrapper project. | MyAddin

See Also

Other Resources

Information files
© 1997-2014 Planatech Solutions Ltd. All rights reserved.

Send comments on this topic to Planatech Support


Clients element

[image]

XLL Wrapper
Clients element
See Also Send Feedback

The Clients element should contain one or more Client elements. Each Client element will be transformed to a wrapper class designed for the specified client type.

Child elements

Element | Required | Description
Client | Required | The Client element controls the generation of code for a single client type (COM or VBA).

See Also

Other Resources

Information files
© 1997-2014 Planatech Solutions Ltd. All rights reserved.

Send comments on this topic to Planatech Support


Client element

[image]

XLL Wrapper
Client element
See Also Send Feedback

The Client element defines a single wrapper class that will be generated. The attributes of the Client element are summarized below. All attributes are required.

An instruction file normally contains two Client elements, one with type COM, and the other with type VBA.

Guids are supplied when the information file is created, and should not usually be changed afterwards.

Attributes

Attribute | Required | Description | Example(s)
Type | Required | The type of client: either COM or VBA. | COM VBA
Namespace | Required | The namespace used for the generated class. | MyCompany.Analytics
Class | Required | The name of the generated C# wrapper class. | MyXllAddin
ClassGuid | Required | The globally unique identifier of the generated class. | 14636546-A5DE-40F9-B02B-1847BC47C9E5
Interface | Required | The name of the COM interface class which will be used as the wrapper class’s defaultinterface. | IMyXllAddin
InterfaceGuid | Required | The globally unique identifier of the generated interface | 7CBD1C10-C089-4D34-8BC4-633B729C49C1

See Also

Other Resources

Information files
© 1997-2014 Planatech Solutions Ltd. All rights reserved.

Send comments on this topic to Planatech Support


ErrorPrefixes element

[image]

XLL Wrapper
ErrorPrefixes element
See Also Send Feedback

The ErrorPrefixes element may contain one or more ErrorPrefix elements.

If an add-in function returns a string value which starts with any of the text strings specified in the ErrorPrefix elements, then an exception will be raised, using the remainder of the string value (after the prefix has been removed) as the error message.

If the ErrorPrefixes element contains zero ErrorPrefix elements, then no testing against string values will occur.

Child elements

Element | Required | Description
ErrorPrefix | Required | Each ErrorPrefix element should contain a text string, which will be matched against return values.

See Also

Other Resources

Information files
© 1997-2014 Planatech Solutions Ltd. All rights reserved.

Send comments on this topic to Planatech Support


ErrorPrefix element

[image]

XLL Wrapper
ErrorPrefix element
See Also Send Feedback

Each ErrorPrefix element should contain a text string. If an add-in function returns a string value which starts with the specified text string, then an exception will be raised, using the remainder of the string value (after the prefix has been removed) as the error message.

See Also

Other Resources

Information files


Functions element

[image]

XLL Wrapper
Functions element
See Also Send Feedback

The Functions element should contain zero or more Function elements. Each Function element will modify the code generation for a single wrapper method.

Child elements

Element | Required | Description
Function | Required | Each Function element will modify the code generation for a single wrapper method.

See Also

Other Resources

Information files
© 1997-2014 Planatech Solutions Ltd. All rights reserved.

Send comments on this topic to Planatech Support


Function element

[image]

XLL Wrapper
Function element
See Also Send Feedback

The Function element contains instructions for wrapping a single add-in function. These instructions will enrich or override the data in the model file. The attributes of the function element are summarized below.

The element can also contain any number of Argument elements and, optionally, an ErrorPrefixes element.

Child elements

Element | Required | Description
ErrorPrefixes | Optional | The ErrorPrefixes element contains the error prefixes to be used for this add-in function only. If the ErrorPrefixes element is omitted, then the default prefixes specified for the XllWrapper will be used.
Argument | Optional | An Argument element is an optional element which controls the wrapping of a single named argument.

Attributes

Attribute | Required | Description | Example(s)
ExportedName | Required | The name of the function, as it appears in the model file. | NORMSINV2
Wrap | Optional | One of: Always, Never, Default. Controls whether the specified function will be wrapped. If omitted, Default will be assumed. | Always Never Default
ReturnType | Optional | The expected return type of the add-in function. This should be a C# scalar type or array type. | string double[] int[,]
WrappedName | Optional | The name of the function as it will appear in the wrapper method. | NormsInv2
NoExceptionOnError | Optional | If 0 or omitted, then an exception will be thrown if the function returns either an error value or a string beginning with one of the specified ErrorPrefixes. If 1, then an error value will be returned as a COM error value. | 0 1

See Also

Other Resources

Information files
Argument element


Argument element

[image]

XLL Wrapper
Argument element
See Also Send Feedback

An Argument element is an optional element which controls the wrapping of a single named argument.

Attributes

Attribute | Required | Description | Example(s)
Name | Required | The name of the argument as it appears in the Name attribute of the XlArgument element in the model file. | X
IsDate Optional One of: 0, 1. If 1, then the argument will be treated as a date (or an array of dates). In the wrapper class, the argument's type will be DateTime (or DateTime[] or DateTime[,] for an array). If 0 or omitted, then the argument's type will be treated normally.

0

1
WrappedName | Optional | The name of the function as it will appear in the wrapper method. | nItemCount
Type Optional

The argument type, as it will appear in the C# wrapper function.

Only the following basic types are supported: bool, DateTime, double, int, string, object. The type may be a scalar (e.g. int), a vector (e.g. int[]) or a matrix (e.g. int[,]).

An argument that accepts a vector or matrix of mixed types should use object[] or object[,] respectively. An argument that accepts a variety of different input types should use object.

string

double[]

int[,]

See Also

Other Resources

Information files
Function element


Wrapper Generator Tools

[image]

XLL Wrapper
Wrapper Generator Tools
Send Feedback

XLL Wrapper Generator contains a number of tools which are used by the build process. The tools can also be used by the developer at the command-line or as part of a batch file, make file etc.

In This Section

CWGENCLS
Command-line utility that generates wrapper classes.
CWGENINF
Command-line utility that generates a skeleton information file.
[0221417c-ed74-484c-8968-dab910f4551c]
Command-line utility that examines XLLs and generates model files.
XLLQUERY
Alternative command-line utility that examines XLLs and generates model files. This should only be used if [0221417c-ed74-484c-8968-dab910f4551c] has failed.


CWGENCLS

[image]

XLL Wrapper
CWGENCLS
Send Feedback

CWGENCLS is a command-line tool that generates wrapper classes for XLL add-ins. The generated code is written in C#.

Usage

CWGENCLS -i InformationFile -m ModelFile [options]

Parameter | Required | Description
-i InfoFile | Required | The full path and file name of the information file.
-m ModelFile | Required | The full path and file name of the model file.
-c ClientType | Optional | COM or VBA. If provided, only the class for the named client will be generated. If omitted, both classes will be generated.
-o OutputFile | Optional | The file name (optionally including a path) of the output file. If omitted, then the project name will be used, e.g. MyAddin.cs.
-d TargetDir | Optional | The directory that will contain the output file. If OutputFile is provided, and is rooted (i.e. contains a complete path), then this parameter will be ignored. If the directory provided is not rooted, then it will be relative to the directory containing the InformationFile. If TargetDir is omitted, then the directory containing the InformationFile will be used.

Location

In the XLL+ Toolkit, CWGENCLS.EXE can be found in the bin sub-directory of the installation folder, e.g. C:\Program Files\Planatech\XllPlus\6.0\VS9.0\bin.

In the XLL Host installation, CWGENCLS.EXE can be found in the bin sub-directory of the installation folder, e.g. C:\Program Files\Planatech\XllHost\2.0\bin.


CWGENINF

[image]

XLL Wrapper
CWGENINF
Example Send Feedback

CWGENINF is a command-line tool that generates skeleton information files for use by CWGENCLS.

Usage

CWGENCLS projectname namespace [outfile]
Parameter | Required | Description
projectname | Required | projectname is the name of the XLL+ add-in project, and is used for the names of the generated classes.
namespace | Required | namespace cis the namespace used for the generated classes.
outfile | Optional | outfile is the name of the information file that will be produced. If omitted, the project name will be used.

Location

In the XLL+ Toolkit, CWGENINF.EXE can be found in the bin sub-directory of the installation folder, e.g. C:\Program Files\Planatech\XllPlus\6.0\VS9.0\bin.

In the XLL Host installation, CWGENINF.EXE can be found in the bin sub-directory of the installation folder, e.g. C:\Program Files\Planatech\XllHost\2.0\bin.

Example

For example, a command like the following:

CWGENCLS MyAddin MyNamespace
will produce a file named MyAddin.Wrapper.xml containing something resembling the following:

CopyXML
<?xml version="1.0" encoding="utf-8"?>
<XllWrapper Name="MyAddin">
  <Clients>
    <Client Type="COM"
            Namespace="MyNamespace"
            Class=" MyAddin"
            ClassGuid="51922C8E-F57D-485F-91AD-7B6FB01E046B"
            Interface="IMyAddin"
            InterfaceGuid="F665828B-9914-41E5-9B74-42505F67A88D"/>
    <Client Type="VBA"
            Namespace="MyNamespace"
            Class="MyAddinVba"
            ClassGuid="14636546-A5DE-40F9-B02B-1847BC47C9E5"
            Interface="IMyAddinVba"
            InterfaceGuid="7CBD1C10-C089-4D34-8BC4-633B729C49C1"/>
  </Clients>
  <Functions>
    <Function ExportedName="MyAddin_VersionInfo"
              Wrap="Always"
              ReturnType="string[,]"/>
  </Functions>
</XllWrapper>


XLLQUERY

[image]

XLL Wrapper
XLLQUERY
See Also Send Feedback

XLLQUERY is a command-line tool that examines an XLL add-in and generates a model file which describes the add-in functions it contains. The model file can be used by CWGENCLS.

Usage

XLLQUERY -m ModelFile -i XllFile [-i XllFile2] [options]
Parameter | Required | Description
-m ModelFile | Required | The full path and file name of the output file, which will be a model file.
-i XllFile | Required | The full path and file name of the XLL to be analyzed. Note that this parameter may be repeated, so that more than one XLL is scanned into the same model file.
-e ExcelDir | Required | The directory that contains the desired version of EXCEL.EXE.
-t Timeout | Optional | The length of time allowed for Excel to start up and load the XLL addins, in milliseconds. If omitted, the default timeout of 10000 (10 seconds) will be used.

Location

In the XLL Host installation, XLLQUERY.EXE can be found in the bin\XllQuery sub-directory of the installation folder, e.g. C:\Program Files\Planatech\XllHost\2.0\bin\XllQuery.

The directory will also contain a special version of XLCALL32.DLL, which will be used as a replacement for the standard Microsoft file.

Process

XLLQUERY operates as follows:

  1. Check that EXCEL.EXE and XLCALL32.DLL exist in the Excel directory, and are valid.
  2. Rename XLCALL32.DLL to XLCALL32MS.DLL in the Excel directory, and copy the special version of XLCALL32.DLL into the Excel directory.

  3. Start the specified version of Excel and use Excel's automation model to open the XLL file or files.

    While the XLL files are opened, the special version of XLCALL32.DLL will monitor all function registrations, and save the parameters to a temporary file.

  4. When the timeout period has completed, close Excel.
  5. Rename XLCALL32MS.DLL to XLCALL32.DLL in the Excel directory, restoring the original state.
  6. Transform the temporary file into a model file and save it as specified in the command line.

See Also

Other Resources

[0221417c-ed74-484c-8968-dab910f4551c]


XllPlus.ComWrappers.Runtime Namespace

[image]

XLL Wrapper
XllPlus.ComWrappers.Runtime Namespace
Send Feedback

Contains runtime classes that support the add-in wrapper assemblies generated by the XLL Wrapper Generator.

Classes

Class | Description
AddinWrapperBase | Base class for XLL wrapper concrete classes.
ExcelWrapperEngine | IWrapperEngine implementation class that controls an instance of Excel.
XllWrapperException | Represents errors that occur during the execution of XLL add-in functions.

Interfaces

Interface | Description
IExcelWrapperEngine | Default interface for class ExcelWrapperEngine, for use by COM objects
IWrapperEngine | Public interface supported by Excel wrapper implementation classes.


AddinWrapperBase Class

[image]

XLL Wrapper
AddinWrapperBase Class
Members See Also Send Feedback
Base class for XLL wrapper concrete classes.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public class AddinWrapperBase : IDisposable
Visual Basic (Declaration)
Public Class AddinWrapperBase _
    Implements IDisposable
Visual C++
public ref class AddinWrapperBase : IDisposable

Inheritance Hierarchy

System..::.Object
XllPlus.ComWrappers.Runtime..::.AddinWrapperBase

See Also

AddinWrapperBase Members
XllPlus.ComWrappers.Runtime Namespace


AddinWrapperBase Members

[image] [image]

XLL Wrapper
AddinWrapperBase Members
AddinWrapperBase Class Constructors Methods Properties See Also Send Feedback

The AddinWrapperBase type exposes the following members.

Constructors

Name | Description
AddinWrapperBase | Creates a new instance of AddinWrapperBase.

Methods

Name | Description
CheckEngine | Check that the Engine property has been initialized. Raise an exception if it has not.
CombineVectorGroup | Combines the supplied vector arguments into a 2-dimensional array
DateFromExcel | Converts a numeric date value used by Excel to a .NET DateTime.
DatesFromExcel1d | Converts an array of numeric date values used by Excel to an array of .NET DateTime.
DatesFromExcel2d | Converts an array of numeric date values used by Excel to an array of .NET DateTime.
DatesToExcel1d | Converts an array of .NET DateTime to an aray of numeric date values, as used by Excel.
DatesToExcel2d | Converts an array of .NET DateTime to an aray of numeric date values, as used by Excel.
DateToExcel | Converts a .NET DateTime to a numeric date value used by Excel.
Dispose | The Dispose method of the AddinWrapperBase class releases all unmanaged resources used by the object.
LoadXll | Invokes the Engine to load the specified XLL file into memory.
Unwrap | Convert the value returned by Excel to the expected type

Properties

Name | Description
Engine | The Engine instance, which may be a controlled instance of Excel, or an Excel emulator.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


AddinWrapperBase Constructor

[image]

XLL Wrapper
AddinWrapperBase Constructor
AddinWrapperBase Class See Also Send Feedback
Creates a new instance of AddinWrapperBase.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
protected AddinWrapperBase()
Visual Basic (Declaration)
Protected Sub New
Visual C++
protected:
AddinWrapperBase()

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


AddinWrapperBase Methods

[image] [image]

XLL Wrapper
AddinWrapperBase Methods
AddinWrapperBase Class See Also Send Feedback

The AddinWrapperBase type exposes the following members.

Methods

Name | Description
CheckEngine | Check that the Engine property has been initialized. Raise an exception if it has not.
CombineVectorGroup | Combines the supplied vector arguments into a 2-dimensional array
DateFromExcel | Converts a numeric date value used by Excel to a .NET DateTime.
DatesFromExcel1d | Converts an array of numeric date values used by Excel to an array of .NET DateTime.
DatesFromExcel2d | Converts an array of numeric date values used by Excel to an array of .NET DateTime.
DatesToExcel1d | Converts an array of .NET DateTime to an aray of numeric date values, as used by Excel.
DatesToExcel2d | Converts an array of .NET DateTime to an aray of numeric date values, as used by Excel.
DateToExcel | Converts a .NET DateTime to a numeric date value used by Excel.
Dispose | The Dispose method of the AddinWrapperBase class releases all unmanaged resources used by the object.
LoadXll | Invokes the Engine to load the specified XLL file into memory.
Unwrap | Convert the value returned by Excel to the expected type

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


CheckEngine Method

[image]

XLL Wrapper
AddinWrapperBase..::.CheckEngine Method
AddinWrapperBase Class See Also Send Feedback
Check that the Engine property has been initialized. Raise an exception if it has not.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
protected void CheckEngine()
Visual Basic (Declaration)
Protected Sub CheckEngine
Visual C++
protected:
void CheckEngine()

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | The Engine property has not been initialized.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


CombineVectorGroup Method

[image]

XLL Wrapper
AddinWrapperBase..::.CombineVectorGroup Method
AddinWrapperBase Class See Also Send Feedback
Combines the supplied vector arguments into a 2-dimensional array

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
protected Object[,] CombineVectorGroup(
    params Object[] args
)
Visual Basic (Declaration)
Protected Function CombineVectorGroup ( _
    ParamArray args As Object() _
) As Object(,)
Visual C++
protected:
array<Object^,2>^ CombineVectorGroup(
    ... array<Object^>^ args
)

Parameters

args
Type: array< System..::.Object >[]()[]
A list of argument pairs, each comprising name followed by value.

Return Value

A two-dimensional array

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | Thrown if conversion is not possible, or if there is a size mismatch between the vector arguments.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


DateFromExcel Method

[image]

XLL Wrapper
AddinWrapperBase..::.DateFromExcel Method
AddinWrapperBase Class See Also Send Feedback
Converts a numeric date value used by Excel to a .NET DateTime.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
protected DateTime DateFromExcel(
    double d
)
Visual Basic (Declaration)
Protected Function DateFromExcel ( _
    d As Double _
) As DateTime
Visual C++
protected:
DateTime DateFromExcel(
    double d
)

Parameters

d
Type: System..::.Double
An Excel numeric value to be converted to .NET DateTime.

Return Value

A .NET DateTime equivalent to the Excel date/time value.

Remarks

The implementation of this method is delegated to the implementation class instance, as returned by GetImpl.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


DatesFromExcel1d Method

[image]

XLL Wrapper
AddinWrapperBase..::.DatesFromExcel1d Method
AddinWrapperBase Class See Also Send Feedback
Converts an array of numeric date values used by Excel to an array of .NET DateTime.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
protected DateTime[] DatesFromExcel1d(
    double[] ad
)
Visual Basic (Declaration)
Protected Function DatesFromExcel1d ( _
    ad As Double() _
) As DateTime()
Visual C++
protected:
array<DateTime>^ DatesFromExcel1d(
    array<double>^ ad
)

Parameters

ad
Type: array< System..::.Double >[]()[]
An array of Excel numeric values to be converted to .NET DateTimes.

Return Value

An array of .NET DateTime values equivalent to the Excel date/time values.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


DatesFromExcel2d Method

[image]

XLL Wrapper
AddinWrapperBase..::.DatesFromExcel2d Method
AddinWrapperBase Class See Also Send Feedback
Converts an array of numeric date values used by Excel to an array of .NET DateTime.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
protected DateTime[,] DatesFromExcel2d(
    double[,] ad
)
Visual Basic (Declaration)
Protected Function DatesFromExcel2d ( _
    ad As Double(,) _
) As DateTime(,)
Visual C++
protected:
array<DateTime,2>^ DatesFromExcel2d(
    array<double,2>^ ad
)

Parameters

ad
Type: array< System..::.Double ,2>[,](,)[,]
An array of Excel numeric values to be converted to .NET DateTimes.

Return Value

An array of .NET DateTime values equivalent to the Excel date/time values.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


DatesToExcel1d Method

[image]

XLL Wrapper
AddinWrapperBase..::.DatesToExcel1d Method
AddinWrapperBase Class See Also Send Feedback
Converts an array of .NET DateTime to an aray of numeric date values, as used by Excel.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
protected double[] DatesToExcel1d(
    DateTime[] adt
)
Visual Basic (Declaration)
Protected Function DatesToExcel1d ( _
    adt As DateTime() _
) As Double()
Visual C++
protected:
array<double>^ DatesToExcel1d(
    array<DateTime>^ adt
)

Parameters

adt
Type: array< System..::.DateTime >[]()[]
Array of date and time values to be converted to Excel numeric values.

Return Value

An array of numeric values representing each date in Excel.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


DatesToExcel2d Method

[image]

XLL Wrapper
AddinWrapperBase..::.DatesToExcel2d Method
AddinWrapperBase Class See Also Send Feedback
Converts an array of .NET DateTime to an aray of numeric date values, as used by Excel.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
protected double[,] DatesToExcel2d(
    DateTime[,] adt
)
Visual Basic (Declaration)
Protected Function DatesToExcel2d ( _
    adt As DateTime(,) _
) As Double(,)
Visual C++
protected:
array<double,2>^ DatesToExcel2d(
    array<DateTime,2>^ adt
)

Parameters

adt
Type: array< System..::.DateTime ,2>[,](,)[,]
Array of date and time values to be converted to Excel numeric values.

Return Value

An array of numeric values representing each date in Excel.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


DateToExcel Method

[image]

XLL Wrapper
AddinWrapperBase..::.DateToExcel Method
AddinWrapperBase Class See Also Send Feedback
Converts a .NET DateTime to a numeric date value used by Excel.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
protected double DateToExcel(
    DateTime dt
)
Visual Basic (Declaration)
Protected Function DateToExcel ( _
    dt As DateTime _
) As Double
Visual C++
protected:
double DateToExcel(
    DateTime dt
)

Parameters

dt
Type: System..::.DateTime
Date and time to be converted to an Excel numeric value.

Return Value

A numeric value representing the date in Excel.

Remarks

The implementation of this method is delegated to the implementation class instance, as returned by GetImpl.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


Dispose Method

[image]

XLL Wrapper
AddinWrapperBase..::.Dispose Method
AddinWrapperBase Class See Also Send Feedback
The Dispose method of the AddinWrapperBase class releases all unmanaged resources used by the object.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public void Dispose()
Visual Basic (Declaration)
Public Sub Dispose
Visual C++
public:
virtual void Dispose() sealed

Implements

IDisposable..::.Dispose()()()

Remarks

Use the Dispose method to close the AddinWrapperBase-derived object and release resources when you are finished using the object.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


LoadXll Method

[image]

XLL Wrapper
AddinWrapperBase..::.LoadXll Method
AddinWrapperBase Class See Also Send Feedback
Invokes the Engine to load the specified XLL file into memory.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public void LoadXll(
    string xllPath
)
Visual Basic (Declaration)
Public Sub LoadXll ( _
    xllPath As String _
)
Visual C++
public:
void LoadXll(
    String^ xllPath
)

Parameters

xllPath
Type: System..::.String
Full path to a XLL file whose add-in functions are to be wrapped.

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | The Engine property has not been initialized, or the XLL cannot be found, or an error occurred while loading the XLL.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


Unwrap Method

[image]

XLL Wrapper
AddinWrapperBase..::.Unwrap Method
AddinWrapperBase Class See Also Send Feedback
Convert the value returned by Excel to the expected type

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
protected Object Unwrap(
    Object result,
    Type returnType
)
Visual Basic (Declaration)
Protected Function Unwrap ( _
    result As Object, _
    returnType As Type _
) As Object
Visual C++
protected:
Object^ Unwrap(
    Object^ result,
    Type^ returnType
)

Parameters

result
Type: System..::.Object
A variant value returned by Excel
returnType
Type: System..::.Type
The desired type, which may be an array type

Return Value

If the function returns, it always returns an object of type returnType.

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | Thrown if conversion is not possible.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


AddinWrapperBase Properties

[image] [image]

XLL Wrapper
AddinWrapperBase Properties
AddinWrapperBase Class See Also Send Feedback

The AddinWrapperBase type exposes the following members.

Properties

Name | Description
Engine | The Engine instance, which may be a controlled instance of Excel, or an Excel emulator.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


Engine Property

[image]

XLL Wrapper
AddinWrapperBase..::.Engine Property
AddinWrapperBase Class See Also Send Feedback
The Engine instance, which may be a controlled instance of Excel, or an Excel emulator.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public IWrapperEngine Engine { get; set; }
Visual Basic (Declaration)
Public Property Engine As IWrapperEngine
Visual C++
public:
property IWrapperEngine^ Engine {
    IWrapperEngine^ get ();
    void set (IWrapperEngine^ value);
}

Remarks

Until this property has been initialized, the wrapper class is not ready for use.

See Also

AddinWrapperBase Class
XllPlus.ComWrappers.Runtime Namespace


ExcelWrapperEngine Class

[image]

XLL Wrapper
ExcelWrapperEngine Class
Members See Also Send Feedback
IWrapperEngine implementation class that controls an instance of Excel.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public class ExcelWrapperEngine : IExcelWrapperEngine,
    IWrapperEngine, IDisposable
Visual Basic (Declaration)
Public Class ExcelWrapperEngine _
    Implements IExcelWrapperEngine, IWrapperEngine, IDisposable
Visual C++
public ref class ExcelWrapperEngine : IExcelWrapperEngine,
    IWrapperEngine, IDisposable

Remarks

An instance of this class should be used as the Engine for wrapper class instances when Excel is available at run-time. If Excel is not available then an emulator engine should be used instead.

An instance is initialized by using either Create()()() or Attach(Object), and must be terminated by calling either Destroy()()() or Detach()()() respectively.

Note that the class is heavyweight if Create()()() is used, since a hidden Excel application instance is created. Care should therefore be taken to create as few as possible instances of the class (preferably only one), and instances should be kept "alive" as long as they are needed.

Remarks

Inheritance Hierarchy

System..::.Object
XllPlus.ComWrappers.Runtime..::.ExcelWrapperEngine

See Also

ExcelWrapperEngine Members
XllPlus.ComWrappers.Runtime Namespace


ExcelWrapperEngine Members

[image] [image]

XLL Wrapper
ExcelWrapperEngine Members
ExcelWrapperEngine Class Constructors Methods See Also Send Feedback

The ExcelWrapperEngine type exposes the following members.

Constructors

Name | Description
ExcelWrapperEngine | Constructs a new instance of ExcelWrapperEngine.

Methods

Name | Description
Attach | Prepares the object for use by attaching to the specified Excel application instance and initializing the date offset.
CallExcel | Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments.
CallExcelWithErrorCheck | Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments, and raises an error under the conditions specified.
Create | Prepares the object for use by creating an owned instance of Excel, making it invisible, and initializing the date offset.
DateFromExcel | Converts a numeric date value used by Excel to a .NET DateTime.
DateToExcel | Converts a .NET DateTime to a numeric date value used by Excel.
Destroy | Closes down the owned instance of Excel, cleanly and quietly, and releases resources.
Detach | Detaches the Excel Application instance from the object.
Dispose | Unloads all resources used by the class.
LoadXll | Loads the specified XLL into the engine.

See Also

ExcelWrapperEngine Class
XllPlus.ComWrappers.Runtime Namespace


ExcelWrapperEngine Constructor

[image]

XLL Wrapper
ExcelWrapperEngine Constructor
ExcelWrapperEngine Class See Also Send Feedback
Constructs a new instance of ExcelWrapperEngine.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public ExcelWrapperEngine()
Visual Basic (Declaration)
Public Sub New
Visual C++
public:
ExcelWrapperEngine()

Remarks

The object is not ready for use until the Create() or Attach() method has been called.

See Also

ExcelWrapperEngine Class
XllPlus.ComWrappers.Runtime Namespace


ExcelWrapperEngine Methods

[image] [image]

XLL Wrapper
ExcelWrapperEngine Methods
ExcelWrapperEngine Class See Also Send Feedback

The ExcelWrapperEngine type exposes the following members.

Methods

Name | Description
Attach | Prepares the object for use by attaching to the specified Excel application instance and initializing the date offset.
CallExcel | Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments.
CallExcelWithErrorCheck | Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments, and raises an error under the conditions specified.
Create | Prepares the object for use by creating an owned instance of Excel, making it invisible, and initializing the date offset.
DateFromExcel | Converts a numeric date value used by Excel to a .NET DateTime.
DateToExcel | Converts a .NET DateTime to a numeric date value used by Excel.
Destroy | Closes down the owned instance of Excel, cleanly and quietly, and releases resources.
Detach | Detaches the Excel Application instance from the object.
Dispose | Unloads all resources used by the class.
LoadXll | Loads the specified XLL into the engine.

See Also

ExcelWrapperEngine Class
XllPlus.ComWrappers.Runtime Namespace


Attach Method

[image]

XLL Wrapper
ExcelWrapperEngine..::.Attach Method
ExcelWrapperEngine Class See Also Send Feedback
Prepares the object for use by attaching to the specified Excel application instance and initializing the date offset.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public void Attach(
    Object app
)
Visual Basic (Declaration)
Public Sub Attach ( _
    app As Object _
)
Visual C++
public:
virtual void Attach(
    Object^ app
) sealed

Parameters

app
Type: System..::.Object
A valid instance of Excel, which can be acquired in VBA by passing the global variable Application.

Implements

IExcelWrapperEngine..::.Attach(Object)

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | Thrown if app is not a valid Application object or if the object has already been initialized.

See Also

ExcelWrapperEngine Class
XllPlus.ComWrappers.Runtime Namespace


CallExcel Method

[image]

XLL Wrapper
ExcelWrapperEngine..::.CallExcel Method
ExcelWrapperEngine Class See Also Send Feedback
Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public Object CallExcel(
    string fnName,
    params Object[] arguments
)
Visual Basic (Declaration)
Public Function CallExcel ( _
    fnName As String, _
    ParamArray arguments As Object() _
) As Object
Visual C++
public:
virtual Object^ CallExcel(
    String^ fnName,
    ... array<Object^>^ arguments
) sealed

Parameters

fnName
Type: System..::.String
The name of the function, as visible in Excel.
arguments
Type: array< System..::.Object >[]()[]
The arguments to the add-in function.

Return Value

The variant type that was returned by Excel.

Implements

IExcelWrapperEngine..::.CallExcel(String, array<Object>[]()[])
IWrapperEngine..::.CallExcel(String, array<Object>[]()[])

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | Thrown if Excel is unable to call the function, or if Excel rejects the inputs.

See Also

ExcelWrapperEngine Class
XllPlus.ComWrappers.Runtime Namespace


CallExcelWithErrorCheck Method

[image]

XLL Wrapper
ExcelWrapperEngine..::.CallExcelWithErrorCheck Method
ExcelWrapperEngine Class See Also Send Feedback
Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments, and raises an error under the conditions specified.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public Object CallExcelWithErrorCheck(
    string fnName,
    bool raiseExceptionOnExcelError,
    string[] errorStringPrefixes,
    params Object[] arguments
)
Visual Basic (Declaration)
Public Function CallExcelWithErrorCheck ( _
    fnName As String, _
    raiseExceptionOnExcelError As Boolean, _
    errorStringPrefixes As String(), _
    ParamArray arguments As Object() _
) As Object
Visual C++
public:
virtual Object^ CallExcelWithErrorCheck(
    String^ fnName,
    bool raiseExceptionOnExcelError,
    array<String^>^ errorStringPrefixes,
    ... array<Object^>^ arguments
) sealed

Parameters

fnName
Type: System..::.String
The name of the function, as visible in Excel.
raiseExceptionOnExcelError
Type: System..::.Boolean
If true, then when Excel returns an error value, such as #VALUE!, an error is raised. If false, then the error value is returned.
errorStringPrefixes
Type: array< System..::.String >[]()[]
If not null or empty, then if Excel returns a string value which begins with any of these prefixes, an error is raised.
arguments
Type: array< System..::.Object >[]()[]
The arguments to the add-in function.

Return Value

The variant type returned by Excel.

Implements

IExcelWrapperEngine..::.CallExcelWithErrorCheck(String, Boolean, array<String>[]()[], array<Object>[]()[])
IWrapperEngine..::.CallExcelWithErrorCheck(String, Boolean, array<String>[]()[], array<Object>[]()[])

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | Thrown if Excel is unable to call the function, or if Excel rejects the inputs, or if Excel returns an error value (e.g. #VALUE!) or if a string result containing an error description is returned.

See Also

ExcelWrapperEngine Class
XllPlus.ComWrappers.Runtime Namespace


Create Method

[image]

XLL Wrapper
ExcelWrapperEngine..::.Create Method
ExcelWrapperEngine Class See Also Send Feedback
Prepares the object for use by creating an owned instance of Excel, making it invisible, and initializing the date offset.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public void Create()
Visual Basic (Declaration)
Public Sub Create
Visual C++
public:
virtual void Create() sealed

Implements

IExcelWrapperEngine..::.Create()()()

Remarks

VBA applications running inside Excel should use Attach(Object) instead of this method.

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | Thrown if a COM error occurs or if the object has already been initialized.

See Also

ExcelWrapperEngine Class
XllPlus.ComWrappers.Runtime Namespace


DateFromExcel Method

[image]

XLL Wrapper
ExcelWrapperEngine..::.DateFromExcel Method
ExcelWrapperEngine Class See Also Send Feedback
Converts a numeric date value used by Excel to a .NET DateTime.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public DateTime DateFromExcel(
    double d
)
Visual Basic (Declaration)
Public Function DateFromExcel ( _
    d As Double _
) As DateTime
Visual C++
public:
virtual DateTime DateFromExcel(
    double d
) sealed

Parameters

d
Type: System..::.Double
An Excel numeric value to be converted to .NET DateTime.

Return Value

A .NET DateTime equivalent to the Excel date/time value.

Implements

IExcelWrapperEngine..::.DateFromExcel(Double)
IWrapperEngine..::.DateFromExcel(Double)

Remarks

This method handles the case where the Excel base date has been to a value other than the standard OADate value.

See Also

ExcelWrapperEngine Class
XllPlus.ComWrappers.Runtime Namespace


DateToExcel Method

[image]

XLL Wrapper
ExcelWrapperEngine..::.DateToExcel Method
ExcelWrapperEngine Class See Also Send Feedback
Converts a .NET DateTime to a numeric date value used by Excel.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public double DateToExcel(
    DateTime dt
)
Visual Basic (Declaration)
Public Function DateToExcel ( _
    dt As DateTime _
) As Double
Visual C++
public:
virtual double DateToExcel(
    DateTime dt
) sealed

Parameters

dt
Type: System..::.DateTime
Date and time to be converted to an Excel numeric value.

Return Value

A numeric value representing the date in Excel.

Implements

IExcelWrapperEngine..::.DateToExcel(DateTime)
IWrapperEngine..::.DateToExcel(DateTime)

Remarks

This method handles the case where the Excel base date has been to a value other than the standard OADate value.

See Also

ExcelWrapperEngine Class
XllPlus.ComWrappers.Runtime Namespace


Destroy Method

[image]

XLL Wrapper
ExcelWrapperEngine..::.Destroy Method
ExcelWrapperEngine Class See Also Send Feedback
Closes down the owned instance of Excel, cleanly and quietly, and releases resources.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public void Destroy()
Visual Basic (Declaration)
Public Sub Destroy
Visual C++
public:
virtual void Destroy() sealed

Implements

IExcelWrapperEngine..::.Destroy()()()

Remarks

Call this method to terminate an instance that was initialized using Create()()().

This method is called automatically by Dispose()()() for instances that were initialized using Create()()().

See Also

ExcelWrapperEngine Class
XllPlus.ComWrappers.Runtime Namespace


Detach Method

[image]

XLL Wrapper
ExcelWrapperEngine..::.Detach Method
ExcelWrapperEngine Class See Also Send Feedback
Detaches the Excel Application instance from the object.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public void Detach()
Visual Basic (Declaration)
Public Sub Detach
Visual C++
public:
virtual void Detach() sealed

Implements

IExcelWrapperEngine..::.Detach()()()

Remarks

Call this method to terminate an instance that was initialized using Attach(Object).

This method is called automatically by Dispose()()() for instances that were initialized using Attach(Object).

See Also

ExcelWrapperEngine Class
XllPlus.ComWrappers.Runtime Namespace


Dispose Method

[image]

XLL Wrapper
ExcelWrapperEngine..::.Dispose Method
ExcelWrapperEngine Class See Also Send Feedback
Unloads all resources used by the class.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public void Dispose()
Visual Basic (Declaration)
Public Sub Dispose
Visual C++
public:
virtual void Dispose() sealed

Implements

IDisposable..::.Dispose()()()

Remarks

Since the resources used by the implementation class may include a dedicated instance of the Excel application, this method should be used as soon as the object is no longer in use. Note that an instance of a derived wrapper class may efficiently be used in a C# using statement or a Visual Basic With statement.

See Also

ExcelWrapperEngine Class
XllPlus.ComWrappers.Runtime Namespace


LoadXll Method

[image]

XLL Wrapper
ExcelWrapperEngine..::.LoadXll Method
ExcelWrapperEngine Class See Also Send Feedback
Loads the specified XLL into the engine.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public void LoadXll(
    string xllPath
)
Visual Basic (Declaration)
Public Sub LoadXll ( _
    xllPath As String _
)
Visual C++
public:
virtual void LoadXll(
    String^ xllPath
) sealed

Parameters

xllPath
Type: System..::.String
Full path to a XLL file that contains add-in functions to be wrapped.

Implements

IExcelWrapperEngine..::.LoadXll(String)
IWrapperEngine..::.LoadXll(String)

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | Thrown if the XLL cannot be loaded, or if no functions are loaded from it.

See Also

ExcelWrapperEngine Class
XllPlus.ComWrappers.Runtime Namespace


IExcelWrapperEngine Interface

[image]

XLL Wrapper
IExcelWrapperEngine Interface
Members See Also Send Feedback
Default interface for class ExcelWrapperEngine, for use by COM objects

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public interface IExcelWrapperEngine
Visual Basic (Declaration)
Public Interface IExcelWrapperEngine
Visual C++
public interface class IExcelWrapperEngine

See Also

IExcelWrapperEngine Members
XllPlus.ComWrappers.Runtime Namespace


IExcelWrapperEngine Members

[image] [image]

XLL Wrapper
IExcelWrapperEngine Members
IExcelWrapperEngine Interface Methods See Also Send Feedback

The IExcelWrapperEngine type exposes the following members.

Methods

Name | Description
Attach | Prepares the object for use by attaching to the specified Excel application instance and initializing the date offset.
CallExcel | Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments.
CallExcelWithErrorCheck | Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments, and raises an error under the conditions specified.
Create | Prepares the object for use by creating an owned instance of Excel, making it invisible, and initializing the date offset.
DateFromExcel | Converts a numeric date value used by Excel to a .NET DateTime.
DateToExcel | Converts a .NET DateTime to a numeric date value used by Excel.
Destroy | Closes down the owned instance of Excel, cleanly and quietly, and releases resources.
Detach | Detaches the Excel Application instance from the object.
LoadXll | Loads the specified XLL into the engine.

See Also

IExcelWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


IExcelWrapperEngine Methods

[image] [image]

XLL Wrapper
IExcelWrapperEngine Methods
IExcelWrapperEngine Interface See Also Send Feedback

The IExcelWrapperEngine type exposes the following members.

Methods

Name | Description
Attach | Prepares the object for use by attaching to the specified Excel application instance and initializing the date offset.
CallExcel | Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments.
CallExcelWithErrorCheck | Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments, and raises an error under the conditions specified.
Create | Prepares the object for use by creating an owned instance of Excel, making it invisible, and initializing the date offset.
DateFromExcel | Converts a numeric date value used by Excel to a .NET DateTime.
DateToExcel | Converts a .NET DateTime to a numeric date value used by Excel.
Destroy | Closes down the owned instance of Excel, cleanly and quietly, and releases resources.
Detach | Detaches the Excel Application instance from the object.
LoadXll | Loads the specified XLL into the engine.

See Also

IExcelWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


Attach Method

[image]

XLL Wrapper
IExcelWrapperEngine..::.Attach Method
IExcelWrapperEngine Interface See Also Send Feedback
Prepares the object for use by attaching to the specified Excel application instance and initializing the date offset.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
void Attach(
    Object app
)
Visual Basic (Declaration)
Sub Attach ( _
    app As Object _
)
Visual C++
void Attach(
    Object^ app
)

Parameters

app
Type: System..::.Object
A valid instance of Excel, which can be acquired in VBA by passing the global variable Application.

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | Thrown if app is not a valid Application object.

See Also

IExcelWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


CallExcel Method

[image]

XLL Wrapper
IExcelWrapperEngine..::.CallExcel Method
IExcelWrapperEngine Interface See Also Send Feedback
Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
Object CallExcel(
    string fnName,
    params Object[] arguments
)
Visual Basic (Declaration)
Function CallExcel ( _
    fnName As String, _
    ParamArray arguments As Object() _
) As Object
Visual C++
Object^ CallExcel(
    String^ fnName,
    ... array<Object^>^ arguments
)

Parameters

fnName
Type: System..::.String
The name of the function, as visible in Excel.
arguments
Type: array< System..::.Object >[]()[]
The arguments to the add-in function.

Return Value

The variant type that was returned by Excel.

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | Thrown if Excel is unable to call the function, or if Excel rejects the inputs.

See Also

IExcelWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


CallExcelWithErrorCheck Method

[image]

XLL Wrapper
IExcelWrapperEngine..::.CallExcelWithErrorCheck Method
IExcelWrapperEngine Interface See Also Send Feedback
Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments, and raises an error under the conditions specified.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
Object CallExcelWithErrorCheck(
    string fnName,
    bool raiseExceptionOnExcelError,
    string[] errorStringPrefixes,
    params Object[] arguments
)
Visual Basic (Declaration)
Function CallExcelWithErrorCheck ( _
    fnName As String, _
    raiseExceptionOnExcelError As Boolean, _
    errorStringPrefixes As String(), _
    ParamArray arguments As Object() _
) As Object
Visual C++
Object^ CallExcelWithErrorCheck(
    String^ fnName,
    bool raiseExceptionOnExcelError,
    array<String^>^ errorStringPrefixes,
    ... array<Object^>^ arguments
)

Parameters

fnName
Type: System..::.String
The name of the function, as visible in Excel.
raiseExceptionOnExcelError
Type: System..::.Boolean
If true, then when Excel returns an error value, such as #VALUE!, an error is raised. If false, then the error value is returned.
errorStringPrefixes
Type: array< System..::.String >[]()[]
If not null or empty, then if Excel returns a string value which begins with any of these prefixes, an error is raised.
arguments
Type: array< System..::.Object >[]()[]
The arguments to the add-in function.

Return Value

The variant type returned by Excel.

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | Thrown if Excel is unable to call the function, or if Excel rejects the inputs, or if Excel returns an error value (e.g. #VALUE!) or if a string result containing an error description is returned.

See Also

IExcelWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


Create Method

[image]

XLL Wrapper
IExcelWrapperEngine..::.Create Method
IExcelWrapperEngine Interface See Also Send Feedback
Prepares the object for use by creating an owned instance of Excel, making it invisible, and initializing the date offset.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
void Create()
Visual Basic (Declaration)
Sub Create
Visual C++
void Create()

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | Thrown if a COM error occurs or if the object has already been initialized.

See Also

IExcelWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


DateFromExcel Method

[image]

XLL Wrapper
IExcelWrapperEngine..::.DateFromExcel Method
IExcelWrapperEngine Interface See Also Send Feedback
Converts a numeric date value used by Excel to a .NET DateTime.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
DateTime DateFromExcel(
    double d
)
Visual Basic (Declaration)
Function DateFromExcel ( _
    d As Double _
) As DateTime
Visual C++
DateTime DateFromExcel(
    double d
)

Parameters

d
Type: System..::.Double
An Excel numeric value to be converted to .NET DateTime.

Return Value

A .NET DateTime equivalent to the Excel date/time value.

Remarks

This method handles the case where the Excel base date has been to a value other than the standard OADate value.

See Also

IExcelWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


DateToExcel Method

[image]

XLL Wrapper
IExcelWrapperEngine..::.DateToExcel Method
IExcelWrapperEngine Interface See Also Send Feedback
Converts a .NET DateTime to a numeric date value used by Excel.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
double DateToExcel(
    DateTime dt
)
Visual Basic (Declaration)
Function DateToExcel ( _
    dt As DateTime _
) As Double
Visual C++
double DateToExcel(
    DateTime dt
)

Parameters

dt
Type: System..::.DateTime
Date and time to be converted to an Excel numeric value.

Return Value

A numeric value representing the date in Excel.

Remarks

This method handles the case where the Excel base date has been to a value other than the standard OADate value.

See Also

IExcelWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


Destroy Method

[image]

XLL Wrapper
IExcelWrapperEngine..::.Destroy Method
IExcelWrapperEngine Interface See Also Send Feedback
Closes down the owned instance of Excel, cleanly and quietly, and releases resources.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
void Destroy()
Visual Basic (Declaration)
Sub Destroy
Visual C++
void Destroy()

See Also

IExcelWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


Detach Method

[image]

XLL Wrapper
IExcelWrapperEngine..::.Detach Method
IExcelWrapperEngine Interface See Also Send Feedback
Detaches the Excel Application instance from the object.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
void Detach()
Visual Basic (Declaration)
Sub Detach
Visual C++
void Detach()

See Also

IExcelWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


LoadXll Method

[image]

XLL Wrapper
IExcelWrapperEngine..::.LoadXll Method
IExcelWrapperEngine Interface See Also Send Feedback
Loads the specified XLL into the engine.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
void LoadXll(
    string xllPath
)
Visual Basic (Declaration)
Sub LoadXll ( _
    xllPath As String _
)
Visual C++
void LoadXll(
    String^ xllPath
)

Parameters

xllPath
Type: System..::.String
Full path to a XLL file that contains add-in functions to be wrapped.

Exceptions

Exception | Condition
XllPlus.ComWrappers.Runtime..::.XllWrapperException | Thrown if the XLL cannot be loaded, or if no functions are loaded from it.

See Also

IExcelWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


IWrapperEngine Interface

[image]

XLL Wrapper
IWrapperEngine Interface
Members See Also Send Feedback
Public interface supported by Excel wrapper implementation classes.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public interface IWrapperEngine
Visual Basic (Declaration)
Public Interface IWrapperEngine
Visual C++
public interface class IWrapperEngine

See Also

IWrapperEngine Members
XllPlus.ComWrappers.Runtime Namespace


IWrapperEngine Members

[image] [image]

XLL Wrapper
IWrapperEngine Members
IWrapperEngine Interface Methods See Also Send Feedback

The IWrapperEngine type exposes the following members.

Methods

Name | Description
CallExcel | Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments.
CallExcelWithErrorCheck | Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments, and raises an error under the conditions specified.
DateFromExcel | Converts a numeric date value used by Excel to a .NET DateTime.
DateToExcel | Converts a .NET DateTime to a numeric date value used by Excel.
LoadXll | Loads the specified XLL into the engine.

See Also

IWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


IWrapperEngine Methods

[image] [image]

XLL Wrapper
IWrapperEngine Methods
IWrapperEngine Interface See Also Send Feedback

The IWrapperEngine type exposes the following members.

Methods

Name | Description
CallExcel | Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments.
CallExcelWithErrorCheck | Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments, and raises an error under the conditions specified.
DateFromExcel | Converts a numeric date value used by Excel to a .NET DateTime.
DateToExcel | Converts a .NET DateTime to a numeric date value used by Excel.
LoadXll | Loads the specified XLL into the engine.

See Also

IWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


CallExcel Method

[image]

XLL Wrapper
IWrapperEngine..::.CallExcel Method
IWrapperEngine Interface See Also Send Feedback
Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
Object CallExcel(
    string fnName,
    params Object[] arguments
)
Visual Basic (Declaration)
Function CallExcel ( _
    fnName As String, _
    ParamArray arguments As Object() _
) As Object
Visual C++
Object^ CallExcel(
    String^ fnName,
    ... array<Object^>^ arguments
)

Parameters

fnName
Type: System..::.String
The name of the function, as visible in Excel.
arguments
Type: array< System..::.Object >[]()[]
The arguments to the add-in function.

Return Value

The variant type returned by Excel.

See Also

IWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


CallExcelWithErrorCheck Method

[image]

XLL Wrapper
IWrapperEngine..::.CallExcelWithErrorCheck Method
IWrapperEngine Interface See Also Send Feedback
Invokes the controlled Excel instance and evaluates the named add-in function, using the specified parameter list of arguments, and raises an error under the conditions specified.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
Object CallExcelWithErrorCheck(
    string fnName,
    bool raiseExceptionOnExcelError,
    string[] errorStringPrefixes,
    params Object[] arguments
)
Visual Basic (Declaration)
Function CallExcelWithErrorCheck ( _
    fnName As String, _
    raiseExceptionOnExcelError As Boolean, _
    errorStringPrefixes As String(), _
    ParamArray arguments As Object() _
) As Object
Visual C++
Object^ CallExcelWithErrorCheck(
    String^ fnName,
    bool raiseExceptionOnExcelError,
    array<String^>^ errorStringPrefixes,
    ... array<Object^>^ arguments
)

Parameters

fnName
Type: System..::.String
The name of the function, as visible in Excel.
raiseExceptionOnExcelError
Type: System..::.Boolean
If true, then when Excel returns an error value, such as #VALUE!, an error is raised. If false, then the error value is returned.
errorStringPrefixes
Type: array< System..::.String >[]()[]
If not null or empty, then if Excel returns a string value which begins with any of these prefixes, an error is raised.
arguments
Type: array< System..::.Object >[]()[]
The arguments to the add-in function.

Return Value

The variant type returned by Excel.

See Also

IWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


DateFromExcel Method

[image]

XLL Wrapper
IWrapperEngine..::.DateFromExcel Method
IWrapperEngine Interface See Also Send Feedback
Converts a numeric date value used by Excel to a .NET DateTime.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
DateTime DateFromExcel(
    double d
)
Visual Basic (Declaration)
Function DateFromExcel ( _
    d As Double _
) As DateTime
Visual C++
DateTime DateFromExcel(
    double d
)

Parameters

d
Type: System..::.Double
An Excel numeric value to be converted to .NET DateTime.

Return Value

A .NET DateTime equivalent to the Excel date/time value.

See Also

IWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


DateToExcel Method

[image]

XLL Wrapper
IWrapperEngine..::.DateToExcel Method
IWrapperEngine Interface See Also Send Feedback
Converts a .NET DateTime to a numeric date value used by Excel.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
double DateToExcel(
    DateTime dt
)
Visual Basic (Declaration)
Function DateToExcel ( _
    dt As DateTime _
) As Double
Visual C++
double DateToExcel(
    DateTime dt
)

Parameters

dt
Type: System..::.DateTime
Date and time to be converted to an Excel numeric value.

Return Value

A numeric value representing the date in Excel.

See Also

IWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


LoadXll Method

[image]

XLL Wrapper
IWrapperEngine..::.LoadXll Method
IWrapperEngine Interface See Also Send Feedback
Loads the specified XLL into the engine.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
void LoadXll(
    string xllPath
)
Visual Basic (Declaration)
Sub LoadXll ( _
    xllPath As String _
)
Visual C++
void LoadXll(
    String^ xllPath
)

Parameters

xllPath
Type: System..::.String
Full path to a XLL file that contains add-in functions to be wrapped.

See Also

IWrapperEngine Interface
XllPlus.ComWrappers.Runtime Namespace


XllWrapperException Class

[image]

XLL Wrapper
XllWrapperException Class
Members See Also Send Feedback
Represents errors that occur during the execution of XLL add-in functions.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public class XllWrapperException : Exception
Visual Basic (Declaration)
Public Class XllWrapperException _
    Inherits Exception
Visual C++
public ref class XllWrapperException : public Exception

Inheritance Hierarchy

System..::.Object
System..::.Exception
XllPlus.ComWrappers.Runtime..::.XllWrapperException

See Also

XllWrapperException Members
XllPlus.ComWrappers.Runtime Namespace


XllWrapperException Members

[image] [image]

XLL Wrapper
XllWrapperException Members
XllWrapperException Class Constructors See Also Send Feedback

Constructors

Name | Description
XllWrapperException | Overloaded.

See Also

XllWrapperException Class
XllPlus.ComWrappers.Runtime Namespace


XllWrapperException Constructor

[image] [image]

XLL Wrapper
XllWrapperException Constructor
XllWrapperException Class See Also Send Feedback

Overload List

Name | Description
XllWrapperException(String) | Initializes a new instance of the XllWrapperException class with a specified error message.
XllWrapperException(String, Exception) | Initializes a new instance of the XllWrapperException class with a specified error message and a reference to the inner exception that is the cause of this exception.

See Also

XllWrapperException Class
XllWrapperException Members
XllPlus.ComWrappers.Runtime Namespace


XllWrapperException Constructor (String)

[image]

XLL Wrapper
XllWrapperException Constructor (String)
XllWrapperException Class See Also Send Feedback
Initializes a new instance of the XllWrapperException class with a specified error message.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllWrapperException(
    string message
)
Visual Basic (Declaration)
Public Sub New ( _
    message As String _
)
Visual C++
public:
XllWrapperException(
    String^ message
)

Parameters

message
Type: System..::.String
The message that describes the error.

See Also

XllWrapperException Class
XllWrapperException Overload
XllPlus.ComWrappers.Runtime Namespace


XllWrapperException Constructor (String, Exception)

[image]

XLL Wrapper
XllWrapperException Constructor (String, Exception)
XllWrapperException Class See Also Send Feedback
Initializes a new instance of the XllWrapperException class with a specified error message and a reference to the inner exception that is the cause of this exception.

Namespace: XllPlus.ComWrappers.Runtime
Assembly: XllPlus.ComWrappers.Runtime (in XllPlus.ComWrappers.Runtime.dll) Version: 7.0.6.102 (7.0.6.0102)

Syntax

C#
public XllWrapperException(
    string message,
    Exception innerException
)
Visual Basic (Declaration)
Public Sub New ( _
    message As String, _
    innerException As Exception _
)
Visual C++
public:
XllWrapperException(
    String^ message,
    Exception^ innerException
)

Parameters

message
Type: System..::.String
The error message that explains the reason for the exception.
innerException
Type: System..::.Exception
The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.

See Also

XllWrapperException Class
XllWrapperException Overload
XllPlus.ComWrappers.Runtime Namespace


Technical notes

This section contains a number of miscellaneous technical notes. Please use the contents tree to explore them.


XLL+ Change History

XLL+ version history is detailed below.

7.0.6

Date: | 28-February-2014
Description: | First release for Visual Studio 2013 and maintenance release for other versions
Files: | setup_xlp7_80T_7_0_6.exe setup_xlp7_80R_7_0_6.exe setup_xlp7_90T_7_0_6.exe setup_xlp7_90R_7_0_6.exe setup_xlp7_100T_7_0_6.exe setup_xlp7_100R_7_0_6.exe setup_xlp7_110T_7_0_6.exe setup_xlp7_110R_7_0_6.exe setup_xlp7_120T_7_0_6.exe setup_xlp7_120R_7_0_6.exe
Item | Change | Description
E00250 | NEW - CXlMenu::GetCallingMenu under Excel 2007 | This method can return wrong results when called under Excel 2007 (Excel 12). This is due to an as yet unresolved bug in that version of Excel, which has been fixed in later versions. A new method CXlMenu::GetCallingMenuItemPosition has been added to the CXlMenu class, which works around the bug, and returns correct results under all Excel versions.
E00251 | NEW - WorkbookAfterSave and AfterCalculate events | Two new COM event handlers have been added to the library, to handle the WorkbookAfterSave and AfterCalculate events, introduced in Excel 2010. These event handlers will have no effect under earlier versions of Excel.
E00252 | NEW - Shared object handles | Object handles created using the non-RTD handle mechanisms (StringHandle, NumericHandle etc) can be shared between different add-ins. They can be created in one XLL and consumed in a separate XLL, by using the new HandleCache import and export manager mechanism.
E00253 | NEW - Using object handles in macros | A new macro function (MonteCarlo2.InspectHandle) has been added to the MonteCarlo2 sample project, to show how to use object handles from macro functions.
E00254 | NEW - Function publishing filter | A new class (CXllFunctionFilter) is included, which allows the developer full control over which functions are published in an XLL, and which are suppressed. Two example projects are provided to illustrate the use of the filter.
E00255 | NEW - Handles for classes with namespaces and templates | It is now possible to create handles for objects that have namespaces in the class name or that are the result of templates. See the StringHandleDemo and RtdHandleDemo samples for examples of this use.
E00256 | NEW - CXllApp::GetRibbonCallbackFunctionName and CXllApp::GetObserverFunctionName | Two new methods for CXllApp expose the published names of the framework-generated add-in functions.
E00257 | NEW - Accurate conversion for numerics to strings | If numeric cells were converted automatically to strings as part of a generated input conversion, rounding in XLL+ 6.0 to XLL+ 7.0.4 was to 6 decimal places. A new method CXllApp::SetNumericToStringConversionMethod() has been provided which emulates the behavior of XLL+ 5 and earlier versions, thereby offering the same conversion accuracy as Excel itself.
E00258 | NEW - Visual Studio 2013 | A new version has been released which supports Visual Studio 2013.
F00160 | FIX - Two-dimensional input arrays containing empty cells can cause an input error | The conversion of two-dimensional input arrays can return an error when some empty cells are contained within the array and at its boundaries. This behavior has been fixed.
F00161 | FIX - StringHandles | Certain invalid string handles could cause the StringHandles extension to crash when they were decoded. This behavior has been fixed.
F00162 | FIX - CXlOper::AllocArray for a zero-size array | CXlOper::AllocArray caused run-time errors if a zero-size array was allocated. This behavior has been fixed, and an exception is thrown, resulting in a returned value of #VALUE!
F00163 | FIX - Signing problem with on-line help | In XLL+ 7.0.4 for Visual Studio 2010 and above, a problem occurred when installing the on-line help integrated into Visual Studio. This was due to a problem with the certificate used to sign the help. The problem has been resolved.

7.0.4

Date: | 10-December-2012
Description: | First release for Visual Studio 2012 and maintenance release for other versions
Files: | setup_xlp7_80T_7_0_4.exe setup_xlp7_80R_7_0_4.exe setup_xlp7_90T_7_0_4.exe setup_xlp7_90R_7_0_4.exe setup_xlp7_100T_7_0_4.exe setup_xlp7_100R_7_0_4.exe setup_xlp7_110T_7_0_4.exe setup_xlp7_110R_7_0_4.exe
Item | Change | Description
E00238 | NEW - Visual Studio 2012 | A new version has been released which supports Visual Studio 2012.
E00239 | NEW - Rolling file appender | A new appender has been added to the set of logging options. The rolling file appender writes to a new log file each day (or month, or hour, as controlled by the configuration).
E00240 | NEW - ExcepExt sample project | A new sample project, ExcepExt, has been added, which demonstrates how to use a function extension to automate the handling of common exceptions.
E00242 | NEW - Handle lifetime management | Changes have been made to the RTD handle implementation to allow the handles created to persist longer than the lifetime granted by Excel, by locking them into memory from procedural code.
E00243 | NEW - Default values for new functions | New application-level settings have been added, so that the user can specify default values for properties applied to new functions: DoNotCallInExcelFormulaWizard and DoNotCatchStructuredExceptions.
E00244 | NEW - Default values for new arguments | New application-level settings have been added, so that the user can specify default values for properties applied to new arguments, including DefaultFillArrayBehavior and DefaultFillArrayTargets.
E00245 | NEW - Structured exception handlers can be suppressed | By setting the compiler macro XLP_SUPPRESS_SEH, the impact of all Structured Exception Handler generated code can be suppressed.
E00246 | NEW - Fast iterators for large arrays | A set of fast iterator classes have been provided in XlpFastIt.h, which offer optimally fast read access to large arrays of Excel cell values.
E00247 | NEW - XLPGEN code generator | XLPGEN.EXE is a command line utility that can be used to generate C++ code for XLL add-in functions from XML files containing function definitions. It can be used as part of an automated build process.
E00248 | NEW - CXlValueListWriter | A new run-time class, CXlValueListWriter, is used to generate lists of value/name pairs for Value Lists. This technique allows enum values to be used for values, as well as integers.
E00249 | NEW - LockableHandles sample project | A new sample project has been provided, to demonstrate the use of lockable handles and the LockableHandleCache class.
F00155 | FIX - In Argument Editor, 'Show Popup in Wizard' can be misplaced. | In the detailed argument editor, on the General pane, the checkbox 'Show Popup in Wizard' is fixed in place, and does not move correctly when the dialog is resized. This behavior has been fixed.
F00156 | FIX - After Visual Studio 2012 is installed, the Function Wizard stops working. | After the installation of any version of Visual Studio 2012, including Beta, Release Candidate and RTM, the XLL+ Function Wizard under earlier versions of Visual Studio fails with the following error: System.Runtime.Serialization.SerializationException: Unable to find assembly 'Psl.XL7.FunctionModel, Version=7.0.3.102, Culture=neutral, PublicKeyToken=b753a985dcbde9e1'. This behavior, which was due to changes in the .NET 4.5 runtime, has been fixed.
F00157 | FIX - Vectors with lower bounds wrongly assigned | The method CXlOper::FromVectorWithoutClearing() was ignoring the lbound parameter when allocating a new CXlOper array. This behavior has been fixed.

7.0.3

Date: | 14-February-2012
Description: | Maintenance release
Files: | setup_xlp7_80T_7_0_3.exe setup_xlp7_80R_7_0_3.exe setup_xlp7_90T_7_0_3.exe setup_xlp7_90R_7_0_3.exe setup_xlp7_100T_7_0_3.exe setup_xlp7_100R_7_0_3.exe
Item | Change | Description
E00232 | NEW - ArrayHandles sample | A new sample has been added which demonstrates how to use RTD handles to represent arrays of numbers. This allows a whole array to be represented by a single cell.
E00233 | NEW - Unused ribbon controls are hidden | By default, a getVisible attribute is added to the top-level control of the ribbon generated by the XLL+ AppWizard. The GetVisible event is also handled in the skeleton code produced by the AppWizard. As a result, the ribbon controls of an add-in are automatically hidden when the add-in is unloaded.
E00234 | NEW - RTD Handles can be created in array functions | It is now possible to create arrays of RTD handles in an add-in function that returns an array result. Previously, handles had to be created within functions that returned a single cell.
E00235 | NEW - AppWizard help | A new topic has been added to the help, containing instructions for adding AppWizard-generated features through code.
E00236 | NEW - GPU/CUDA documentation | New topics have been added to the online help, discussing how to support massively parallel processing using CUDA code with Graphical Processor Units.
E00237 | NEW - AvgOptCuda sample | A new sample has been added, which demonstrates the use of CUDA to enable GPU parallel processing in XLL add-ins.
F00147 | FIX - Ribbon callback function fails to register | If a project which uses the Excel Ribbon has a name which includes a space, then the ribbon callback function fails to register. A message appears when the add-in is opened, and all ribbon events are ignored. This behaviour has been fixed.
F00148 | FIX - Cells of CXlOper arrays cannot be copied from error values | The method CXlCell::operator=(const CXlOperBase& src) throws a run-time error if the source cell contains an Excel error value. This behavior has been fixed.
F00149 | FIX - Rtd Handle creation fails if handle creator is called from a worker thread | Rtd Handle creation fails if handle creator is called from a different thread from the Excel User Interface. This behavior has been fixed, by disallowing the Thread safe attribute on handle creator functions.
F00150 | FIX - Queued functions cause a compiler error | An add-in function marked as Queued causes a compiler error "error C2065: 'xlAsyncReturn' : undeclared identifier" unless xlcallfnids.h is also #included. This behavior has been fixed
F00151 | FIX - Error in User Guide topic 'Asynchronous function support in projects' | The User Guide topic refers to wizard-generated code including an instance of the CRtdLink class, which has been deprecated since XLL+ 7.0.0. This has been fixed.
F00152 | FIX - Extended UI displaying incorrectly in Excel Formula Wizard for nested formulae | Formulae which included a nested function with an extended user interface were often displayed incorrectly in the Excel Formula Wizard, when the outer function did not have an extended UI. This behavior has been fixed.
F00153 | FIX - The buttons for the Extended UI were wrongly positioned on screens with magnified DPI settings | On machines with non-standard DPI settings (such as portable computers) the buttons on the extended UI displayed in the Excel Formula Wizard were placed incorrectly. This behavior has been fixed.
F00154 | FIX - Function Wizard layout problems on screens with magnified DPI settings | On machines with non-standard DPI settings (such as portable computers) some of the labels of the XLL+ Function Wizard were overwritten. This behavior has been fixed.

7.0.2

Date: | 14-August-2011
Description: | Maintenance release
Files: | setup_xlp7_80T_7_0_2.exe setup_xlp7_80R_7_0_2.exe setup_xlp7_90T_7_0_2.exe setup_xlp7_90R_7_0_2.exe setup_xlp7_100T_7_0_2.exe setup_xlp7_100R_7_0_2.exe
Item | Change | Description
F00138 | FIX - Project Upgrade Wizard on machines without 64-bit tools | The project upgrade wizard failed on installations where the Visual Studio 64-bit libraries and tools had not been installed. This behavior has been fixed.
F00139 | FIX - XLL+ AppWizard on machines without 64-bit tools | The XLL+ AppWizard failed on installations where the Visual Studio 64-bit libraries and tools had not been installed. This behavior has been fixed.
F00140 | FIX - Upgrade Wizard Report - Bad link | The Project Upgrade Wizard produced a bad link to the XLL+ help page for "Breaking Changes". This has been fixed.
F00141 | FIX - Help Generator: omitting default text for optional arguments | Argument help for optional arguments was still being generated when the Position attribute was set to 'Replace'. This behavior has been fixed, and the default value description is now omitted.
F00142 | FIX - CXlFuncs Lookup and Reference Functions | A number of CXlFuncs methods take parameters that represent a row or column index, but are represented only as small integer types. New or changed versions of each of these methods have been provided so that the row or column index is a large integer type, as required by Excel 2007 and above. The following are affected: CXlFuncs::Address, CXlFuncs::HLookup, CXlFuncs::Index, CXlFuncs::Match, CXlFuncs::Offset, CXlFuncs::VLookup
F00143 | FIX - CXlMacros Range Functions | A number of CXlMacros methods take parameters that represent a row or column index, but are represented only as small integer types. New or changed versions of each of these methods have been provided so that the row or column index is a large integer type, as required by Excel 2007 and above. The following are affected: CXlMacros::HLine, CXlMacros::HPage, CXlMacros::VLine, CXlMacros::VPage.
F00145 | FIX - Async functions with string arguments fail | If multiple instances exist of an asynchronous function with one or more string arguments, then the string argument passed to the function is arbitrary. This behavior has been fixed.
F00146 | FIX - .NET Reflection - Null values in string arrays are now converted to empty strings | For wrapped functions which return string arrays, any contained null values are now converted to empty strings. Previously an exception was thrown.

7.0.0

Date: | 25-March-2011
Description: | Major commercial release
Files: | setup_xlp7_80T_7_0_0.exe setup_xlp7_80R_7_0_0.exe setup_xlp7_90T_7_0_0.exe setup_xlp7_90R_7_0_0.exe setup_xlp7_100T_7_0_0.exe setup_xlp7_100R_7_0_0.exe
Item | Change | Description
E00221 | NEW - 64-bit support for Excel 2010 | XLL+ projects can now be built as 32-bit or 64-bit binaries.
E00222 | NEW - Support for the Ribbon | XLL+ add-ins can now add content to the Office Ribbon.
E00223 | NEW - Support for Excel 2010 asynchronous function implementations | XLL+ add-in functions can be marked as 'asynchronous' so that they queue efficiently for shared, lockable resources. Threading and marshalling code is generated to support the required asynchronous implementation.
E00224 | NEW - New functions are thread-safe | New functions are marked as thread-safe by default. The global setting DefaultIsThreadSafe can be used to control this behavior.
E00225 | NEW - CXllApp::GetXllFileName, CXllApp::GetXllFileNameOnly | Two new helper methods provide parts of the current XLL's path.
E00226 | NEW - Async functions are supported by all add-ins | It is no longer necessary to insert a CRtdLink object in an application class, in order to support asynchronous functions. An instance of a new class, CRtdAsyncManager, is now a member of CXllApp.
E00227 | NEW - Non-RTD handle mechanisms | The non-RTD handle mechanisms (StringHandle, StringPtrHandle and NumericHandle) have been enhanced, to support smart pointers (including boost::shared_ptr) and also custom handle formats.
E00228 | NEW - CXllApp::GetListSeparator, CXllApp::GetRowPrefix, CXllApp::GetColumnPrefix | Three new CXllApp methods can be used to report international settings during worksheet functions (when CXllApp::GetInternational may not be called).
F00133 | FIX - RTD handles fail in Excel 2002 using languages other than English | A bug in Excel 2002 meant that RTD handles usually returned the error "#ERROR: Excel API call RTD failed with error code 32", when working in some languages other than English. A work-around has been applied, so that this behavior has been fixed.

6.3.7

Date: | 14-August-2011
Description: | Maintenance release, superceding 6.3.4 and the 6.3.5 patch
Files: | setup_xlp7_71T_6_3_7.exe setup_xlp7_71R_6_3_7.exe setup_xlp7_80R_6_3_7.exe setup_xlp7_90R_6_3_7.exe setup_xlp7_100R_6_3_7.exe
Item | Change | Description
E00229 | NEW - Non-RTD handle mechanisms | The non-RTD handle mechanisms, StringHandle and StringPtrHandle, have been enhanced to support smart pointers (including boost::shared_ptr) and also custom handle formats.
E00230 | NEW - CXllApp::GetListSeparator, CXllApp::GetRowPrefix, CXllApp::GetColumnPrefix | Three new CXllApp methods can be used to report international settings during worksheet functions (when CXllApp::GetInternational may not be called).
E00231 | NEW - CXllApp::GetXllFileName, CXllApp::GetXllFileNameOnly | Two new helper methods provide parts of the current XLL's path.
F00132 | FIX - .NET Reflection - Null values in string arrays are now converted to empty strings | For wrapped functions which return string arrays, any contained null values are now converted to empty strings. Previously an exception was thrown.
F00134 | FIX - Help Generator: omitting default text for optional arguments | Argument help for optional arguments was still being generated when the Position attribute was set to 'Replace'. This behavior has been fixed, and the default value description is now omitted.
F00135 | FIX - CXlFuncs Lookup and Reference Functions | A number of CXlFuncs methods take parameters that represent a row or column index, but are represented only as small integer types. New or changed versions of each of these methods have been provided so that the row or column index is a large integer type, as required by Excel 2007 and above. The following are affected: CXlFuncs::Address, CXlFuncs::HLookup, CXlFuncs::Index, CXlFuncs::Match, CXlFuncs::Offset, CXlFuncs::VLookup
F00136 | FIX - CXlMacros Range Functions | A number of CXlMacros methods take parameters that represent a row or column index, but are represented only as small integer types. New or changed versions of each of these methods have been provided so that the row or column index is a large integer type, as required by Excel 2007 and above. The following are affected: CXlMacros::HLine, CXlMacros::HPage, CXlMacros::VLine, CXlMacros::VPage.
F00137 | FIX - RTD handles fail in Excel 2002 using languages other than English | A bug in Excel 2002 meant that RTD handles usually returned the error "#ERROR: Excel API call RTD failed with error code 32", when working in some languages other than English. A work-around has been applied, so that this behavior has been fixed.
F00144 | FIX - Async functions with string arguments fail | If multiple instances exist of an asynchronous function with one or more string arguments, then the string argument passed to the function is arbitrary. This behavior has been fixed.

6.3.5

Date: | 5-October-2010
Description: | Patch release, applied to 6.3.4
Files: | xlp71t_6_3_5_101006.zip xlp71r_6_3_5_101006.zip xlp80t_6_3_5_101006.zip xlp80r_6_3_5_101006.zip xlp90t_6_3_5_101006.zip xlp90r_6_3_5_101006.zip xlp100t_6_3_5_101006.zip xlp100r_6_3_5_101006.zip
Item | Change | Description
E00217 | NEW - Code changes to help 64-bit migration | A number of small changes have been made to header files, to ease the future migration path to 64-bit add-ins. These changes have no impact on 32-bit add-ins.
E00218 | NEW - ple::clr::objectToXl | The objectToXl generic conversion function now accepts an optional second argument, which is used to represent null values.
E00219 | NEW - ple::clr::toClrObjectVector and ple::clr::toClrObjectMatrix | The conversion functions toClrObjectVector and toClrObjectMatrix now accept an optional second argument, isOptional. When this is true, missing or empty arguments are transformed to empty object arrays.
F00130 | FIX - IsInFormulaWizard returned true if Find/Replace dialog was open | CXllApp::IsInFormulaWizard() returned true if the Find/Replace dialog was open. This behavior has been fixed, and a new support class, CXlFormulaWizardDetector, has been added, to help detect the Formula Wizard in languages other than English.
F00131 | FIX - RTD handles and async functions failed to be refreshed in some Excel language versions | In languages where a character other than the comma is used for separating arguments, the RTD messages for handles and for asynchronous functions were failing to be delivered. This behavior has been fixed.

6.3.4

Date: | 27-August-2010
Description: | Maintenance release
Files: | setup_xlp6_71T_6_3_4.exe setup_xlp6_71R_6_3_4.exe setup_xlp6_80T_6_3_4.exe setup_xlp6_80R_6_3_4.exe setup_xlp6_90T_6_3_4.exe setup_xlp6_90R_6_3_4.exe setup_xlp6_100T_6_3_4.exe setup_xlp6_100R_6_3_4.exe
Item | Change | Description
E00211 | NEW - .NET Reflection - Variable types | The assembly import tool now treats arguments of type object, object[] or object[,] as inputs of variable type, and automatically translates the Excel inputs to the appropriate .NET value type.
E00212 | NEW - German language resources | Runtime errors are now available in German. Help files can now be generated in German, as well as in English, French and Portuguese.
E00213 | NEW - .NET Reflection - Value lists | The assembly import tool now supports value lists for arguments. Developers can specify value lists, which can be displayed in the Excel Formula Wizard and can also used for validation. Value lists are automatically generated for enumerated types .
E00214 | NEW - Performance enhancements for validation routines | An optimization has been applied to the generated code for optional scalar arguments. The optimization significantly reduces the cost of validating a scalar argument.
E00215 | NEW - Excel Formula Wizard fails for functions with long argument names | The Excel Formula Wizard will fail for functions with many, long argument names. A new validation test has been added to the XLL+ Function Wizard which will show a warning for functions of this type.
E00216 | NEW - Profiling extension and sample - timer improved | A more sensitive timer has been used for the profiling extension.The high-resolution performance counter is used instead of the system timer.
F00123 | FIX - CString::operator+(char) | A compile error was caused by the STL versions of this operator. This has been fixed.
F00124 | FIX - Tools menu commands | The commands "New XLL+ Function…" and "XLL+ Function Wizard…" on the Visual Studio "Tools" menu could fail with an "IndexOutOfRangeExecption" error, if the XLL Add-ins tool window has not been opened. This behavior has been fixed.
F00125 | FIX - XLL Wrapper (Visual Studio 2008 version) no longer depends on .NET runtime 2.0 | The Visual Studio 2008 version of the XLL Wrapper project wizard no longer adds a dependency for .NET runtime 2.0 to new projects. .NET runtime 3.5 is used instead. The developer can still change the targeted run-time at a later date.
F00126 | FIX - XLL Wrapper (Visual Studio 2010 version) no longer depends on .NET runtime 2.0 | The Visual Studio 2010 version of the XLL Wrapper project wizard no longer adds a dependency for .NET runtime 2.0 to new projects. .NET runtime 4.0 is used instead. The developer can still change the targeted run-time at a later date.
F00127 | FIX - .NET Reflection - Externally defined enumerated types | The assembly import tool was failing to import enumerated type arguments whose enumeration class was declared in a separate assembly. This behavior has been fixed.
F00128 | FIX - Failure to read file if //}}XLP_SRC is missing | If the end marker for a function's generated code (//}}XLP_SRC) was removed, then none of the functions in the file were read, and confusing error reports were issued. This behavior has been fixed.

6.3.3

Date: | 24-June-2010
Description: | First release for Visual Studio 2010 and maintenance release for other versions
Files: | setup_xlp6_71T_6_3_3.exe setup_xlp6_71R_6_3_3.exe setup_xlp6_80T_6_3_3.exe setup_xlp6_80R_6_3_3.exe setup_xlp6_90T_6_3_3.exe setup_xlp6_90R_6_3_3.exe setup_xlp6_100T_6_3_3.exe setup_xlp6_100R_6_3_3.exe
Item | Change | Description
F00122 | FIX - Field refresh problems in the Import Editor | In the Assembly Import Editor, changes made to properties in the property grid were not always being immediately displayed. This behavior has been fixed.
E00208 | NEW - Visual Studio 2010 | A new version has been released which supports Visual Studio 2010.
E00209 | NEW - Code-signing | The setup programs and some installed components are now signed by the publisher.
E00210 | NEW - psl::clr::toClrObject | New helper functions ToClrObject(), ToClrObjectVector() and ToClrObjectMatrix() have been added to XlpClrConvert.h, which convert CXlOper values or arrays of arbitrary types to CLR objects and object arrays.

6.3.1

Date: | 1-May-2010
Description: | Maintenance release
Files: | setup_xlp6_71T_6_3_1.exe setup_xlp6_71R_6_3_1.exe setup_xlp6_80T_6_3_1.exe setup_xlp6_80R_6_3_1.exe setup_xlp6_90T_6_3_1.exe setup_xlp6_90R_6_3_1.exe
Item | Change | Description
E00205 | NEW - .NET Reflection | The .NET Reflection tols have been enhanced, and are now more flexible and responsive.
E00206 | NEW - Runtime libraries and headers | A number of small changes have been made to the runtime libraries and headers to make the code compatible with Visual Studio 2010.
E00207 | NEW - Handle types with namespaces | The code generator has been enhanced to support the use of handle types which include namespaces as return values from HandleCreator methods.

6.3.0

Date: | 1-Feb-2010
Description: | Major commercial release
Files: | setup_xlp6_71T.exe setup_xlp6_71R.exe setup_xlp6_80T.exe setup_xlp6_80R.exe setup_xlp6_90T.exe setup_xlp6_90R.exe
Item | Change | Description
F00110 | FIX - RTD Handles and CXllApp::OnExitInstance | A bug in this method was causing Excel to hang during closedown when RTD handles were in use. This has been fixed.
F00111 | FIX - CLR add-ins crash in Tools/Addins | An initialization problem was causing some add-ins built with the CLR release build run-time libraries to crash when added through Tools/Add-ins. This behavior has been fixed.
F00112 | FIX - Help build fails for XLLs whose names contain spaces | The help build command-line failed for projects with spaces in their names. This behavior has been fixed.
F00113 | FIX - Function registration fails for XLLs whose names contain spaces | The XLL+ run-time libraries displayed an error message during function registration for for projects with spaces in their names. This behavior has been fixed.
F00114 | FIX - Value list drop-down in Formula Wizard | If no description is specified for an item, only the name will be displayed, without a superfluous dash.
F00115 | FIX - psl::clr::objectToXl | The objectToXl generic conversion function now handles Decimal types correctly.
F00116 | FIX - CallExcel sample | Under Excel 2007 and above, the add-in function DescribeCell() failed because some cells of the result array were left uninitialized. This has been fixed.
F00117 | FIX - Asynchronous functions - scalability fixes | A number of scalability problems that affected the asynchronous function RTD implementation have been fixed. Performance is much improved, and update failures are now prevented.
F00118 | FIX - Code generator produces code that does not compile by splitting single quoted characters | An error in the code generator allowed some unicode single characters to be split across lines, separating, for example, L';' into two separate lines after the first quote. This behavior has been fixed.
F00119 | FIX - Help generator is ignoring Syntax attribute for some arguments | An error in the help generator was causing the Syntax attribute for some arguments to be ignored. This behavior has been fixed.
F00120 | FIX - Error validating 2-dimensional arguments with extended scalar types and extended parameters | An error in CXlCoreConverterEx::ReadMatrix was causing a false validation error for 2-dimensional arguments of extended scalar types, with extended argument parameters. This has been fixed.
F00121 | FIX - Errors in code produced when importing .NET assemblies. | When importing .NET assemblies, compile errors were produced for handle arguments which were not the same type as the declaring type of the method invoked. This behavior has been fixed.
E00199 | NEW - psl::clr::objectToXl | A new helper function objectToXl() has been added to XlpClrConvert.h, which converts .NET objects of arbitrary types into CXlOper values or arrays.
E00200 | NEW - Implementation code is hidden | Most of the implementation code for add-in functions is now generated in a #pragma region. The Function Wizard automatically hides these regions.
E00201 | NEW - XLL Wrapper | A new set of tools has been added which lets you generate wrapper libraries in .NET and COM, so that you can call Excel add-in functions directly from other applications. A new sample application, ApiTest, has been added, which shows how to call XLL functions from C++, C# and VBA.
E00202 | NEW - Asynchronous functions - performance | The file-based channel used for communicating between threads in asynchronous functions has been replaced with a shared-memory implementation. This has significantly lower performance overhead, and improved scalability.
E00203 | NEW - Value list editor improvements | The value list editor has been improved, with the addition of support for copy/paste and Excel import/export.
E00204 | NEW - Data Feed sample | A new sample application, DemoFeed, has been added. This shows how to use RTD to integrate a real-time data feed into an XLL.

6.2.0

Date: | 1-Jul-2009
Description: | Major commercial release
Files: | setup_xlp6_71T.exe setup_xlp6_71R.exe setup_xlp6_80T.exe setup_xlp6_80R.exe setup_xlp6_90T.exe setup_xlp6_90R.exe
Item | Change | Description
F00100 | FIX - Help build on 64-bit OS | The help build tool (BUILDHELP.EXE) was not running correctly on Windows 64-bit platforms. This behavior has been fixed.
F00101 | FIX - Cache in CLR builds | The value cache was not being correctly used by CLR builds. This has been fixed.
F00102 | FIX - xlhandle.h | xlhandle.h has been amended to work with Unicode and MFC builds.
F00103 | FIX - CXllApp::XlMessageBox | This method was returning an incorrect value for the user's input in some cases. This has been fixed.
F00104 | FIX - CXlOper::GetCaller | This method was causing run-time errors under some circumstances if called from macros. This has been fixed.
F00105 | FIX - CXlControlRefEdit | CXlControlRefEdit::SetRef() was failing for some local addresses. This behavior has been fixed.
F00106 | FIX - CString::TrimRight and TrimLeft | These methods were behaving incorrectly in STL builds of the run-time library. This behavior has been fixed.
F00107 | FIX - Container classes - code generation | An error in the code generation meant that some custom container classes for vectors and matrices, such as TT::vector<T>, were generating incorrect and uncompilable code. This error has been fixed.
F00108 | FIX - Memory leak in CXlOper::FromMRef() | This method was leaking memory when running under Excel 2003 and below. This behaviour has been fixed
F00109 | FIX - CXlControlRefEdit | A bug in Excel causes inconsistent behavior in the RefEdit field when a workbook has a name that includes a space and has a mixture of sheets whose names contain spaces and sheets whose names do not contain spaces. A workaround has been added to the CXlControlRefEdit class to correct this behavior.
E00186 | NEW - Asynchonous functions | The pattern for asynchronous functions has been revised, and is now simpler, faster and less intrusive.
E00187 | NEW - Assembly import | XLL+ 6.2 can create wrapper add-ins from .NET assemblies. These add-ins contain automatically generated functions for all selected methods and properties of the imported .NET assembly.
E00188 | NEW - Logging framework | A new logging framework is included, which makes it simple and quick to write diagnostic information to log files.
E00189 | NEW - Logging sample | A new sample application, LogDemo, has been added, to demonstrate the use of logging in add-ins.
E00190 | NEW - CXlOper::Resize & CXlOper::Offset | Two new methods have been added to CXlOper that simplify manipulating references.
E00191 | NEW - CXlMacros::Split & CXlMacros::FreezePanes | New command methods have been added to CXlMacros.
E00192 | NEW - Formula Wizard Extended User Interface | New functionality has been added to allow add-ins to show drop-downs and popups from within the Excel Formula Wizard.
E00193 | NEW - Value list constraints | A list of values can be added to an argument's specification which will validate an input against a list of expected values.
E00194 | NEW - CXllApp::AfterXllOpen event | A new event has been added, which occurs after all other XllOpen processing
E00195 | NEW - Help command line tool | The usage has been changed, so that paths are now relative and machine-independent wherever possible, making it easier to move XLL+ projects between machines.
E00196 | NEW - Object Handles | A new implementation of object handles, using RTD, has been added. These handles are generally to be preferred to the older handle implementations. They provide real-time object cache synchronization and flexible handle formats.
E00197 | NEW - Value cache files moved to per-user storage | To better the suit the security environments of Windows Vista, Windows 7 and Windows Server, value cache files are now placed in per-user storage, rather than in the Program Files directory tree. The method CXlOperCache::GetUserCacheFilePath() has been added, which returns the default file name for the cache.
E00198 | NEW - Extended user interface | An extended user interface has been added to run within Excel's Formula Wizard. Fields may include drop-down lists and pop-up editors.

6.0.6

Date: | 19-Mar-2009
Description: | Patch release
Files: | xlp_6_0_6_090319_80T.ZIP xlp_6_0_6_090319_80.ZIP xlp_6_0_6_090319_90T.ZIP xlp_6_0_6_090319_90.ZIP
Item | Change | Description
F00098 | FIX - Bug in Upgrade Wizard | Functions upgraded from XLL+ 5, that had arguments whose descriptions contained square braces (e.g. "[Optional] Further text"), failed to be transformed correctly. This behavior has been fixed.
F00099 | FIX - Unicode bugs in Function Wizard | Some Unicode characters in descriptions were causing the XLL+ Function Wizard to generate faulty code, including code that could not be read by the Wizard. This behavior has been fixed.
E00184 | NEW - Minimum-dependency MFC libraries | A new set of run-time libraries has been added for the MFC libraries. These support add-ins which use the C run-time and MFC in a shard library, using compiler settings /MT or /MTd.

6.0.4

Date: | 29-Sep-2008
Description: | Maintenance release
Files: | setup_xlp6_71T.exe setup_xlp6_71R.exe setup_xlp6_80T.exe setup_xlp6_80R.exe setup_xlp6_90T.exe setup_xlp6_90R.exe
Item | Change | Description
E00181 | NEW - .NET Support | Support for .NET integration has been added to the AppWizard and to the XLL+ runtime libraries. Add-ins can now call .NET methods using C++/CLI. A new section has been added to the User Guide to explain how to use .NET methods in XLL+ add-ins.
E00182 | NEW - Concurrent licensing | Concurrent licensing is now fully supported. Users can log on and off license servers from within Visual Studio.
E00183 | NEW - New samples | 3 new samples have been added: ClrDemo, AssemblyDemo and PiaDemo, which demonstrate how to use .NET assemblies from an add-in.
F00094 | FIX - CStringT::ReverseFind | The implementation of this function (in the STL builds only) contained an error which usually resulted in searches failing. This has been fixed.
F00095 | FIX - CXlFuncs methods | A number of methods of CXlFuncs failed to catch Excel errors, and returned invalid results in these cases. This has been fixed.
F00096 | FIX - Date methods (xlldate.h) | A number of date functions declared in xlldate.h failed to catch Excel errors, and returned invalid results in these cases. This has been fixed.
F00097 | FIX - CXlDate mehods | A number of CXlDate methods failed to catch Excel errors, and returned invalid results in these cases. This has been fixed.

6.0.3

Date: | 12-Jun-2008
Description: | Maintenance release
Files: | setup_xlp6_71T.exe setup_xlp6_71R.exe setup_xlp6_80T.exe setup_xlp6_80R.exe setup_xlp6_90T.exe setup_xlp6_90R.exe
Item | Change | Description
F00087 | FIX - CXllApp::XlOpen | If no object descended from CXllApp was instantiated, this method crashed Excel. This behavior has been fixed, so that an error is reported in a message box.
F00088 | FIX - Instability on machines where Visual Studio is also installed | The AppWizard was unstable under VS2003 on machines which had VS2008 also installed. This behavior has been fixed.
F00089 | FIX - UpgradeWizard report | This report is now displayed within Visual Studio, instead of an external browser.
F00090 | FIX - XLL Add-ins Window Toolbar | The commands on the XLL Add-ins Window's toolbar have been rearranged, so that the window fits into a smaller width.
F00091 | FIX - Memory leaks in runtime library | A number of memory leaks were found in the runtime library, affecting arrays and references returned by call-backs to the Excel API. These have been fixed.
F00092 | FIX - RuntimeTypeInfo switched on | The compiler's RuntimeTypeInfo setting is now switched on for all new projects. The Upgrade Wizard also switches it on.
E00177 | NEW - /MD run-time libraries added | A new set of run-time libraries has been added. These support add-ins which use the C run-time in a separate DLL, using compiler settings /MD or /MDd.
E00178 | NEW - Pre-build help compiler step omitted by default | In version 6.0.2 a pre-build help compiler step was added to XLL+ projects, which checked that the arguments to the help compiler were complete. In particular, the step checks each C++ source file for Excel add-in functions; any C++ file that contains such functions is added to the list of input files for the help compioler. This step is now omitted by default; it can be reenabled by changing the SkipHelpBuilderSetup option in the Tools/XLL+/General options page.
E00179 | NEW - Visual Studio 2008 | A new version has been released which supports Visual Studio 2008.
E00180 | NEW - Tools on XLL Add-ins toolbar rearranged | The tools on the XLL Add-ins toolbar have been rearranged, so that the toolbar is less wide. This allows the XLL Add-ins window to be less wide, and allows full access to the toolbar from a narrower window.

6.0.2

Date: | 28-Mar-2008
Description: | Major commercial release
Files: | setup_xlp6_80T.exe setup_xlp6_80R.exe
Item | Change | Description
F00085 | FIX - ple::mtx_transpose, ple::mtx_ptrs::get_ptrs, ple::mtx_flat::get_flat | These methods caused an out-of-bounds exception when applied to an empty matrix. This behavior has been fixed
F00086 | FIX - MAXCOORD sample function in Tutorial1 | This sample function failed if the input array was empty. This behavior has been fixed by using the "Reject Empty Array" flag.
E00165 | NEW - Help command line tool | A command line utility, BUILDHELP.EXE, has been provided so that help systems can be built outside of Visual Studio, as part of an automated build process.
E00166 | NEW - Add external files to help projects | The AdditionalFile element can now be used to add your own pages to generated help projects.
E00167 | NEW - Localized help | Help projects can now be generated in languages other than English.
E00168 | NEW - MAXCOORD sample function in Tutorial1 | This sample function failed if the input array was empty. This behavior has been fixed by using the "Reject Empty Array" flag.
E00169 | NEW - CXlMacros::Error | A new method CXlMacros::Error can be used to switch Excel alerts on and off.
E00170 | NEW - CXlErrorSuspend | A new helper class, CXlErrorSuspend, can be used to temporarily switch off Excel alert dialogs.
E00171 | NEW - French language resources | Runtime errors ar now available in French as well as English.
E00172 | NEW - Macro helpers topic | The User Guide contains a new topic "Macro helpers", which descibes classes which make the user experience more pleasant during the execution of macros.
E00173 | NEW - Add macro command | A new menu command is available to create macro functions in one step.
E00174 | NEW - Help resource files | In the Help generator help file, the new attribute Help/@CopyFileExtensions and the new element ResourceFile allow image and style files to be automatically added to a help project.
E00175 | NEW - New Profiling sample | A new sample project, Profiling, has been added. This demonstrates how to implement a Function Extension.
E00176 | NEW - Help projects build | The building of the help files has been made part of the standard build. The Help commands are therefore no longer present.

6.0.1

Date: | 1-Jan-2008
Description: | Beta release (Visual Studio 2005 only)
Files: | setup_xlp6_80T.exe
Item | Change | Description
E00157 | NEW - Excel 2007 | The design tools and class libraries have been updated to provide support for the new features of Excel 2007.
E00158 | NEW - Unicode | The class libraries now support Unicode builds, as well as ANSI.
E00158 | NEW - XLL Add-ins window | The XLL Add-ins window has been added to the developer toolset. This is a ToolWindow that appears within Visual Studio, and can be used for more efficient editing of XLL+ add-in functions.
E00160 | NEW - Language support for error messages | The run-time error mesages produced by the libraries are now in a resource file, and can be replaced by messages in languages other than English.
E00161 | NEW - Extended types | The XLL+ Function Wizard and class libraries now support the use of user-defined data types, as well as the standard built-in data types.
E00162 | NEW - Function extensions | Developers can define function extensions which can be injected into the code generated by the XLL+ Function Wizard.
E00163 | NEW - Exceptions | Add-in functions can now be exited early by raising an exception derived from CXlRuntimeException.
E00163 | NEW - Help generator | An integrated help generator can be used to generate Compiled Help (CHM) format help files for add-in functions.
E00164 | NEW - COper | The COper class has been merged into the CXlOper class.

5.0.2

Date: | 19-Oct-2006
Description: | Maintenance commercial release
Files: | xlpn_md_5_0_1.zip xlpt_md_5_0_1.zip xlpv_md_5_0_1.zip
Item | Change | Description
E00156 | NEW - /MD and /MDd libraries | Builds of each the XLL+ 5.0.1 for applications built with the /MD or /MDd flags set.

5.0.1

Date: | 7-Mar-2006
Description: | Major commercial release
Files: | xlpu_5_0_1_e.exe xlpn_5_0_1_e.exe xlps_5_0_1_e.exe xlpt_5_0_1_e.exe xlpv_5_0_1_e.exe xlpw_5_0_1_e.exe xlpx_5_0_1_e.exe xlp_demo_5_0_1_e.exe
Item | Change | Description
E00147 | NEW - Support for Visual Studio 2005 | XLL+ version 5 supports Microsoft Visual Studio 2005. The run-time libraries and samples use the new 'safe' functions of the C standard library. The help and user guide integrate fully with the new Visual Studio 2005 help formats and style, and the XLL+ tools work within the VS 2005 environment.
E00148 | NEW - Asynchronous functions using RTD | We've added a new Real-time Data module, along with sample code and a User Guide, to let you write asynchronous functions that calculate in a background, and only return to Excel when a calculation is complete. The module uses Excel's native RTD mechanism to provide an asynchronous calculation implementation that is efficient, stable and unintrusive.
E00149 | NEW - XllHost module | You can now use the wrapper libraries generated by the XLL+ COM Wrapper Generator with XLL Host to run applications on machines that do not have Excel installed. This makes it possible to deliver your Excel add-ins to production environments on business-critical servers without any change to your code.
E00150 | NEW - ColorCell sample | A new sample shows how to set the colors of cells from a macro function.
E00151 | NEW - UseTimer sample | This sample add-in shows how to run a macro function at a specific time.
E00152 | NEW - AvgOptAsync sample | The AvgoptAsync sample demonstrates how to write asynchronous add-in functions that do their work in a separate thread, leaving Excel available and responsive. Excel's built-in RTD mechanism is used to update the target spreadsheet when calculation is complete.
E00153 | NEW - Support for Proxy Libraries | A new virtual method, CXllApp::GetRegDllName, has been added which enables you to register add-in functions that are not contained in the XLL loaded by Excel. This allows the use of boot-strap XLLS, which is necessary for the safe use of the .NET (CLR) run-time libraries from an XLL add-in.
E00154 | NEW - mtx_ptrs::erase method | A new method has been added to the mtx_ptrs template class, which allows you to erase a subset of the columns or rows in the matrix.
E00155 | NEW - CXlFormulaRefresh::RefreshSheet | The CXlFormulaRefresh::RefreshSheet method has been improved, so that it is now much faster to recalculate handles. New methods have also been added: CXlFormulaRefresh::RefreshCell and CXlFormulaRefresh::RefreshRange.
F00080 | FIX - Optional matrices | The Function Wizard was not emitting code to handle matrix inputs that were optional. This behavior has been fixed.
F00081 | FIX - Function name lengths | The Function Wizard restricted all 'C' functions to 32 characters. This constraint was required for Visual C++ 5 and earlier versions. The restriction has now been relaxed to 64 characters.
F00082 | FIX - Argument names containing 'ia' | The Function Wizard was failing to produce code for arguments which included the letters 'ia'. This behavior has been fixed.
F00083 | FIX - Padding of argument descriptions | Under most Excel versions, the Excel Formula Wizard showed two extra characters on most argument descriptions: a space followed by a period. This behavior has been fixed.
F00084 | FIX - Set argument dimensions command | In the XLL+ Function Wizard under XLL+ for Visual Studio .NET, the accelerator keys Ctrl+0, Ctrl+1 and Ctrl+2 should have been setting the dimensions of the selected argument to scalar, vector and matrix respectively, but were being ignored. This behavior has been fixed.

4.3.2

Date: | 11-Jun-2005
Description: | Maintenance commercial release
Files: | xlpu_4_3_2_e.exe xlpn_4_3_2_e.exe xlps_4_3_2_e.exe xlp_demo_4_3_2_e.exe

4.3.1

Date: | 10-Sep-2004
Description: | Maintenance commercial release
Files: | xlpu_4_3_1_e.exe xlpn_4_3_1_e.exe xlps_4_3_1_e.exe xlp_demo_4_3_1_e.exe
Item | Change | Description
F00069 | FIX - CXllApp::GetVersionInfo() | Errors in CXllApp::GetVersionInfo() were causing (i) instability in the STL build and (ii) abnormal string truncation in the MFC build. These have been fixed.
F00070 | FIX - CXlOper & COper vector & matrix template functions | Bugs in the C6 compiler were causing unpredictable compiler crashes when the templated functions of CXlOper and COper were used. All these functions have been reimplemented as macros for the Visual Studio 6 build only, and moved to a separate file "xlptplmc.h". The compiler crashes no longer occur.
F00071 | FIX - CXlRef::ToString() | The class CXlRef was wrongly generating string addresses for cells in column AA. The behavior has been fixed.
F00072 | FIX - CXllApp::SplitSheetName() | CXllApp::SplitSheetName() was wrongly truncating the book portion of a combined sheet name. The behavior has been fixed.
F00073 | FIX - COper::ReadMatrix() & COper::ToMatrix() | COper::ReadMatrix() & COper::ToMatrix() were crashing Excel when the usIgnoreRows or usIgnoreCols parameters were set. The behavior has been fixed.
F00074 | FIX - COM interface failed in non-English versions | The initialization of the COM interface failed in non-English versions of Excel. As a result, events could not be trapped and some samples, including "CalcEvt" would not run. The behavior has been fixed.
F00075 | FIX - Function wizard unable to handle argument names containing 'ia' | The Function wizard was unable to handle argument names containing the character sequence "ia". The behavior has been fixed.
F00076 | FIX - VS6 resource editor unable to edit resources | When the Visual Studio 6 resource editor was used to edit resources in a project built by the XLL+ AppWizard (using STL libraries only), an error occured when the changed resources were saved. This behavior has been fixed: the resource file header is now named resource.h.
F00077 | FIX - Warning from VS.NET resource editor | When the Visual Studio .NET resource editor was used to edit resources in a project built by the XLL+ AppWizard (using STL libraries only), a warning appeared when the changed resources were saved. This behavior has been fixed: the resource file header is now named resource.h.
F00078 | FIX - CXlOper::SetFormula() | CXlOper::SetFormula() was setting A1-style formulae relative to the active cell, rather than relative to the cell whose formula was being set. This behavior has been fixed.
F00079 | FIX - CXlOper::ConvertFormula() | CXlOper::ConvertFormula() was a static function. As a side-effect of this, it was calculating relative addresses wrongly. Thnis design error has been foxed and is now a const CXlOper::ConvertFormula() member function. This may be a breaking change for existing code that uses CXlOper::ConvertFormula().
E00117 | NEW - Serialization classes | The serialization classes (CXlOStream, CXlIStream, CXlSerialData, CXlInputKey, CXlResultSet & CXlOperCache) have been extended for ease of use, and documented.
E00118 | NEW - Serialization sample | A new sample, "Serialize", has been added, which demonstrates the serialization classes.
E00119 | NEW - Grabbing a cell value example code | New example code has been added to show how to grab a cell value from a sheet in a macro add-in.
E00120 | NEW - Tool bars | A new class, CXlToolbar, has been added, which allows the developer to create toolbars, populate them and manage their state.
E00121 | NEW - Toolbar samples | Three new samples, "Toolbar1", "Toolbar2" and "Toolbar3", have been added, which demonstrate the CXlToolbar class.
E00122 | NEW - Creating a long formula | New example code has been added to show how to create a long (>512 characters) formula.
E00123 | NEW - Safe code for .NET runtime | A new sample, "CallDotNet", has been added, which shows how to amend the classes generated by the XLL+ AppWizard, so that they are safe to use with the .NET run-time classes.
E00124 | NEW - CXlOper::AllocArray() | A new variant of the function has been added, that allows all cells to be initialized to a supplied value. The documentation has been corrected.
E00125 | NEW - CXlOper::SetLongFormula() | A new function has been added, that supports setting formulae of more than 255 characters.
E00126 | NEW - New push model | A new version of the Push model has been released, written in Visual Basic for Applications. The model is supplied with source code, and is not supported code. The old C++ Push model, which displays instabilities under Excel 2000, is discontinued.
E00127 | NEW - Formatting cells | New example code has been added to show how to format a range of cells.
E00128 | NEW - International settings | New example code has been added to show how to get the current international settings from Excel.
E00129 | NEW - International information | A new method, CXllApp::GetInternational(), has been added to retrieve the current values of various international settings, including decimal point, thousands separator and list separators.
E00130 | NEW - Creating a workbook | New example code has been added to show how to create and populate a new workbook.
E00131 | NEW - Creating a sheet | New example code has been added to show how to create and populate a new sheet in an existing workbook.
E00132 | NEW - Extracting a range from an array | New example code has been added to show how to extract a range of values from an array argument passed by Excel to an add-in function.
E00133 | NEW - CXllApp::XlInputBox() | A new method, XlInputBox(), has been added to the CXllApp class. This displays a simple input box, with caption title and default value. The user can enter a value or select a range in a spreadsheet.
E00134 | NEW - COM Wrappers | A new tool, ComWrapperGen, has been added. This generates all the source code for a COM wrapper library, which will allow developers to call your XLL add-in functions from stand-alone Visual Basic, C++ and C# applications.
E00135 | NEW - XLL Version function | The built-in version function, optionally built into new add-ins by the AppWizard, now uses the resource file to load the company name.
E00136 | NEW - CXlOper::FromNumericVector | A new method, CXlOper::FromNumericVector(), has been added, to create an add-in result which contains a vector of numbers, from a vector of any numeric type.
E00137 | NEW - AppWizard creates toolbar code | A new option has been added to the toolbar "Add a toolbar". If checked, the AppWizard adds code to create and display a toolbar when the add-in opens.
E00138 | NEW - New CXlOper constructor | A new constructor, CXlOper::CXlOper(const CString&), and assignment operator CXlOper::operator=(const CString&), have been added, for the convenience of passing strings instead of CXlOper arguments.
E00139 | NEW - Localized strings | Most strings can now be localized, so that they appear in the language of the user (if available). A string such as "#123" will be replaced by string resource 123, loaded from the add-in's resource file, in the current language.
E00140 | NEW - Localized argument names | A new field has been added to the Function Wizard, to allow developers to assign resource strings to argument names. The argument names will thus appear in Excel in the language of the user.
E00141 | NEW - New CXlMacros methods | New methods have been added to CXlMacros: GetActiveWorkbookName, GetActiveWorksheetName, WorkbookGetWorksheetCount NewDefaultWorkbook, NewSingleSheetWorkbook, WorkbookMove & WorkbookCopy. All these methods allow you to create and manipulate workbooks and worksheets.
E00142 | NEW - New Macro topics | New topics have been added to the User Guide, discussing the CXlMacros class, how to use cell references and how to manipulate fornlae in cells.
E00143 | NEW - CXlOper::GetLongString() | A new function has been added, that supports retrieving string values which contain more than 255 characters.
E00144 | NEW - CXlRef::MoveBy() | A new function has been added, that supports adding a row and column offset to a range reference.
E00145 | NEW - CXlOper international formulae functions | New functions have been added to CXlOper, to support getting and setting formulae in international format: GetFormulaIntl(), SetFormulaIntl(), SetLongFormulaIntl(), ConvertFormulaIntl() and MakeRefIntl().
E00146 | NEW - CXlRef international strings | New optional arguments have been added to CXlRef::ToString() and CXlRef::FromString(), to support getting and setting RC style cell addresses formulae in international format. A new static method GetRowColumnLetters() can be used to get the petters used for RC style addresses in the langauge of the Excel version being used.

4.2.5

Date: | 11-Jul-2003
Description: | Maintenance commercial release
Files: | xlpu_4_2_5_e.exe xlpn_4_2_5_e.exe xlps_4_2_5_e.exe xlp_demo_4_2_5_e.exe
Item | Change | Description
E00113 | NEW - Visual Studio.NET 2003 support | Support for VS.NET 2003 has been added. The installation programs of XLL+ for .NET and XLL+ Universal will now install the toolkit for VS.NET, VS.NET 2003, or both (for side-by-side installations).
E00114 | NEW - typename keyword | The typename keyword has been added to template definitions in XLL+ header files, as required by VS.NET 2003, in order to conform to the ISO C++ standard. The typename keyword is only used if the compiler version (__MSC_VER) is 1310 or higher. Code using earlier versions of the compiler will not be affected.
E00115 | NEW - Object handles | A new section has been added to the User Guide which describes how to represent C++ objects in spreadsheets as "handles". Two new sample applications using object handles have also been added.
E00116 | NEW - CXlMacros new methods | Some new methods have been added to CXlMacros to support some of the more common calls to GET.CELL, and FORMULA.REPLACE.
F00064 | FIX - ple::mtx_ptrs::operator[] const | The overloaded operator [] const contained a bug which prevented compilation. This has been fixed.
F00065 | FIX - CXlControlListBox | A listbox with no entries caused the containing dialog not to appear. This behavior has been fixed.
F00066 | FIX - ReadMatrix() | COper::ReadMatrix() and CXlOper::ReadMatrix() contained a bug whereby arrays with non-zero lower bounds might be written to using an out-of-bounds index. This behavior has been fixed.
F00067 | FIX - CXlMenu internationalization fix | In versions of Excel that do not use English menu titles, user-defined menus could fail to appear. This behavior has been fixed.
F00068 | FIX - XllGetTypedApp() | The ::XllGetTypedApp() method is now defined inline.

4.2.4

Date: | 3-Mar-2003
Description: | Maintenance commercial release
Files: | xlpu_4_2_4_e.exe xlpn_4_2_4_e.exe xlps_4_2_4_e.exe xlp_demo_4_2_4_e.exe
Item | Change | Description
E00094 | NEW - New classes for calling Excel functions | Two new classes, CXlFuncs and CXlMacros, have been added to simplify calling most Excel worksheet and macro functions from C++.
E00095 | NEW - Sample for calling Excel functions | A new sample CallExcel has been added to demonstrate how to use the CXlMacros and CXlFuncs classes to call Excel functions.
E00096 | NEW - New methods for Binary Names | New methods have been added to handle the DefineBinaryName and GetBinaryName call-backs. These allow you to store binary data in Excel worksheets so that it persists when they are closed and reopened.
E00097 | NEW - Sample for Binary Names | A new sample, BinaryData, has been added to demonstrate how to store binary data in spreadsheets using Binary Names.
F00062 | FIX - Single column COper arrays | COper::AllocArray() failed when an array with one column was created. This behaviour has been fixed.
E00098 | NEW - How Do I... | A new "How Do I..." topic has been added to the on-line help, containing references to the most commonly needed topics.
E00099 | NEW - CXlOper::AllocArray | CXlOper::AllocArray() has a new variant that allows you to initialise all cells immediately after allocation.
F00063 | FIX - Treatment of blank cells in arrays | Under versions 4.2.1 to 4.2.3, COper::ReadVector(), COper::ReadMatrix() and all related array reading methods rejected cells containing empty strings when reading numbers. These cells are now, by default, treated as empty cells.
E00100 | NEW - XlpSetTemplate tool | A new command line tool, XlpSetTemplate.exe, has been provided to let you change the template file used by the XLL+ Function Wizard.
E00101 | NEW - Serialization classes | New serialization classes, CXlSerialData and CXlInputKey, have been added to help you store Excel data types.
E00102 | NEW - Cache class | A new cache class, CXlOperCache, has been added to speed up the performance of frequently called add-ins, by cacheing the results in a map.
E00103 | NEW - Cache sample | A new sample, AvgOpt, has been added, to demonstrate the use of the CXlOperCache class.
E00104 | NEW - Function Wizard cache flag | A new attribute, "cacheresults", has been added to the Function model, to automatically add cacheing to an add-in function. The attribute is available as a menu item on the Function menu in the XLL+ Function Wizard.
E00105 | NEW - AppWizard cache option | The AppWizard now offers an option to add a cache of type CXlOperCache to a new project's application class.
E00106 | NEW - AppWizard overrides option | The AppWizard now offers an option to add default implementations of OnXllOpenEx() and OnXllClose().
E00107 | NEW - SimpOpt sample | The SimpOpt sample has been improved, and now uses the CXlOper::CallAddin method to invoke one add-in function from another. The sample documentation has been expanded.
E00108 | NEW - FAQ | The Frequently Asked Questions have been copied from the web-site to the on-line help.
E00109 | NEW - Functions to get and set Calculation mode | Two new functions, CXllApp::GetCalculationMode() and CXllApp::SetCalculationMode() have been added.
E00110 | NEW - Integration sample | A new advanced sample, Integration, had been added, which uses dialogs and macro functions to integrate functions in a workbook.
E00111 | NEW - Functions to detect user cancel | Two new functions, CXllApp::GetUserAbort() and CXllApp::CancelUserAbort() have been added, to detect the user pressing the Cancel key.
E00112 | NEW - Structured Exception Handling | A new class SE_Handler is used in the SEH sample code, to simplify the use of C Structured Exception Handling techniques.

4.2.3

Date: | 11-Jan-2003
Description: | Initial commercial release
Files: | xlpu_4_2_3_e.exe xlpn_4_2_3_e.exe xlps_4_2_3_e.exe xlp_demo_4_2_3_e.exe
Item | Change | Description
E00083 | NEW - New members for mtx_ptrs<T> | New members, including a casting operator, have been added to the template class mtx_ptrs, to simplify access to array values.
E00084 | NEW - New extended attribute for Formula Wizard | A new extended attribute is now supported by functions and can be controlled using the Extended Attributes dialog. The attribute, 'nopreview', determines whether the function will be unavailable if called from the Excel Formula Wizard.
F00058 | FIX - COper::ReadVectorItem bug | A bug in COper::ReadVectorItem caused Excel to crash when handling the error message for a missing argument. This has been fixed.
E00085 | NEW - COper::ReadGroupItem replaces COper::ReadVectorItem | COper::ReadGroupItem is now used in place of COper::ReadVectorItem in functions generated by the Function Wizard.
E00086 | NEW - Visual Studio .NET Help integration | Visual Studio .NET Help integration has been completed. All topics are now in the style and structure of Visual Studio.
E00087 | NEW - New methods for CXlMenu | CXlMenu now contains new methods for menu manipulation: DeleteItem(), EnableItem(), CheckItem() and ReplaceItem(). CXlMenu can also be used to create sub-menus, by calling the new forms of Create().
E00088 | NEW - Advanced menu sample | A new sample, SubMenus, has been added, to demonstrate how to add sub-menus and dynamic menus.
E00089 | NEW - COM event handler interface | A new simplified COM event handler interface, CXllApp::SetComEventHandler() has been added.
E00090 | NEW - COM event handler documentation | The COM event handler interfaces have all been documented.
E00091 | NEW - COM event handler samples | A new sample, ComEvents, has been added, to demonstrate how to add a handlers for COM events such as WorkbookOpen and Calculate.
F00059 | FIX - Grouped arguments | Grouped arguments that were marked as optional were failing to remember their state in the Formula Wizard. This behaviour has been fixed.
F00060 | FIX - Empty arrays | CXlOper::AllocArray() asserted when an array of zero rows, columns or items was created. This behaviour has been fixed to be tolerant of empty arrays.
F00061 | FIX - Crash in Export window | The Function Wizard crashed when a non-existent directory was selected for an exported XML file. This behaviour has been fixed.
E00092 | NEW - Walkthroughs for array results | Two new walkthroughs have been added to demonstrate how to return array results from add-in functions.
E00093 | NEW - Walkthroughs for grouped arguments | A new walkthrough has been added to demonstrate how to create grouped arguments with the Function Wizard.

4.2.2

Date: | 01-Dec-2002
Description: | Maintenance beta release
Files: | xlp_4_2_2_e.exe xlp_demo_4_2_2_e.exe
Item | Change | Description
E00080 | NEW - Help Generator Tool | A new Help Generator tool has been added. This tool generates a complete Help project based on the add-in functions found in source files, along with the code needed to connect it to the add-in.
F00056 | FIX - CXlOper::ReadMatrix failed to link | Some CXlOper methods were excluded from the run-time libraries; as a result CXlOper::ReadMatrix() caused a link error. This has been fixed.
E00081 | NEW - SDK Function numbers | New technical notes and a walkthrough have been added to the documentation to help with the CXlOper::Excel() and CXllApp::Excel() methods.
F00057 | FIX - COper::ToMatrix failed to compile | CXlOper::ToMatrix() failed to compile. This has been fixed.
E00082 | NEW - MFC Resources in .NET | The resources file in the MFC builds under VisualStudio .NET was not compatible with the resource editor. This has been fixed.

4.2.1

Date: | 18-Nov-2002
Description: | Maintenance beta release
Files: | xlp_4_2_1.exe xlp_demo_4_2_1.exe
Item | Change | Description
F00050 | FIX - Bug in MtCalc | The MtCalc sample add-in caused Excel to crash if the application was closed with calculations still running. This behaviour has been fixed.
E00074 | NEW - .NET AppWizard automatically opens C++ source file | The .NET AppWizard now automatically opens the main cpp file after creating an XLL+ project.
F00051 | FIX - CXllApp::GetVersionInfo() failed under MFC | Calls to CXllApp::GetVersionInfo() failed under MFC under certain conditions. This behaviour has been fixed.
F00052 | FIX - Various bad links in User Guide |
F00053 | FIX - Erroneous function descriptions in Reference | Errors in the ple::imtx<T> documentation were fixed.
F00054 | FIX - CXlDialog class failed to compile with MFC | Errors in the CXlDialog class prevented compilation under MFC under some conditions. This behaviour has been fixed.
E00075 | NEW - Walkthroughs | A new section "Walkthroughs" containing task-oriented walkthroughs has been added to the XLL+ help.
E00076 | NEW - Installable matrix classes | The developer can now install their own matrix classes in place of those supplied with XLL+, by creating a matrix adapter class, and overriding the macros MTX_FLAT and MTX_PTRS.
E00077 | NEW - Extended attributes dialog | A new dialog, listing extended function attributes,is available from the Edit menu of the XLL+ Function Wizard.
E00078 | NEW - Application-level data flag | A new function flag, "appscope" is available. The flag, if true, causes "XLL_FIX_STATE;" to be generated at the start of the add-in function. It can be set via the Extended Attributes dialog.
F00055 | FIX - Function Wizard Context Help under .NET | Function Wizard Context Help failed under .NET. This behaviour has been fixed.
E00079 | NEW - Registry settings documentation | A list of all registry settings used by the various XLL+ components is now included as a technical note in the reference guide.

4.2.0

Date: | 20-Sep-2002
Description: | Initial beta release
Files: | xlp_4_2_0.exe xlp_demo_4_2_0.exe
Item | Change | Description
E00055 | NEW - New string methods for CXllApp | A new set of static methods, RetString(), have been added to CXllApp, to return string results to Excel.
E00056 | NEW - New stack check method for CXllApp | A new static method, XlGetStackSpace(), has been added to CXllApp, to return the number of bytes available in the stack.
E00057 | NEW - New error conversion method for CXllApp | A new static method, ErrorToString(), has been added to CXllApp, to convert an error code to a string.
E00058 | NEW - New bool() casting operator for COper | A new casting operator, bool(), has been added to COper, to extract and return a C++ boolean value.
E00059 | NEW - New optional argument reading functions for COper | A new templated optional argument reader, ReadOptional(), has been added to COper, to extract and return any simple scalar value from an optional argument. This function is preferred to the older ReadOpt().
E00060 | NEW - Enhancements to COper::ReadVector(), COper::ReadVectorBounded() and COper::ReadMatrix() | The array argument reading functions, ReadVector(), ReadVectorBounded() & ReadMatrix(), have been replaced by templated functions, which can handle any basic C++ type. The functions are no longer limited to double, long and CString output types.
E00061 | NEW - New COper functions ReadRow() and ReadColumn() | New helper functions have been added to allow a vector to be read only as a row or a column.
E00062 | NEW - New STL collection support | New template methods, ReadArrayIntoOrderedCollection1D() and ReadArrayIntoSet1D(), have been added to COper to allow an array to be read into any STL collection class.
E00063 | NEW - New matrix classes | A new set of matrix support interfaces and classes have been added, to support faster and more flexible storage and conversion of two-dimensional arrays, and integration with users' existing matrix classes and libraries.
E00064 | NEW - New CXlOper constructors | New constructors have been added for CXlOper, to support conversion from the C++ bool type and the STL std::string type.
E00065 | NEW - New bool() casting operator for CXlOper | A new casting operator, bool(), has been added to CXlOper, to extract and return a C++ boolean value.
E00066 | NEW - New matrix output functions | A new templated conversion function, CXlOper::FromMatrix(), and a new templated constructor have been added to CXlOper, to support output of matrices of any basic C/C++ type.
E00067 | NEW - Excel function names may contain periods | The Function Wizard now allows Excel function names to include periods e.g. "GET.SYSTEMTIME".
F00043 | FIX - Fixed memory leak under Windows XP | A memory leak (under Windows XP only) in the STL libraries' implementation of CString::AllocSysString() was fixed.
F00044 | FIX - CXllCOM::Init() fails with Excel 2000/2002 | On some machines running Excel 2000 or 2002, CXllCom::Init() failed with the following error: "CLSIDFromProgID("Excel.Application.8", ...) failed with error 800401f3". This bug applied only to machines on which Excel 97 had never been installed. This behavior has been fixed and the function will now succeed, as long as any of Excel 97, 2000 or 2002 has been correctly installed.
F00045 | FIX - Argument descriptions can now start with a digit | If an argument description (other than the first) began with a digit, then it was possible for the description to be hidden, and possibly also all subsequent arguments' descriptions. This behavior has been fixed.
E00068 | NEW - New methods for cell formulae | New methods CXlOper::GetFormula() and CXlOper::SetFormula() let you inspect and change formulae in spreadheet cells.
E00069 | NEW - Visual Studio .NET integration | XLL+ 4.2 works within Microsoft Visual Studio .NET, with fully integrated wizards and help. (Visual Studio 6 and Visual C++ 6 continue to be supported.)
E00070 | NEW - New dialog classes | New classes CXlDialog and CXlControl have been added, to support the use of native Excel dialogs.
E00071 | NEW - New menu class | A new class CXlMenu has been added, to support the addition of menus to Excel's application menu.
F00046 | FIX - GetVersionInfo bug fixed | The bug in CXllApp::GetVersionInfo() which caused MFC dialogs to fail to appear after its use has been fixed. (See XLL+ FAQ #5.)
F00047 | FIX - Functions now disappear from Excel Formula Wizard when unregistered | Prior to this version, functions in XLLs that were unregistered (via the Tools - Addins dialog) remained in the Formula Wizard, stripped of help text. This behaviour has been fixed.
E00072 | NEW - Optional arguments in Function Wizard | Arguments can now be marked as Optional in the XLL+ Function Wizard, and default values can be provided for missing arguments.
E00073 | NEW - Automatic internationalisation of standard categories | Functions that use standard categories are registered in the current Excel language.

4.1.7

Date: | 19-Apr-2002
Description: | Enhancement release
Files: | xlp_4_1_7.exe xlp_demo_4_1_7.exe
Item | Change | Description
F00042 | FIX - Empty example links | Empty example links were replaced in Reference Guide.
E00042 | NEW - XllPush library added | The XLLPUSH library, supporting asynchronous functions, was added. New files: XllPush.lib, XlpPush.h, XllPushApp.h, XlpMtMsg.h, XlpAsync.dll.
E00043 | NEW - Asynchronous demos added | Three new sample libraries were added, to demonstrate various uses of the XllPush library: MtBackground, MtCalc and MtFeed.
E00044 | NEW - AppWizard: XllPlus.h included in project | The file XllPlus.h is now automatically added to the list of files in a new project. This makes the XLL+ header files known to the DevStudio parser, and thereby switches on IntelliSense for XLL+ classes and functions.
E00045 | NEW - New reference methods for CXlOper | New methods for references have been added to CXlOper: SetValue(), MakeRef(), GetActiveCell() and SetActiveCell().
E00046 | NEW - New reference methods for CXllApp | New methods for references have been added to CXllApp: MakeSheetName(), SplitSheetName(), GetSheetId() and GetSheetName().
E00047 | NEW - New errror handling method for CXllApp | A new method for has been added to CXllApp, SetErrorHandling(), which switches on and off XL4 macro error handling.
E00048 | NEW - New class CXllFinder | A new class has been added, to support find and replace operations.
E00049 | NEW - New sample application FindReplace | A new sample application, FindReplace, shows how to use the CXllFinder class.
E00050 | NEW - New chapter in user guide: Macro functions | A new chapter on Macro functions has been added to the User Guide.
E00051 | NEW - New tech note: Bounded input arrays | A new technical note has been added, which discusses the use of upper bounds in ReadVector() and ReadMatrix().
E00052 | NEW - New chapter in user guide: Writing safe functions | A new chapter on exception handling has been added to the User Guide.
E00053 | NEW - New sample application SafeCode | A new sample application, SafeCode, shows how to protect your code with Structured Exception Handling.
E00054 | NEW - Sample applications added to documentation | A new section in the online documentation describes each of the sample applications.

4.1.6

Date: | 14-Mar-2002
Description: | Maintenance release
Files: | xlp_4_1_6.exe xlp_demo_4_1_6.exe
Item | Change | Description
F00038 | FIX - Setup program failed without Administrator priviliges | The InstallShield setup program failed and aborted when run by a user without Administrator rights on the installation machine. This condition is now detected by the setup program and a useful error message is issued.
F00039 | FIX - DinkumWare libraries supported | The COM methods of CXllApp failed under some conditions when the STL XLL+ run-time libraries were used with the DinkumWare STL headers. This was due to a conflict between the DinkumWare map classes and those in the Microsoft release. This has been fixed, and all versions of the XLL+ run-time libraries can be used with both the DinkumWare and the Microsoft STL headers.
F00040 | FIX - MFC build uses CXllApp::POSITION | As a side-effect of F00039 (support for DimkumWare libraries), the signatures of CXllApp::GetStartFnPosition() and CXllApp::GetNextFnAssoc() in the MFC run-time libraries have been altered. These now use CXllApp::POSITION instead of POSITION for iteration. Any MFC code that uses these functions should be changed, with instances of POSITION replaced by CXllApp::POSITION.
F00041 | FIX - XLLPLUS.H no longer #includes <map> | As a side-effect of F00039 (support for DimkumWare libraries), the STL <map> header file is no longer #included by XLLPLUS.H. Any applications that use map classes without explictly #including <map> now need to do so. This applies to the demo project Tutorial1.
E00041 | NEW - ::XllGetVersion() no longer inline | The global function XllGetVersion() is now implemented in the run-time libraries, rather than inline. You can compare XllGetVersion() (implemented in the run-time library) and XLLPLUS_VERSION (implemented in XLLPLUS.H) to ensure that headers and libraries are in sync.

4.1.5

Date: | 03-Mar-2002
Description: | Commercial release
Files: | xllplus41-02030301.zip
Item | Change | Description
E00039 | NEW - AppWizard renamed | The AppWizard binary file has been renamed to XLLPLUS4.AWX, so as to remove any conflicts with earlier versions of XLL+. Version 4.1 can now be run in parallel with earlier versions.
E00040 | NEW - New CXllCom methods added | 3 new methods were added to CXllCom: OleGetWorksheetName(), OleGetRangeWorksheet() and OleGetWorksheetWorkbook().

4.1.4

Date: | 06-Feb-2002
Description: | Maintenance release
Files: | xllplus41-02022601.zip
Item | Change | Description
F00029 | FIX - CXlRef::Width() | CXlRef::Width() returned a BYTE and therefore failed when a range contained 256 columns. It now returns a WORD.
F00030 | FIX - CXlArray::GetWidth() + CXlArray::GetHeight() | These methods returned WORD. They now return USHORT, in line with COper and CXlOper.
E00035 | NEW - New method CXlArray::GetDims() | This method was added to bring CXlArray in line with COper and CXlOper.
E00036 | NEW - Technical Notes | A new topic, "Comparison of COper, CXlOper and CXlArray" has been added to the Technical Notes.
E00037 | NEW - AppWizard | The AppWizard now opens the project's main C++ source file after it has finished creating the project.
F00031 | FIX - Function Wizard changes selection after saving | If a function was saved using the save button, the wizard would change its selection to the function selected when the wizard first opened. This behavior has been fixed.
F00032 | FIX - Function Wizard does not display saved changes | If a function was saved by the save button, or before changing the selected function, the wizard would not display the updates but would instead display the version originally loaded. This behavior has been fixed.
F00033 | FIX - Various typos in Reference Guide and Function Wizard help |
F00034 | FIX - Function Wizard displays error when adding column group | If a new function was created, and the first argument to be added to it was a group, the Wizard displayed an error message. This behavior has been fixed.
F00035 | FIX - Function Wizard pops up argument editor when changing argument type | If an argument's type was changed to a group in the Arguments grid of the Function Wizard, the argument editor popped up. This behavior has been removed.
F00036 | FIX - Generated functions did not include CXlArray instantiation | The Function Wizard did not generate code to instantiate a CXlArray object from a LPXLARRAY type input. This has been fixed.
F00037 | FIX - Arrays of strings were wrongly declared | The Function Wizard did not generate code to correctly instantiate an array of strings, creating a collection of pointers instead of a collection of strings. e.g. vector<const char*>, which should be vector<CString>. This has been fixed.
E00038 | NEW - New demo project ArgSize | A new demo project, ArgSize, has been added. This, along with the test spreadsheet ArgSize.xls, demonstrates argument size limits.

4.1.3

Date: | 22-Feb-2002
Description: | Maintenance release
Files: | xllplus41-02022201.zip
Item | Change | Description
F00025 | FIX - Various typos in User Guide |
E00033 | NEW - CXllApp::GetXllName() added | A new method, CXllApp::GetXllName(), returns the full path of the current XLL module.
F00026 | FIX - CXllCom::OleGetRangeAddress() | This function was returning local addresses only. This behavior has been fixed.
F00027 | FIX - CVariant::Compare() | This method was returning unpredictable results. This behavior has been fixed.
E00034 | NEW - CXllCom documentation | All the methods of the CXllCom class have now been documented.
F00028 | FIX - Incomplete uninstall | After uninstallation, some keys were left in the registry, which caused problems the next time MSDev was run. This behavior has been fixed.

4.1.2

Date: | 20-Feb-2002
Description: | Maintenance release
Files: | xllplus41-02022001.zip
Item | Change | Description
F00022 | FIX - Fixed some empty links in User Guide |
F00023 | FIX - Clicking on a tool button loses recent changes to text grid fields | Function Wizard: If a text field in the argument grid was changed, and then, while the cursor was in the text field, a toolbutton or menu choice was used, the changes to the text field were lost. This behavior has been fixed.
F00024 | FIX - Deleting //}}XLP_SRC caused inconsistent behavior | Function Wizard: If the //}}XLP_SRC delimiter was deleted, then the Function Wizard would load the function and allow user modifications, but these changes could not be saved. This behavior has been fixed.

4.1.1

Date: | 14-Feb-2002
Description: | Maintenance release
Files: | xllplus41-02021401.zip
Item | Change | Description
F00021 | FIX - Function Wizard fails to accept input in empty files | If the Function Wizard was opened using the Edit Function tool, and the file being edited contained no add-in functions, and a new function was added using the New Function button, user input was thereafter rejected for some fields of the wizard. This behavior has been fixed.
E00032 | NEW - New date functions added | New date functions were added to xlldate.h: XlNow(), XlToday(), XlWeekday(), XlStringToSerial() and XlStringToLSerial().

4.1.0

Date: | 06-Feb-2002
Description: | Initial release
Files: | xllplus41-02020601.zip


Registry Settings

The registry settings used by the various components of the XLL+ toolkit are listed below.

XLL+ 7 for Visual Studio 2005 - machine settings

HKEY_LOCAL_MACHINE\Software\Planatech\XllPlus\7.0\VS8.0

Name | Description | Default value
DefaultExcelExe | Full path to EXCEL.EXE. If there are multiple versions of Excel installed, This will contain the version of Excel which is used by default. |
InstallationGuid | Identifier of build number installed |
InstallDir | Full path to the installation directory for XLL+ version 7.0 for Visual Studio 2005 |
Sku | Product identifier |

HKEY_LOCAL_MACHINE\Software\Planatech\XllPlus\7.0\VS8.0\License

Name | Description | Default value
LicenseFile | Full path to license file (ignored if not fixed license) | [InstallDir]\License\xllplus.lic
LicenseServer | Machine name of license server |
LicenseType | Type of license: FLOATING, FIXED or DEMO |

HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\8.0\InstalledProducts\XllPlus7Package

Name | Description | Default value
Package | Package identifier |
PID | Package version number |

HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\8.0\Packages\{8cb93419-352f-4fd2-ae33-05aea2072b46}

Name | Description | Default value
(Default) | Package type name |
CodeBase | The main DLL of the XLL+ package |
ProductVersion | The product identifier (SKU) of the package |

XLL+ 7 for Visual Studio 2005 - user settings

HKEY_CURRENT_USER\Software\Planatech\XllPlus\7.0\VS8.0

Name | Description | Default value
InstallationGuid | Identifier of build number installed |

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\DialogPage\Planatech.XllPlus7.OptionsPageGeneral

Name | Description | Default value
(Various) | The values in this folder correspond to the values entered in the Options/XLL+/General window |

XLL+ 7 for Visual Studio 2008 - machine settings

HKEY_LOCAL_MACHINE\Software\Planatech\XllPlus\7.0\VS9.0

Name | Description | Default value
DefaultExcelExe | Full path to EXCEL.EXE. If there are multiple versions of Excel installed, This will contain the version of Excel which is used by default. |
InstallationGuid | Identifier of build number installed |
InstallDir | Full path to the installation directory for XLL+ version 7.0 for Visual Studio 2008 |
Sku | Product identifier |

HKEY_LOCAL_MACHINE\Software\Planatech\XllPlus\7.0\VS9.0\License

Name | Description | Default value
LicenseFile | Full path to license file (ignored if not fixed license) | [InstallDir]\License\xllplus.lic
LicenseServer | Machine name of license server |
LicenseType | Type of license: FLOATING, FIXED or DEMO |

HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\9.0\InstalledProducts\XllPlus7Package

Name | Description | Default value
Package | Package identifier |
PID | Package version number |

HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\9.0\Packages\{9e9c58fd-458c-46f3-8e80-6670d6f21e1d}

Name | Description | Default value
(Default) | Package type name |
CodeBase | The main DLL of the XLL+ package |
ProductVersion | The product identifier (SKU) of the package |

XLL+ 7 for Visual Studio 2008 - user settings

HKEY_CURRENT_USER\Software\Planatech\XllPlus\7.0\VS10.0

Name | Description | Default value
InstallationGuid | Identifier of build number installed |

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\DialogPage\Planatech.XllPlus7.OptionsPageGeneral

Name | Description | Default value
(Various) | The values in this folder correspond to the values entered in the Options/XLL+/General window |

XLL+ 7 for Visual Studio 2010 - machine settings

HKEY_LOCAL_MACHINE\Software\Planatech\XllPlus\7.0\VS10.0

Name | Description | Default value
DefaultExcelExe | Full path to EXCEL.EXE. If there are multiple versions of Excel installed, This will contain the version of Excel which is used by default. |
InstallationGuid | Identifier of build number installed |
InstallDir | Full path to the installation directory for XLL+ version 7.0 for Visual Studio 2010 |
Sku | Product identifier |

HKEY_LOCAL_MACHINE\Software\Planatech\XllPlus\7.0\VS10.0\License

Name | Description | Default value
LicenseFile | Full path to license file (ignored if not fixed license) | [InstallDir]\License\xllplus.lic
LicenseServer | Machine name of license server |
LicenseType | Type of license: FLOATING, FIXED or DEMO |

HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\10.0\InstalledProducts\XllPlus7Package

Name | Description | Default value
Package | Package identifier |
PID | Package version number |

HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\10.0\Packages\{7104ac6a-abb0-4e3b-9346-9d0fb0733d9c}

Name | Description | Default value
(Default) | Package type name |
CodeBase | The main DLL of the XLL+ package |
ProductVersion | The product identifier (SKU) of the package |

XLL+ 7 for Visual Studio 2010 - user settings

HKEY_CURRENT_USER\Software\Planatech\XllPlus\7.0\VS9.0

Name | Description | Default value
InstallationGuid | Identifier of build number installed |

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\DialogPage\Planatech.XllPlus7.OptionsPageGeneral

Name | Description | Default value
(Various) | The values in this folder correspond to the values entered in the Options/XLL+/General window |

See Also

Trouble-shooting


Conversion functions

Input conversion and validation functions

The conversion functions are listed below. All conversion that takes place in code that is generated by the XLL+ Function Wizard is done using these functions.

Function | Description
XlReadScalar | Read a scalar (single-cell) argument whose type is standard.
XlReadScalarEx | Read a scalar (single-cell) argument of extended type. Convert the value from an Excel form to that specified for the extended type.
XlReadVector | Read an array argument into a vector of values whose type is standard.
XlReadVectorEx | Read an array argument into a vector of values whose type is extended. Convert each cell's value from an Excel form to that specified for the extended type.
XlReadMatrix | Read an array argument into a matrix of values whose type is standard.
XlReadMatrixEx | Read an array argument into a matrix of values whose type is extended. Convert each cell's value from an Excel form to that specified for the extended type.
XlReadGroupedScalar | Read a scalar (single-cell) argument whose type is standard from a scalar group.
XlReadGroupedScalarEx | Read a scalar (single-cell) argument whose type is extended from a scalar group. Convert the value from an Excel form to that specified for the extended type.
XlReadGroupedVector | Read one column or row of a matrix argument into a vector of values whose type is standard from a vector group.
XlReadGroupedVectorEx | Read one column or row of a matrix argument into a vector of values whose type is extended from a vector group. Convert each cell's value from an Excel form to that specified for the extended type.

Flags

The input conversion and validation functions support a wide range of special behaviors, most of which are controlled by the flags parameter. The bits of the flags parameter are summarized below.

Topic | Flag | Description | Notes
Default | XLA_DEFAULT_EMPTY | Use a default value if the argument is missing or empty. | Ignored if vector or matrix. Ignored if group.
 | XLA_DEFAULT_BLANK | Use a default value if the argument is a blank string.
 | XLA_DEFAULT_ZERO | Use a default value if the argument's value is zero.
 | XLA_DEFAULT_NONNUMERIC | Use a default value if the argument is not numeric.
Truncation | XLA_TRUNC_ONEMPTY | Truncate an array if a cell is empty. | Ignored if scalar. Ignored if XLA_FILL_ALL is used. See Truncation for more details.
 | XLA_TRUNC_ONBLANK | Truncate an array if a cell contains a blank string.
 | XLA_TRUNC_ONZERO | Truncate an array if a cell contains a zero value.
 | XLA_TRUNC_ONNONNUMERIC | Truncate an array if a cell's contents are not numeric.
Cell default | XLA_FILL_USED_AREA | Truncate an array after the last non-empty cell. Empty cells within the used area are filled with the default cell value. | Ignored if scalar. See Fill for details of the interaction between fill flags and truncation flags.
 | XLA_FILL_ALL | Empty cells within the array are filled with the default cell value.
Fill values | XLA_CELL_DEFAULT_EMPTY | If an array is to be filled, fill cells that are empty. | Ignored if scalar. Ignored unless either XLA_FILL_USED_AREA or XLA_FILL_ALL is used.
 | XLA_CELL_DEFAULT_BLANK | If an array is to be filled, fill cells that contain blank strings.
 | XLA_CELL_DEFAULT_ZERO | If an array is to be filled, fill cells that contain the value zero.
 | XLA_CELL_DEFAULT_NONNUMERIC | If an array is to be filled, fill cells that contain non-numeric values.
Array | XLA_FLAG_REJECT_NULL_ARRAY | The array argument may not be entirely empty. | Ignored if scalar.
Vector | XLA_FLAG_VECTOR_COLUMN | A vector argument must be vertical, i.e. a column. | Ignored if scalar or matrix.
 | XLA_FLAG_VECTOR_ROW | A vector argument must be horizontal, i.e. a row.
Matrix | XLA_FLAG_TRANSPOSE | The contents of a matrix argument will be transposed before storage; array[i][j] will be swapped with array[j][i]. | Ignored if scalar or vector.
 | XLA_MATRIX_LAYOUT_ROWS | The contents of a matrix argument will be stored with rows as the innermost dimension; an item will be found in the output matrix as matrix[column][row]. Without this flag, matrix values will always be stored with columns as the innermost dimension, and items are found at matrix[row][column].
 | XLA_MATRIX_DATA_VALUES | The contents of a matrix argument will be stored in one continuous array. Without this flag, matrix values will always be stored in an array of pointers, each of which points to an equal-sized array.
Bounds | XLA_BOUND_UBOUND_INNER | A array whose size is constrained will treat the constraint as the index of the upper bound, i.e. size - 1. | Ignored if scalar, or if bounds are not constrained.
 | XLA_BOUND_UBOUND_AUTO | A array whose size is constrained will treat the constraint as the index of the upper bound, i.e. size - 1, if the lower bound of the dimension is not zero. If the lower bound is zero (or is not specified) then the constraint will be treated as the size of the array (in the given dimension).
Grouping | XLA_OPER_IS_GROUP | The argument is a member of a group. | Ignored if matrix.

Standard types

The standard built-in types are listed below.

Name | C++ type
Boolean | bool
Double | double
Integer | int
Short integer | short
Unsigned short integer | unsigned short
String | CXlStringArg

Extended types

Extended types are defined in extension files, and registered using the Manage extensions command.

See Extended types in the User Guide for more information.

Groups

Groups are a way of representing multiple inner arguments as a single Excel argument. This is useful when there are too many arguments for Excel to handle, and for helping with layouts of complicated arguments.

See Grouping arguments in the User Guide for more information.

Truncation

The truncation flags and the fill flags control how the conversion functions treat the sizes of arrays. Let us say we have an argument x, which is defined as a vector of numbers (std::vector<double>). The user passes cell range A1:A3 as x. A1 and A2 contain numbers, but A3 is empty. If none of the truncation flags are set, then the conversion function will fail, with an error message like: "Expected a number for x[3]". However, if the XLA_TRUNC_ONEMPTY flag is set, then the conversion function will discard cell A3, and set x to contain just two numbers (A1 and A2).

Truncation of arrays is very convenient for the user of an add-in function. When assigning an array argument to a function, the user can specify an area that is large enough to contain the array, and also contains some spare, empty cells. If the array changes size, the formula does not need to be changed, because the conversion function automatically truncates the array, discarding the empty cell range.

By default, new vector arguments have the standard truncation flags set: XLA_TRUNC_ONEMPTY and XLA_TRUNC_ONBLANK. XLA_TRUNC_ONBLANK is useful because it allows the use of formulae within the array such as =IF(C2<>0,D2/C2,""). A blank cell is treated as an empty cell, and the user thereby has full control over the size of their array argument.

Fill

The two fill flags, XLA_FILL_ALL and XLA_FILL_USED_AREA, work in conjunction with the truncation and cell default flags to allow special behavior when a conversion function reads an array that is not full populated (i.e. sparse).

If XLA_FILL_ALL is set, then the function will treat every empty cell within the array as if it contained the default cell value passed to the conversion function. This behavior is useful for sparsely populated arrays. Thus if we have a numeric vector argument x and a default cell value of -999.0, and the user passes a range {100.0, empty, 50.0, empty}, the conversion function will return the vector {100.0, -999.0, 50.0, -999.0}.

The cell default flags control which cells are considered to be empty. Normally, the flags XLA_CELL_DEFAULT_EMPTY and XLA_CELL_DEFAULT_BLANK are used in conjunction with a fill flag.

While the XLA_FILL_ALL flag is useful for reading sparse arrays that are of fixed size, the XLA_FILL_USED_AREA can be used to read sparse arrays of variable size. The logic used by the conversion function is a little more complicated. First, the function searches from the end of the range for the last populated cell. (The truncate flag values are used to control which cells are considered to be populated or not populated.) All cells after the last populated cell are discarded; the remaining cells are considered to be the "used area". Next, any empty cells within the used area are replaced with the default cell value.

Say a numeric vector argument is marked with the following flags: XLA_FILL_USED_AREA | XLA_CELL_DEFAULT_EMPTY | XLA_TRUNC_ONEMPTY, and has a default cell value of -999.0. The user passes the following array: {5.0, empty, 6.1, 1.2, empty, empty, empty}. The last 3 cells will be discarded, and then the second cell will be treated as filled, giving a result of {5.0, -999.0, 6.1, 1.2}.

Exceptions

The table below lists the exceptions that may be thrown by the conversion functions.

Type | Description
CXlConversionException | General conversion error.
CXlUninitializedOperException | The argument has not been properly initialized. This cannot occur in code that was generated by the wizard, but it can occur if the conversion functions are used on local CXlOper variables that were instantiated by the developer. CXlUninitializedOperException inherits from CXlConversionException.


Project Settings

This topic describes the standard project settings created by the XLL+ AppWizard, and provides instructions for changing them.

Settings

Projects created by the XLL+ AppWizard have the following significant settings.

Section | Setting | Description
C/C++ | Additional Include Directories | The list of directories specified in the XLL+ IncludePath setting. By default, this contains the location of the XLL+ header files.
 | Debug Information Format | This is set to Program Database (/Zi). It is essential that it not be set to Program Database for Edit & Continue (/ZI); /ZI will often cause XLL add-ins to fail to load.
 | Optimization | For Debug configurations, optimization is disabled (/Od). For Release configurations, optimization is set to Maximum Speed (/O2). This setting may be changed by the developer to suit the requirements of a particular project.
 | Preprocessor Definitions | WIN32 is set for all projects (required). _DEBUG is set for debug configurations (required). NDEBUG is set for release configurations (required). XLL_LIB_MFC is set for MFC projects only. It must not be changed. XLL_LIB_STL is set for STL projects only. It must not be changed. WINVER=0x0400 supports the platform libraries provided with Visual Studio .NET. If later versions of the Microsoft Platform libraries are available, and lower versions of Windows do not need to be supported, it may be set to a higher version. UNICODE and _UNICODE are set for Unicode builds only. _MBCS is set for non-Unicode builds.
 | Enable C++ Exceptions | This setting should support both C++ and C runtime exceptions. In VS 2005 and above, it is set to Yes With SEH Exceptions (/EHa); in VS .NET 2003, it is set to No, and /EHa is added explicitly to the Additional Options in the Command Line.
 | Runtime library | For MFC builds, this is Multi-threaded DLL (/MD) or Multi-threaded Debug DLL (/MDd). For STL builds, this is Multi-threaded (/MT) or Multi-threaded Debug (/MTd); it may be changed (see below).
 | Enable Run-time Type Info | Yes. This setting is required.
 | Treat wchar_t as Built-in Type | Yes.
Linker | Output File | $(OutDir)/[ProjectName].xll. Note that $(OutDir) may be a sub-directory of the project directory or a sibling, depending on whther you chose to create a directory for the solution when you invoked the AppWizard.
 | Additional Library Directories | The list of directories specified in the XLL+ LibPath setting. By default, this contains the location of the XLL+ runtime library files.
Resources | Additional Include Directories | The list of directories specified in the XLL+ IncludePath setting. By default, this contains the location of the XLL+ header files, including the resource files which contain the XLL+ runtime messages.

C/C++ Runtime Library

For STL builds the C/C++ Runtime Library setting may be changed to use the runtime library in a DLL (/MD or /MDd). Changing the setting will automatically cause a different XLL+ runtime library to be used (see Runtime Libraries).

See Also

XLL+ Application Wizard - Application Settings | Runtime libraries


Runtime dependencies

XLL projects created by the XLL+ AppWizard have dependencies on other DLLs as listed below. Each of these DLLs must be present on a user's machine in order for the XLL to load successfully.

If a required DLL is not found when an XLL is opened, the user will get an error message such as "This file is not in a recognizable format".

A list of all DLLs required by a XLL can be displayed using the dependency walker tool (www.dependencywalker.com).

XLCALL32.DLL

XLCALL32.DLL is installed as part of Excel. It it is usually located in the same directory as the executable file EXCEL.EXE. You should not install this file yourself.

Visual Studio .NET 2010

Build | Configuration | Required DLLs
All builds and configurations |  | XLCALL32.DLL
MFC (/MTd) | Debug1 | None
MFC (/MT) | Release | None
MFC (/MDd) | Debug1 | MFC100D.DLL
 |  | MSVCP100D.DLL
 |  | MSVCR100D.DLL
MFC (/MD) | Release | MFC100.DLL
 |  | MSVCP100.DLL
 |  | MSVCR100.DLL
STL (/MTd) | Debug | None
STL (/MT) | Release | None
STL (/MDd) | Debug1 | MSVCP100D.DLL
 |  | MSVCR100D.DLL
STL (/MD) | Release | MSVCP100.DLL
 |  | MSVCR100.DLL
CLR2 | Debug1 | MSVCP100D.DLL
 |  | MSVCR100D.DLL
 |  | MSCOREE.DLL
 |  | .NET Runtime 2.0, 3.0, 3.5 or 4.0
CLR2 | Release | MSVCP100.DLL
 |  | MSVCR100.DLL
 |  | MSCOREE.DLL
 |  | .NET Runtime 2.0, 3.0, 3.5 or 4.0

Visual Studio .NET 2008

Build | Configuration | Required DLLs
All builds and configurations |  | XLCALL32.DLL
MFC (/MTd) | Debug1 | None
MFC (/MT) | Release | None
MFC (/MDd) | Debug1 | MFC90D.DLL
 |  | MSVCP90D.DLL
 |  | MSVCR90D.DLL
MFC (/MD) | Release | MFC90.DLL
 |  | MSVCP90.DLL
 |  | MSVCR90.DLL
STL (/MTd) | Debug | None
STL (/MT) | Release | None
STL (/MDd) | Debug1 | MSVCP90D.DLL
 |  | MSVCR90D.DLL
STL (/MD) | Release | MSVCP90.DLL
 |  | MSVCR90.DLL
CLR2 | Debug1 | MSVCP90D.DLL
 |  | MSVCR90D.DLL
 |  | MSVCM90D.DLL
 |  | MSCOREE.DLL
 |  | .NET Runtime 2.0, 3.0 or 3.5
CLR2 | Release | MSVCP90.DLL
 |  | MSVCR90.DLL
 |  | MSVCM90.DLL
 |  | MSCOREE.DLL
 |  | .NET Runtime 2.0, 3.0 or 3.5

Visual Studio .NET 2005

Build | Configuration | Required DLLs
All builds and configurations |  | XLCALL32.DLL
MFC (/MTd) | Debug1 | None
MFC (/MT) | Release | None
MFC (/MDd) | Debug1 | MFC80D.DLL
 |  | MSVCP80D.DLL
 |  | MSVCR80D.DLL
MFC (/MD) | Release | MFC80.DLL
 |  | MSVCP80.DLL
 |  | MSVCR80.DLL
STL (/MTd) | Debug | None
STL (/MT) | Release | None
STL (/MDd) | Debug1 | MSVCP80D.DLL
 |  | MSVCR80D.DLL
STL (/MD) | Release | MSVCP80.DLL
 |  | MSVCR80.DLL
CLR2 | Debug1 | MSVCP80D.DLL
 |  | MSVCR80D.DLL
 |  | MSVCM80D.DLL
 |  | MSCOREE.DLL
 |  | .NET Runtime 2.0
CLR2 | Release | MSVCP80.DLL
 |  | MSVCR80.DLL
 |  | MSVCM80.DLL
 |  | MSCOREE.DLL
 |  | .NET Runtime 2.0

For XLLs built using MFC and Visual Studio 2005, see also Visual C++ Deployment Examples (Microsoft).

Visual Studio .NET 2003

Build | Configuration | Required DLLs
All builds and configurations |  | XLCALL32.DLL
MFC (/MTd) | Debug1 | None
MFC (/MT) | Release | None
MFC (/MDd) | Debug1 | MFC71D.DLL
 |  | MSVCP71D.DLL
 |  | MSVCR71D.DLL
MFC (/MD) | Release | MFC71.DLL
 |  | MSVCP71.DLL
 |  | MSVCR71.DLL
STL (/MTd) | Debug | None
STL (/MT) | Release | None
STL (/MDd) | Debug1 | MSVCP71D.DLL
 |  | MSVCR71D.DLL
STL (/MD) | Release | MSVCP71.DLL
 |  | MSVCR71.DLL

Notes

1 Licensing restrictions apply when deploying the Debug builds of Microsoft's run-time DLLs. Please consult Microsoft's web-site for details.

2 See also technical note .NET requirements.

See Also

Runtime libraries


.NET requirements

Developer requirements for add-ins that use .NET

.NET runtime version
You must ensure that the your computer loads the correct version of the .NET run-time. See below.
Primary Interop Assemblies
If your add-in uses the Excel object model, then you must ensure that your machine has the Office Primary Interop Assemblies available. See below.
VS 2005 SP1
If you are using Visual Studio 2005, you must install Service Pack 1.

Run-time requirements for add-ins that use .NET

.NET runtime version
You must ensure that the user's machine loads the correct version of the .NET run-time. See below.
Primary Interop Assemblies
If your add-in uses the Excel object model, then you must ensure that the user's machine has the Office Primary Interop Assemblies available. See below.
C Runtime libraries
Ensure that the target machine has the required runtime DLLs. See Runtime Dependencies for details.

Loading the correct .NET runtime version

By default, Excel will load version 1.1.4322 of the .NET runtime. This will have the effect of making an XLL fail to load, with a message such as "This file is not in a recognizable format".

You can fix the problem in several ways.

  1. Install the Microsoft update for Office 2003 (KB907417). Refer to http://support.microsoft.com/default.aspx/kb/907417.

  2. Create a config file named excel.exe.config and place it in the same directory as EXCEL.EXE. The file should contain a <supportedRuntime> element, as in the following example:

    <configuration>
  <startup>
    <supportedRuntime version="v2.0.50727" />
  </startup>
</configuration>

  3. Locate the following key in the registry, and delete or rename it.

    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\policy\AppPatch\v2.0.50727.00000\excel.exe

    Note: extreme care should be taken when editing the registry directly. Refer to support staff as necessary.

Please note that there is normally no need to follow these procedures if Visual Studio 2008 has been installed on a machine, since the installer usually resolves these issues.

With a 64-bit version of Excel, you may find that only the config file technique works.

Office Primary Interop Assemblies

Both developers and users need to have the Office Primary Interop assemblies available on their computers. By default Visual Studio 2008 installs the PIAs for Excel 2003 and Excel 2007. If it is not already installed, you can download the PIAs from Microsoft's web-site. Search the Microsoft web-site for Office Primary Interop Assemblies to find a downloable installer.

The following assemblies are required:

Microsoft.Office.Interop.Excel.dll
Microsoft.Vbe.Interop.dll
office.dll
stdole.dll

The assemblies can be installed in one of two ways:

  1. In the Global Assembly Cache (GAC). You can use the batch program delivered with the assemblies to install them in the GAC. They will be available to all applications.

    This is the simplest and most convenient way to install the assemblies, and is recommended for developers.

  2. Private assemblies. You can deliver copies of the DLLs along with the XLL, in the same directory. This is the approach we have taken with the PiaDemo sample.

Debugging

When you attempt to start the debugger for an add-in that uses .NET code with a 64-bit version of Excel, you may get the error message: "The debugger does not support debugging managed code and native code at the same time on this platform."

In this case you have two options:

  • perform your debugging with a 32-bit version of Excel; or
  • in the Project Properties, navigate to the Configuration Properties / Debugging node, and set Debugger Type to Managed Only or Native Only.


Adapter classes for imtx<T>

Introduction

If your existing code makes of a matrix class, and you want to make use of the matrix conversion methods contained in the COper, CXlOper and CXlArray classes, in order to transfer data between Excel and your existing matrix class, you should write an adapter class.

The adapter class must implement all of the methods defined in the imtx<T> interface. You can then use any of the following methods to transfer data to and from Excel:

COper::ReadMatrix()
COper::WriteMatrix()
CXlOper::ReadMatrix()
CXlOper::operator=()
CXlArray::ReadMatrix()

Requirements

An adapter class must implement each of the following methods:

void resize(bool preserve, mtx_size dim0, mtx_size dim1);
T& at(mtx_size i0, mtx_size i1);
const T& at(mtx_size i0, mtx_size i1) const;
size_t size(int dim) const;
bool get_ptrs(T**& ptrs);
bool get_ptrs(const T**& ptrs) const;
bool get_flat(T*& data);
bool get_flat(const T*& data) const;

The required behavior of each method is described under the appropriate imtx<T> method description.

Example

Take as an example the matrix<T> class supported by earlier versions of XLL+. The class declaration is summarised below:

CopyC++
template<class T>
class matrix {
public:
    matrix();
    matrix(size_t rows, size_t cols, const T& def = T());
    ~matrix() {}

    matrix(const matrix<T>& that);
    const matrix<T>& operator=(const matrix& that);

    size_t rows() const { return m_rows; }
    size_t cols() const { return m_cols; }

    void clear();

    void insert_rows(size_t before, size_t n, const T& def = T());
    void insert_cols(size_t before, size_t n, const T& def = T());
    void insert_lbounds(size_t rows, size_t cols, const T& def = T());
    void resize(size_t rows, size_t cols, bool preserve = false,
                const T& def = T());

    const T& at(size_t r, size_t c) const;
    T& at(size_t r, size_t c);
    std::vector<T> row(size_t r) const;
    std::vector<T> col(size_t c) const;

    void add_row(const T* p);
    void add_col(const T* p);

    size_t find_in_row(const T& t, size_t r) const;
    size_t find_in_col(const T& t, size_t c) const;
    void transpose();

    T* col_ptr(size_t col) {
        return &at(0, col);
    }
    const T* col_ptr(size_t col) const {
        return &at(0, col);
    }

    void get_col_ptrs(std::vector<T*>& v);
    std::vector<T*> col_ptrs();
    void get_const_col_ptrs(std::vector<const T*>& v) const;
    std::vector<const T*> const_col_ptrs() const;

    void get_region(size_t top, size_t left, size_t height, size_t width,
                    matrix<T>& matOut) const;

    bool concat_horz(const matrix<T> *amat, int cmat);

    T* begin() { return m_vec.begin(); }
    const T* begin() const { return m_vec.begin(); }
    T* end() { return m_vec.end(); }
    const T* end() const { return m_vec.end(); }

    enum { npos = (size_t)-1 };
protected:
    typedef std::vector<T> _vec;
    _vec m_vec;
};

A straight-forward adapter can be coded as follows:

CopyC++
template<class T>
class mtx_matrix_adapter : public ple::imtx_impl<T> {
public:
    mtx_matrix_adapter(xlp::matrix<T>& impl) : _impl(impl) {}
    virtual void resize(bool preserve, mtx_size dim0, mtx_size dim1) {
        _impl.resize(dim0, dim1, preserve);
    }
    virtual T& at(mtx_size i0, mtx_size i1) {
        return _impl.at(i0, i1);
    }
    virtual const T& at(mtx_size i0, mtx_size i1) const {
        return _impl.at(i0, i1);
    }
    virtual mtx_size size(int dim) const {
        return (dim == 0) ? _impl.rows() : _impl.cols();
    }
    virtual bool get_flat(T*& data) {
        data = _impl.begin();
        return true;
    }
    virtual bool get_flat(const T*& data) const {
        data = _impl.begin();
        return true;
    }
protected:
    xlp::matrix<T>& _impl;
};

template<class T>
mtx_adapter<T> mtx_adapter(xlp::matrix<T>& src) {
    return mtx_matrix_adapter<T>(src);
}

Let us examine each section in turn, beginning with the declaration of the adapter class:

CopyC++
template<class T>
class mtx_matrix_adapter : public ple::imtx_impl<T> {
    ...
};
The class is descended from the imtx_impl<T> template class. This provides default implementations of the optional functionality of an adapter, and ensures that the compiler will check for the existence of all required functionality.

The constructor associates the adapter class with an existing instance of the class to be adapted, and retains a reference to the adapted class:

CopyC++
public:
    mtx_matrix_adapter(xlp::matrix<T>& impl) : _impl(impl) {}
    ...
protected:
    xlp::matrix<T>& _impl;

The resize(),
    size() and
    at() methods are very simple:

CopyC++
public:
    ...
    virtual void resize(bool preserve, mtx_size dim0, mtx_size dim1) {
        _impl.resize(dim0, dim1, preserve);
    }
    virtual T& at(mtx_size i0, mtx_size i1) {
        return _impl.at(i0, i1);
    }
    virtual const T& at(mtx_size i0, mtx_size i1) const {
        return _impl.at(i0, i1);
    }
    virtual mtx_size size(int dim) const {
        return (dim == 0) ? _impl.rows() : _impl.cols();
    }
In each case the methods are simple rephrasings of existing matrix methods, with the understanding that dimension 0 is a row and dimension 1 is a column.

The get_ptrs() method is not implemented, because the storage method of the matrix<T> class does not suit it: the items in matrix<T> are kept in a "flat" arrangement, rather than in separate arrays for each row/column. The adapter class therefore inherits the default method of imtx_impl<T> which returns false, to indicate that the operation is not supported.

The get_flat() method is implemented, because the storage method of the matrix<T> class does suit it. The calls make use of the begin() methods of the matrix<T> class:

CopyC++
virtual bool get_flat(T*& data) {
    data = _impl.begin();
    return true;
}
virtual bool get_flat(const T*& data) const {
    data = _impl.begin();
    return true;
}

As a final touch, add a template method to simplify construction of the adapter:

CopyC++
template<class T>
mtx_adapter<T> mtx_adapter(xlp::matrix<T>& src) {
    return mtx_matrix_adapter<T>(src);
}

You can now make use of the adapter class by wrapping an instance of your matrix class with a call to mtx_adapter(), as in the following examples:

CopyC++
extern "C" __declspec( dllexport )
LPXLOPER ReadXlOper(const COper* Arg1)
{
    CXlOper xloResult;
    ...
    xlp::matrix<double> matrix1, matrix2;
    bOk = bOk && valArg2.ReadMatrix(mtx_adapter(matrix1), "Arg1", strError);
    ...
    xloResult.FromMatrix(mtx_adapter(matrix2));
    ...
}


Arguments that contain entire columns

The following versions of Excel have three bugs that affect add-in arguments that contain entire columns, such as A:A, A:IV, A1:D65536.

  • Excel 97
  • Excel 2000
  • Excel 2002 (Excel XP)
  • Excel 2003

Using a CXlOper Reference type

If you attempt to use a CXlOper to pass such an argument from Excel 97 by reference, Excel converts it to a range containing only 16384 rows (i.e. the same number of rows as the maximum under Excel 95). If the ability to handle entire columns is important to your function, you may want to handle this with a workaround such as the following:

CopyC++
//{{XLP_SRC(XlOperFix)
IMPLEMENT_XLLFN2(XlOperFix, "RR", "XlOperFix", "InputRange",
    "User Defined", "Work around the 16384 row bug in Excel 97",
    "Input range (CXlOper)", "\0", 1)

extern "C" __declspec( dllexport )
LPXLOPER XlOperFix(const CXlOper* InputRange)
{
    CXlOper xloResult;
//}}XLP_SRC

    // Redirect InputRange to a fixed variable, xloFixedRange,
    // if necessary
    CXlOper xloFixedRange;
    if (CXllApp::XlVersion() >= 8.0
     && CXllApp::XlVersion() < 12.0
     && InputRange->IsRef()
     && InputRange->GetRef().Top() == 0
     && InputRange->GetHeight() == 16384)
    {
        CXlRef xlref = InputRange->GetRef();
        xlref.Bottom() = CXlRef::MaxRow();
        if (InputRange->IsMRef())
            xloFixedRange.FromMRef(&xlref, 1, InputRange->GetSheetId());
        else
            xloFixedRange.FromSRef(xlref);
        InputRange = &xloFixedRange;
    }
    // Now use InputRange as usual
    ...
}

Using a CXlOper by value

Alternatively, if you attempt to use a CXlOper value type to pass a column, then Excel simply passes #NUM! instead. The behaviour of CXlOper by reference is buggy, but can at least be made to work, as shown above.

Using a CXlArray

Finally, if you attempt to use a CXlArray to pass a column, then Excel fails to call the function, and displays #VALUE! instead.


Bounded input arrays

The functions COper::ReadVector(),
        COper::ReadMatrix() CXlOper::ReadVector()
        and CXlOper::ReadMatrix()
        support the use of named bounding variables.

Bounding variables

If the plUBound argument of ReadVector() or the plUBound1 or plUBound2 arguments of ReadMatrix() are not zero, then they are used as pointers to a bounding variable.

Inner and outer bounds

The upper bound value will be treated as the size() of the vector, unless the XLA_BOUND_UBOUND_INNER bit of the lFlags argument has been set, in which case its value will be size() - 1 (following Visual Basic conventions).

Fixed upper bounds

If the bounding variable contains a value >= 0 before the call to ReadXXX(), then it will be treated as the required size of the vector/matrix. For example, if the variable contains 10, then the function ReadVector() will fail if the input variable does not contain exactly 10 non-empty items, and will return an error message like "#Error: Expected 10 items for Input".

Variable upper bounds

If the bounding variable contains -1 before the call to ReadXXX(), then its value will be set to the upper bound of the vector or matrix that has been read in.

Shared bounding variables

If a bounding variable is used by more than one call to ReadMatrix() or ReadVector(), then it can be used to ensure that all the arrays read in by these calls are the same size.

Consider the following example, with two vector inputs X and Y containing 3 and 5 cells respectively.

CopyC++
long lBound = -1;
std::vector<long> vecX;
std::vector<double> vecY;

// Because lBound contains -1, the call to X->ReadVector() will set its value.
bOk = bOk && X->ReadVector(vecX, "X", xloResult, &lBound);
// After reading X, lBound will be set to 3

// Because lBound now does not contain -1, the call to Y->ReadVector() will expect an upper bound of 3.
bOk = bOk && Y->ReadVector(vecY, "Y", xloResult, &lBound);
// The call will fail and an error string, "#Error: Expected 3 items for Y", will be returned.

Similarly, you can ensure that a matrix input is square, by assigning the same bounds to *plBound1 and *plBound2.

CopyC++
long lBound = -1;
xlp::matrix<long> matX;
bOk = bOk && X->ReadMatrix(matX, "X", xloResult, 0, &lBound, &lBound);

See matrix & vector flags for a full list of flag values.

See Also

COper::ReadVector() | COper::ReadMatrix() | CXlOper::ReadVector() | CXlOper::ReadMatrix() | matrix & vector flags


Comparison of CXlOper and CXlArray

It is not always clear which of the Excel data types to use for passing arguments to add-in functions. The table below summarises the various limitations and features of each type.

Item | CXlOper | CXlOper | CXlArray
Passes ranges | By value | By reference | By value
Can contain mixed types | Yes | Yes | No; numeric only
Empty cells | Optionally truncated by input routines | Optionally truncated by input routines | Converted to zeroes by Excel
Pass range references | No | Yes | No
Pass entire columns (e.g. A:A or A:D) | No | Passes only the first 16384 rows | No
Maximum number of cells (Excel 95) | 5458 | unlimited (if passed by reference); 5458 (if passed by value) | 5458
Maximum number of rows (Excel 95) | 5458 / number of columns | 16384 | 5458 / number of columns
Maximum number of cells (Excel 97 and above) | limited by available memory | unlimited | limited by available memory
Maximum number of rows (Excel 97 and above) More... | 65535 | 65535 | 65535

Passing very large arrays

If you pass a very large range as an argument to an add-in function, you should consider the following issues.

  • If you use a CXlOper by value or a CXlArray to pass the data, Excel 95 may simply reject the argument if it is too large, and consequently not call the add-in function. The cell containing the function call will display #VALUE!.
  • If your add-in function only looks at a sub-set of the cells in the range, then using a CXlOper will be most efficient. Since only a reference is passed to the add-in, your code can use CXlOper::Coerce() to establish the values of the various sub-sets, and avoid wasting time resolving the whole array.

It is therefore best generally to use a CXlOper reference type to pass very large arrays.

You can find a detailed analysis of large array passing in the demo project, ArgSizes and its test sheet ArgSizes.xls.

Special considerations for Excel 95

The size limitations of CXlArray and COper types are particularly stringent under Excel 95. If you need to support very large array inputs under Excel 95, you should always use the CXlOper type to pass the argument and then call the ReadMatrix() method to extract the data. CXlOper::ReadMatrix() contains code to retrieve the data in chunks from Excel and then put it all back together in the output matrix.


Compiler Error C1083

When building a project, the compiler fails with error C1083

Symptoms

When compiling an XLL+ project, the following error occurs:

fatal error C1083: Cannot open include file: 'xllplus.h': No such file or directory

Summary

  1. When the project is generated by the XLL+ AppWizard, the path to the directory containing the XLL+ header files is added to the project's INCLUDE path.
  2. If this path is incorrect, or if the header files or the project are later moved, then the header files will not be found.
  3. Use the project Settings dialog to fix the problem in an existing project.
  4. If necessary, you should also correct the XLL+ include path the next time you use the XLL+ AppWizard.

Procedure for fixing the problem

In the Project Settings dialog, select the C/C++ / General category, and correct the field Additional Include Directories, as shown below. Note that you will need to do this for both configurations, Debug and Release.

Next, still in the Project Settings dialog, select the Resources / General category, and correct the field Additional Include Directories, as shown below. Note that you will need to do this for both configurations, Debug and Release.

To prevent the problem recurring, you should also correct the setting in the XLL+ / General options dialog. (You can open this by using the Tools/Options menu and selecting the XLL+ / General node, or by using the XLL+ Options command). The property "IncludePath" is in the "Project" category, as shown below.

You should also ensure at this time that the path to the directory containing the XLL+ run-time libraries, such as xlllibr.lib, is correct.


Data types

Excel data types

Below is a list of data types accepted by Excel. The entries in the Argument and Result columns indicate whether the data type is supported by the Wizard as an argument to an add-in and a result, respectively.

Code | Name | 'C' Type | Argument | Result | Description
A | Boolean | BOOL | Yes | Yes | Boolean value as a 32-bit integer. 1 for true, 0 for false.
B | Double | double | Yes | Yes | 8-byte double-precision floating point number.
C | String | const char* | Yes | No | String of ASCII characters, maximum length 255. The length of the string is contained in the first byte.
C% | String | const wchar_t* | Yes | No | String of Unicode characters, maximum length 32767. The length of the string is contained in the first character. Available under Excel 2007 and above.
H | Unsigned short integer | USHORT | Yes | Yes | Unsigned 16-bit integer.
I | Signed short integer | short | Yes | Yes | Signed 16-bit integer.
J | Signed long integer | long | Yes | Yes | Signed 32-bit integer.
K | Floating point number array | XLARRAY4 | Yes | No | Array of 8-byte numbers in an XLARRAY structure.
K% | Floating point number array | XLARRAY12 | Yes | No | Array of 8-byte numbers in an XLARRAY12 structure. Available under Excel 2007 and above.
P | Value | CXlOper | Yes | No | Excel CXlOper value type. May not contain references.
Q | Value | CXlOper | Yes | No | Excel CXlOper value type. May not contain references. Available under Excel 2007 and above.
R | Reference | CXlOper | Yes | Yes | Excel CXlOper reference type. May contain any type including references.
U | Reference | CXlOper | Yes | Yes | Excel CXlOper reference type. May contain any type including references. Available under Excel 2007 and above.

CXlOper data types

Below is a list of data types contained within the CXlOper class. The Enumeration column contains the value of the private xltype member of CXlOper, which can be tested using CXlOper::IsOfType. The method whose name listed in the Test column can be used to determine if the CXlOper is of the given type.

Name | Enumeration | 'C' Type | Test | Description
Boolean | xltypeBool | short int | IsBool() | Boolean value as a 16-bit integer. 1 for true, 0 for false.
Double | xltypeNum | double | IsDouble() | 8-byte double-precision floating point number.
String | xltypeStr | char* | IsString() | Under Excel 2003 and below: String of ASCII characters, maximum length 255. The length of the string is contained in the first byte.
String | xltypeStr | wchar_t* | IsString() | Under Excel 2007 and above: String of Unicode characters, maximum length 32767. The length of the string is contained in the first character.
Error | xltypeErr | short int | IsError() | Error code. See error codes for a full list.
Array | xltypeMulti | Array structure | IsArray() | Structure containing a pointer to an array of COper, a column count and a row count.
Missing | xltypeMissing |  | IsMissing() | No value was provided; the argument is missing.
Reference | xltypeSRef | CXlRef | IsSRef() | Structure describing an Excel rectangular cell range.
Multi-reference | xltypeMRef | CXlRef* | IsMRef() | Structure describing one or more Excel rectangular cell ranges.
Empty | 0 |  | IsEmpty() | Unused or uninitialized value.


Error codes

Error value types

Below is a list of error values that can be returned to Excel as the value of a CXlOper.

Code | Value | Displayed | Description
xlerrNull | 0 | #NULL! | The function's logic requires an intersection of two areas that do not intersect
xlerrDiv0 | 7 | #DIV/0! | Divide by zero
xlerrValue | 15 | #VALUE! | Argument is of the wrong type and cannot be coerced to the right type
xlerrRef | 23 | #REF! | A cell reference is not valid
xlerrName | 29 | #NAME? | A range name is not valid
xlerrNum | 36 | #NUM! | The #NUM! error value occurs when a problem occurs with a number in a formula or function. A typical use is for numeric inputs that are out of range.
xlerrNA | 42 | #N/A | Data is not currently available

Result codes

Below is a list of result codes that can be returned by CXlOper::Excel, CXllApp::Excel, and all methods of CXlMacros and CXlFuncs.

Code | Value | Description
xlretSuccess | 0 | The function call was successful. This is not always proof of complete success; in some cases the values returned by the call will need to be inspected: they may contain error types (see above).
xlretAbort | 1 | The function call was interrupted by the user.
xlretInvXlfn | 2 | The function was not valid or was not valid at this time.
xlretInvCount | 4 | The wrong number of arguments was passed.
xlretInvXloper | 8 | One of the arguments was invalid.
xlretStackOvfl | 16 | Occurs when a call to the Excel SDK API resulted in stack overflow, often as a result of recursion.
xlretFailed | 32 | Occurs when a call to the Excel SDK API failed, often because the API is not available at this time.
xlretUncalced | 64 | Occurs as a result of a call to the Excel SDK API, when one of the inputs to the function was an uncalculated cell. An add-in function should return immediately; it will be called again later, when the cell has been calculated.


Excel built-in function numbers (Alphabetical order)

The tables below list all the Excel built-in functions. The value in the Number column should be used as an argument to CXlOper::Excel() and CXllApp::Excel().

To see the usage of the built-in functions, refer to Excel on-line help, or search MSDN for the following string (making sure that you retain the quotes):

"Microsoft Excel Macro Functions Contents" and "Listed by category"

The functions below are divided into two sections:

Worksheet functions | Functions that can be called from worksheet cells
Command-equivalent functions | Functions that can only be called from macro functions

Worksheet functions

Function | Number
ABS | 24
ABSREF | 79
ACOS | 99
ACOSH | 233
ACTIVECELL | 94
ADDBAR | 151
ADDCOMMAND | 153
ADDMENU | 152
ADDRESS | 219
ADDTOOLBAR | 253
AND | 36
APPTITLE | 262
AREAS | 75
ARGUMENT | 81
ASC | 214
ASIN | 98
ASINH | 232
ATAN | 18
ATAN2 | 97
ATANH | 234
AVEDEV | 269
AVERAGE | 5
BETADIST | 270
BETAINV | 272
BINOMDIST | 273
CALL | 150
CALLER | 89
CANCELKEY | 170
CEILING | 288
CELL | 125
CHAR | 111
CHECKCOMMAND | 155
CHIDIST | 274
CHIINV | 275
CHITEST | 306
CHOOSE | 100
CLEAN | 162
CODE | 121
COLUMN | 9
COLUMNS | 77
COMBIN | 276
CONCATENATE | 336
CONFIDENCE | 277
CORREL | 307
COS | 16
COSH | 230
COUNT | 0
COUNTA | 169
COUNTBLANK | 347
COUNTIF | 346
COVAR | 308
CREATEOBJECT | 236
CRITBINOM | 278
CUSTOMREPEAT | 240
CUSTOMUNDO | 239
DATE | 65
DATEDIF | 351
DATESTRING | 352
DATEVALUE | 140
DAVERAGE | 42
DAY | 67
DAYS360 | 220
DB | 247
DBCS | 215
DCOUNT | 40
DCOUNTA | 199
DDB | 144
DEGREES | 343
DELETEBAR | 200
DELETECOMMAND | 159
DELETEMENU | 158
DELETETOOLBAR | 254
DEREF | 90
DEVSQ | 318
DGET | 235
DIALOGBOX | 161
DIRECTORY | 123
DMAX | 44
DMIN | 43
DOCUMENTS | 93
DOLLAR | 13
DPRODUCT | 189
DSTDEV | 45
DSTDEVP | 195
DSUM | 41
DVAR | 47
DVARP | 196
ECHO | 87
ENABLECOMMAND | 154
ENABLETOOL | 265
ERROR | 84
ERRORTYPE | 261
EVALUATE | 257
EVEN | 279
EXACT | 117
EXEC | 110
EXECUTE | 178
EXP | 21
EXPONDIST | 280
FACT | 184
FALSE | 35
FCLOSE | 133
FDIST | 281
FILES | 166
FIND | 124
FINDB | 205
FINV | 282
FISHER | 283
FISHERINV | 284
FIXED | 14
FLOOR | 285
FOPEN | 132
FORECAST | 309
FORMULACONVERT | 241
FPOS | 139
FREAD | 136
FREADLN | 135
FREQUENCY | 252
FSIZE | 134
FTEST | 310
FV | 57
FWRITE | 138
FWRITELN | 137
GAMMADIST | 286
GAMMAINV | 287
GAMMALN | 271
GEOMEAN | 319
GETBAR | 182
GETCELL | 185
GETCHARTITEM | 160
GETDEF | 145
GETDOCUMENT | 188
GETFORMULA | 106
GETLINKINFO | 242
GETMOVIE | 335
GETNAME | 107
GETNOTE | 191
GETOBJECT | 246
GETPIVOTFIELD | 340
GETPIVOTITEM | 341
GETPIVOTTABLE | 339
GETTOOL | 259
GETTOOLBAR | 258
GETWINDOW | 187
GETWORKBOOK | 268
GETWORKSPACE | 186
GOTO | 53
GROUP | 245
GROWTH | 52
HALT | 54
HARMEAN | 320
HELP | 181
HLOOKUP | 101
HOUR | 71
HYPGEOMDIST | 289
INDEX | 29
INDIRECT | 148
INFO | 244
INITIATE | 175
INPUT | 104
INT | 25
INTERCEPT | 311
IPMT | 167
IRR | 62
ISBLANK | 129
ISERR | 126
ISERROR | 3
ISLOGICAL | 198
ISNA | 2
ISNONTEXT | 190
ISNUMBER | 128
ISPMT | 350
ISREF | 105
ISTEXT | 127
KURT | 322
LARGE | 325
LASTERROR | 238
LEFT | 115
LEFTB | 208
LEN | 32
LENB | 211
LINEST | 49
LINKS | 103
LN | 22
LOG | 109
LOG10 | 23
LOGEST | 51
LOGINV | 291
LOGNORMDIST | 290
LOOKUP | 28
LOWER | 112
MATCH | 64
MAX | 7
MDETERM | 163
MEDIAN | 227
MID | 31
MIDB | 210
MIN | 6
MINUTE | 72
MINVERSE | 164
MIRR | 61
MMULT | 165
MOD | 39
MODE | 330
MONTH | 68
MOVIECOMMAND | 334
N | 131
NA | 10
NAMES | 122
NEGBINOMDIST | 292
NORMDIST | 293
NORMINV | 295
NORMSDIST | 294
NORMSINV | 296
NOT | 38
NOTE | 192
NOW | 74
NPER | 58
NPV | 11
NUMBERSTRING | 353
ODD | 298
OFFSET | 78
OPENDIALOG | 355
OPTIONSLISTSGET | 349
OR | 37
PAUSE | 248
PEARSON | 312
PERCENTILE | 328
PERCENTRANK | 329
PERMUT | 299
PI | 19
PIVOTADDDATA | 338
PMT | 59
POISSON | 300
POKE | 177
POWER | 337
PPMT | 168
PRESSTOOL | 266
PROB | 317
PRODUCT | 183
PROPER | 114
PV | 56
QUARTILE | 327
RADIANS | 342
RAND | 63
RANK | 216
RATE | 60
REFTEXT | 146
REGISTER | 149
REGISTERID | 267
RELREF | 80
RENAMECOMMAND | 156
REPLACE | 119
REPLACEB | 207
REPT | 30
REQUEST | 176
RESETTOOLBAR | 256
RESTART | 180
RESULT | 96
RESUME | 251
RIGHT | 116
RIGHTB | 209
ROMAN | 354
ROUND | 27
ROUNDDOWN | 213
ROUNDUP | 212
ROW | 8
ROWS | 76
RSQ | 313
SAVEDIALOG | 356
SAVETOOLBAR | 264
SCENARIOGET | 348
SEARCH | 82
SEARCHB | 206
SECOND | 73
SELECTION | 95
SERIES | 92
SETNAME | 88
SETVALUE | 108
SHOWBAR | 157
SIGN | 26
SIN | 15
SINH | 229
SKEW | 323
SLN | 142
SLOPE | 315
SMALL | 326
SPELLINGCHECK | 260
SQRT | 20
STANDARDIZE | 297
STDEV | 12
STDEVP | 193
STEP | 85
STEYX | 314
SUBSTITUTE | 120
SUBTOTAL | 344
SUM | 4
SUMIF | 345
SUMPRODUCT | 228
SUMSQ | 321
SUMX2MY2 | 304
SUMX2PY2 | 305
SUMXMY2 | 303
SYD | 143
T | 130
TAN | 17
TANH | 231
TDIST | 301
TERMINATE | 179
TEXT | 48
TEXTBOX | 243
TEXTREF | 147
TIME | 66
TIMEVALUE | 141
TINV | 332
TODAY | 221
TRANSPOSE | 83
TREND | 50
TRIM | 118
TRIMMEAN | 331
TRUE | 34
TRUNC | 197
TTEST | 316
TYPE | 86
UNREGISTER | 201
UPPER | 113
USDOLLAR | 204
VALUE | 33
VAR | 46
VARP | 194
VDB | 222
VLOOKUP | 102
VOLATILE | 237
WEEKDAY | 70
WEIBULL | 302
WINDOWS | 91
WINDOWTITLE | 263
YEAR | 69
ZTEST | 324

Command-equivalent functions

Function | Number
A1R1C1 | 32798
ACTIVATE | 32871
ACTIVATENEXT | 32872
ACTIVATEPREV | 32873
ACTIVECELLFONT | 33244
ADDARROW | 32849
ADDCHARTAUTOFORMAT | 33158
ADDINMANAGER | 33089
ADDLISTITEM | 33219
ADDOVERLAY | 32843
ADDTOOL | 33045
ALERT | 32886
ALIGNMENT | 32811
APPACTIVATE | 32893
APPACTIVATEMICROSOFT | 33237
APPLYNAMES | 32901
APPLYSTYLE | 32980
APPMAXIMIZE | 32941
APPMINIMIZE | 32940
APPMOVE | 32938
APPRESTORE | 32937
APPSIZE | 32939
ARRANGEALL | 32780
ASSIGNTOOBJECT | 32981
ASSIGNTOTOOL | 33061
ATTACHTEXT | 32848
ATTACHTOOLBARS | 33091
ATTRIBUTES | 32987
AUTOOUTLINE | 33161
AXES | 32846
BEEP | 32768
BORDER | 32813
BRINGTOFRONT | 32942
CALCULATEDOCUMENT | 32935
CALCULATENOW | 32799
CALCULATION | 32800
CANCELCOPY | 32888
CELLPROTECTION | 32814
CHANGELINK | 32934
CHARTADDDATA | 33160
CHARTTREND | 33118
CHARTWIZARD | 33056
CHECKBOXPROPERTIES | 33203
CLEAR | 32820
CLEAROUTLINE | 33217
CLEARROUTINGSLIP | 33236
CLOSE | 32784
CLOSEALL | 32771
COLORPALETTE | 32929
COLUMNWIDTH | 32815
COMBINATION | 32841
CONSOLIDATE | 32959
CONSTRAINNUMERIC | 33065
COPY | 32818
COPYCHART | 32915
COPYPICTURE | 32876
COPYTOOL | 33063
CREATENAMES | 32830
CREATEPUBLISHER | 32985
CUSTOMIZETOOLBAR | 33044
CUT | 32817
DATADELETE | 32804
DATAFIND | 32802
DATAFINDNEXT | 32867
DATAFINDPREV | 32868
DATAFORM | 32914
DATALABEL | 33147
DATASERIES | 32808
DEFINENAME | 32829
DEFINESTYLE | 32997
DELETEARROW | 32894
DELETECHARTAUTOFORMAT | 33159
DELETEFORMAT | 32879
DELETENAME | 32878
DELETEOVERLAY | 32921
DELETESTYLE | 32930
DELETETOOL | 33057
DEMOTE | 32971
DISABLEINPUT | 32908
DISPLAY | 32795
DUPLICATE | 32979
ECHO | 32909
EDITBOXPROPERTIES | 33206
EDITCOLOR | 32991
EDITDELETE | 32822
EDITIONOPTIONS | 33019
EDITOBJECT | 33046
EDITREPEAT | 32858
EDITSERIES | 32996
EDITTOOL | 33111
ENABLEOBJECT | 33212
ENABLETIPWIZARD | 33245
ENTERDATA | 33011
ERROR | 32933
ERRORBARX | 33231
ERRORBARY | 33232
EXTENDPOLYGON | 33036
EXTRACT | 32803
FILECLOSE | 32912
FILEDELETE | 32774
FILLAUTO | 33042
FILLDOWN | 32825
FILLGROUP | 32968
FILLLEFT | 32920
FILLRIGHT | 32824
FILLUP | 32919
FILLWORKGROUP | 33069
FILTER | 33215
FILTERADVANCED | 33138
FILTERSHOWALL | 33216
FINDFILE | 33243
FONT | 32794
FONTPROPERTIES | 33149
FORMATAUTO | 33037
FORMATCHART | 33233
FORMATCHARTTYPE | 33191
FORMATFONT | 32918
FORMATLEGEND | 32856
FORMATMAIN | 32993
FORMATMOVE | 32896
FORMATNUMBER | 32810
FORMATOVERLAY | 32994
FORMATSHAPE | 33035
FORMATSIZE | 32897
FORMATTEXT | 32857
FORMULA | 32864
FORMULAARRAY | 32866
FORMULAFILL | 32865
FORMULAFIND | 32832
FORMULAFINDNEXT | 32869
FORMULAFINDPREV | 32870
FORMULAGOTO | 32831
FORMULAREPLACE | 32898
FREEZEPANES | 32903
FULL | 32783
FULLSCREEN | 33184
FUNCTIONWIZARD | 33218
GALLERY3DAREA | 32961
GALLERY3DBAR | 33040
GALLERY3DCOLUMN | 32962
GALLERY3DLINE | 32963
GALLERY3DPIE | 32964
GALLERY3DSURFACE | 33041
GALLERYAREA | 32835
GALLERYBAR | 32836
GALLERYCOLUMN | 32837
GALLERYCUSTOM | 33156
GALLERYDOUGHNUT | 33112
GALLERYLINE | 32838
GALLERYPIE | 32839
GALLERYRADAR | 33017
GALLERYSCATTER | 32840
GOALSEEK | 32966
GRIDLINES | 32844
HIDE | 32861
HIDEDIALOG | 33210
HIDEOBJECT | 32983
HLINE | 32881
HPAGE | 32883
HSCROLL | 32885
INSERT | 32823
INSERTOBJECT | 33027
INSERTPICTURE | 33110
INSERTTITLE | 33148
JUSTIFY | 32860
LABELPROPERTIES | 33204
LEGEND | 32847
LINEPRINT | 33008
LINKCOMBO | 33208
LINKFORMAT | 33192
LISTBOXPROPERTIES | 33205
LISTNAMES | 32911
MACROOPTIONS | 33150
MAILADDMAILER | 33141
MAILDELETEMAILER | 33142
MAILEDITMAILER | 33238
MAILFORWARD | 33145
MAILLOGOFF | 33235
MAILLOGON | 33107
MAILNEXTLETTER | 33146
MAILREPLY | 33143
MAILREPLYALL | 33144
MAILSENDMAILER | 33250
MAINCHART | 32853
MAINCHARTTYPE | 32953
MENUEDITOR | 33090
MERGESTYLES | 33018
MESSAGE | 32890
MOVE | 33030
MOVETOOL | 33058
NEW | 32887
NEWWINDOW | 32779
NOTE | 32922
OBJECTPROPERTIES | 32975
OBJECTPROTECTION | 32982
ONDATA | 32907
ONDOUBLECLICK | 33047
ONENTRY | 33048
ONKEY | 32936
ONRECALC | 32995
ONSHEET | 33239
ONTIME | 32916
ONWINDOW | 32906
OPEN | 32769
OPENLINKS | 32770
OPENMAIL | 32956
OPENTEXT | 33209
OPTIONSCALCULATION | 33086
OPTIONSCHART | 33093
OPTIONSEDIT | 33087
OPTIONSGENERAL | 33124
OPTIONSLISTSADD | 33226
OPTIONSLISTSDELETE | 33227
OPTIONSTRANSITION | 33123
OPTIONSVIEW | 33088
OUTLINE | 32910
OVERLAY | 32854
OVERLAYCHARTTYPE | 32954
PAGESETUP | 32775
PARSE | 32859
PASTE | 32819
PASTELINK | 32892
PASTEPICTURE | 33020
PASTEPICTURELINK | 33021
PASTESPECIAL | 32821
PASTETOOL | 33066
PATTERNS | 32852
PIVOTADDFIELDS | 33084
PIVOTFIELD | 33082
PIVOTFIELDGROUP | 33201
PIVOTFIELDPROPERTIES | 33081
PIVOTFIELDUNGROUP | 33202
PIVOTITEM | 33083
PIVOTITEMPROPERTIES | 33120
PIVOTREFRESH | 33207
PIVOTSHOWPAGES | 33189
PIVOTTABLEWIZARD | 33080
PLACEMENT | 33068
PRECISION | 32797
PREFERRED | 32842
PRINT | 32776
PRINTERSETUP | 32777
PRINTPREVIEW | 32990
PROMOTE | 32970
PROTECTDOCUMENT | 32796
PUSHBUTTONPROPERTIES | 33213
QUIT | 32778
REMOVELISTITEM | 33221
REMOVEPAGEBREAK | 32793
RENAMEOBJECT | 33168
REPLACEFONT | 32902
RESETTOOL | 33064
RESUME | 33026
ROUTEDOCUMENT | 33106
ROUTINGSLIP | 33104
ROWHEIGHT | 32895
RUN | 32785
SAVE | 32772
SAVEAS | 32773
SAVECOPYAS | 33224
SAVENEWOBJECT | 32976
SAVEWORKBOOK | 32913
SAVEWORKSPACE | 33053
SCALE | 32855
SCENARIOADD | 33075
SCENARIOCELLS | 33073
SCENARIODELETE | 33074
SCENARIOEDIT | 33076
SCENARIOMERGE | 33241
SCENARIOSHOW | 33077
SCENARIOSHOWNEXT | 33078
SCENARIOSUMMARY | 33079
SCROLLBARPROPERTIES | 33188
SELECT | 32877
SELECTALL | 33164
SELECTCHART | 32850
SELECTEND | 32955
SELECTLASTCELL | 32833
SELECTLISTITEM | 33222
SELECTPLOTAREA | 32851
SELECTSPECIAL | 32900
SENDKEYS | 32899
SENDMAIL | 32957
SENDTOBACK | 32943
SERIESAXES | 33228
SERIESORDER | 33234
SERIESX | 33229
SERIESY | 33230
SETCONTROLVALUE | 33223
SETCRITERIA | 32806
SETDATABASE | 32805
SETDIALOGDEFAULT | 33214
SETDIALOGFOCUS | 33211
SETEXTRACT | 32984
SETLISTITEM | 33220
SETPAGEBREAK | 32792
SETPREFERRED | 32845
SETPRINTAREA | 32790
SETPRINTTITLES | 32791
SETUPDATESTATUS | 32927
SHARE | 32977
SHARENAME | 32978
SHORTMENUS | 32923
SHOWACTIVECELL | 32834
SHOWCLIPBOARD | 32889
SHOWDETAIL | 32972
SHOWDIALOG | 33163
SHOWINFO | 32904
SHOWLEVELS | 32992
SHOWTOOLBAR | 32988
SIZE | 33029
SORT | 32807
SORTSPECIAL | 32960
SOUNDNOTE | 33033
SOUNDPLAY | 33034
SPELLING | 33022
SPLIT | 32905
STANDARDFONT | 32958
STANDARDWIDTH | 33240
START | 33094
STYLE | 32812
SUBSCRIBETO | 32986
SUBTOTALCREATE | 33166
SUBTOTALREMOVE | 33167
SUMMARYINFO | 33242
TABLE | 32809
TABORDER | 33162
TEXTTOCOLUMNS | 33190
TRACERCLEAR | 33199
TRACERDISPLAY | 33193
TRACERERROR | 33200
TRACERNAVIGATE | 33198
UNDO | 32816
UNGROUP | 32974
UNGROUPSHEETS | 33165
UNHIDE | 32862
UNLOCKEDNEXT | 32874
UNLOCKEDPREV | 32875
UPDATELINK | 32969
VBAADDWATCH | 33115
VBACLEARBREAKPOINTS | 33103
VBADEBUGWINDOW | 33114
VBAEDITWATCH | 33116
VBAEND | 33095
VBAINSERTFILE | 33096
VBAINSTANTWATCH | 33117
VBAMAKEADDIN | 33246
VBAOBJECTBROWSER | 33113
VBAPROCEDUREDEFINITION | 33098
VBAREFERENCES | 33099
VBARESET | 33092
VBASTEPINTO | 33100
VBASTEPOVER | 33101
VBATOGGLEBREAKPOINT | 33102
VIEW3D | 32965
VLINE | 32880
VPAGE | 32882
VSCROLL | 32884
WAIT | 32917
WINDOWMAXIMIZE | 32932
WINDOWMINIMIZE | 33028
WINDOWMOVE | 32782
WINDOWRESTORE | 32931
WINDOWSIZE | 32781
WORKBOOKACTIVATE | 33060
WORKBOOKADD | 33049
WORKBOOKCOPY | 33051
WORKBOOKDELETE | 33153
WORKBOOKHIDE | 33151
WORKBOOKINSERT | 33122
WORKBOOKMOVE | 33050
WORKBOOKNAME | 33154
WORKBOOKNEW | 33070
WORKBOOKNEXT | 33181
WORKBOOKOPTIONS | 33052
WORKBOOKPREV | 33182
WORKBOOKPROTECT | 33185
WORKBOOKSCROLL | 33180
WORKBOOKSELECT | 33059
WORKBOOKTABSPLIT | 33183
WORKBOOKUNHIDE | 33152
WORKGROUP | 32967
WORKSPACE | 32863
ZOOM | 33024

See Also

Excel built-in function numbers (Numeric order) | Walkthrough: Calling an Excel built-in function from your add-in


Excel built-in function numbers (Numeric order)

The table below lists all the Excel built-in functions. The value in the Number column should be used as an argument to CXlOper::Excel() and CXllApp::Excel().

To see the usage of the built-in functions, refer to Excel on-line help, or search MSDN for the following string (making sure that you retain the quotes):

"Microsoft Excel Macro Functions Contents" and "Listed by category"

The functions below are divided into two sections:

Worksheet functions | Functions that can be called from worksheet cells
Command-equivalent functions | Functions that can only be called from macro functions

Worksheet functions

Function | Number
COUNT | 0
ISNA | 2
ISERROR | 3
SUM | 4
AVERAGE | 5
MIN | 6
MAX | 7
ROW | 8
COLUMN | 9
NA | 10
NPV | 11
STDEV | 12
DOLLAR | 13
FIXED | 14
SIN | 15
COS | 16
TAN | 17
ATAN | 18
PI | 19
SQRT | 20
EXP | 21
LN | 22
LOG10 | 23
ABS | 24
INT | 25
SIGN | 26
ROUND | 27
LOOKUP | 28
INDEX | 29
REPT | 30
MID | 31
LEN | 32
VALUE | 33
TRUE | 34
FALSE | 35
AND | 36
OR | 37
NOT | 38
MOD | 39
DCOUNT | 40
DSUM | 41
DAVERAGE | 42
DMIN | 43
DMAX | 44
DSTDEV | 45
VAR | 46
DVAR | 47
TEXT | 48
LINEST | 49
TREND | 50
LOGEST | 51
GROWTH | 52
GOTO | 53
HALT | 54
PV | 56
FV | 57
NPER | 58
PMT | 59
RATE | 60
MIRR | 61
IRR | 62
RAND | 63
MATCH | 64
DATE | 65
TIME | 66
DAY | 67
MONTH | 68
YEAR | 69
WEEKDAY | 70
HOUR | 71
MINUTE | 72
SECOND | 73
NOW | 74
AREAS | 75
ROWS | 76
COLUMNS | 77
OFFSET | 78
ABSREF | 79
RELREF | 80
ARGUMENT | 81
SEARCH | 82
TRANSPOSE | 83
ERROR | 84
STEP | 85
TYPE | 86
ECHO | 87
SETNAME | 88
CALLER | 89
DEREF | 90
WINDOWS | 91
SERIES | 92
DOCUMENTS | 93
ACTIVECELL | 94
SELECTION | 95
RESULT | 96
ATAN2 | 97
ASIN | 98
ACOS | 99
CHOOSE | 100
HLOOKUP | 101
VLOOKUP | 102
LINKS | 103
INPUT | 104
ISREF | 105
GETFORMULA | 106
GETNAME | 107
SETVALUE | 108
LOG | 109
EXEC | 110
CHAR | 111
LOWER | 112
UPPER | 113
PROPER | 114
LEFT | 115
RIGHT | 116
EXACT | 117
TRIM | 118
REPLACE | 119
SUBSTITUTE | 120
CODE | 121
NAMES | 122
DIRECTORY | 123
FIND | 124
CELL | 125
ISERR | 126
ISTEXT | 127
ISNUMBER | 128
ISBLANK | 129
T | 130
N | 131
FOPEN | 132
FCLOSE | 133
FSIZE | 134
FREADLN | 135
FREAD | 136
FWRITELN | 137
FWRITE | 138
FPOS | 139
DATEVALUE | 140
TIMEVALUE | 141
SLN | 142
SYD | 143
DDB | 144
GETDEF | 145
REFTEXT | 146
TEXTREF | 147
INDIRECT | 148
REGISTER | 149
CALL | 150
ADDBAR | 151
ADDMENU | 152
ADDCOMMAND | 153
ENABLECOMMAND | 154
CHECKCOMMAND | 155
RENAMECOMMAND | 156
SHOWBAR | 157
DELETEMENU | 158
DELETECOMMAND | 159
GETCHARTITEM | 160
DIALOGBOX | 161
CLEAN | 162
MDETERM | 163
MINVERSE | 164
MMULT | 165
FILES | 166
IPMT | 167
PPMT | 168
COUNTA | 169
CANCELKEY | 170
INITIATE | 175
REQUEST | 176
POKE | 177
EXECUTE | 178
TERMINATE | 179
RESTART | 180
HELP | 181
GETBAR | 182
PRODUCT | 183
FACT | 184
GETCELL | 185
GETWORKSPACE | 186
GETWINDOW | 187
GETDOCUMENT | 188
DPRODUCT | 189
ISNONTEXT | 190
GETNOTE | 191
NOTE | 192
STDEVP | 193
VARP | 194
DSTDEVP | 195
DVARP | 196
TRUNC | 197
ISLOGICAL | 198
DCOUNTA | 199
DELETEBAR | 200
UNREGISTER | 201
USDOLLAR | 204
FINDB | 205
SEARCHB | 206
REPLACEB | 207
LEFTB | 208
RIGHTB | 209
MIDB | 210
LENB | 211
ROUNDUP | 212
ROUNDDOWN | 213
ASC | 214
DBCS | 215
RANK | 216
ADDRESS | 219
DAYS360 | 220
TODAY | 221
VDB | 222
MEDIAN | 227
SUMPRODUCT | 228
SINH | 229
COSH | 230
TANH | 231
ASINH | 232
ACOSH | 233
ATANH | 234
DGET | 235
CREATEOBJECT | 236
VOLATILE | 237
LASTERROR | 238
CUSTOMUNDO | 239
CUSTOMREPEAT | 240
FORMULACONVERT | 241
GETLINKINFO | 242
TEXTBOX | 243
INFO | 244
GROUP | 245
GETOBJECT | 246
DB | 247
PAUSE | 248
RESUME | 251
FREQUENCY | 252
ADDTOOLBAR | 253
DELETETOOLBAR | 254
RESETTOOLBAR | 256
EVALUATE | 257
GETTOOLBAR | 258
GETTOOL | 259
SPELLINGCHECK | 260
ERRORTYPE | 261
APPTITLE | 262
WINDOWTITLE | 263
SAVETOOLBAR | 264
ENABLETOOL | 265
PRESSTOOL | 266
REGISTERID | 267
GETWORKBOOK | 268
AVEDEV | 269
BETADIST | 270
GAMMALN | 271
BETAINV | 272
BINOMDIST | 273
CHIDIST | 274
CHIINV | 275
COMBIN | 276
CONFIDENCE | 277
CRITBINOM | 278
EVEN | 279
EXPONDIST | 280
FDIST | 281
FINV | 282
FISHER | 283
FISHERINV | 284
FLOOR | 285
GAMMADIST | 286
GAMMAINV | 287
CEILING | 288
HYPGEOMDIST | 289
LOGNORMDIST | 290
LOGINV | 291
NEGBINOMDIST | 292
NORMDIST | 293
NORMSDIST | 294
NORMINV | 295
NORMSINV | 296
STANDARDIZE | 297
ODD | 298
PERMUT | 299
POISSON | 300
TDIST | 301
WEIBULL | 302
SUMXMY2 | 303
SUMX2MY2 | 304
SUMX2PY2 | 305
CHITEST | 306
CORREL | 307
COVAR | 308
FORECAST | 309
FTEST | 310
INTERCEPT | 311
PEARSON | 312
RSQ | 313
STEYX | 314
SLOPE | 315
TTEST | 316
PROB | 317
DEVSQ | 318
GEOMEAN | 319
HARMEAN | 320
SUMSQ | 321
KURT | 322
SKEW | 323
ZTEST | 324
LARGE | 325
SMALL | 326
QUARTILE | 327
PERCENTILE | 328
PERCENTRANK | 329
MODE | 330
TRIMMEAN | 331
TINV | 332
MOVIECOMMAND | 334
GETMOVIE | 335
CONCATENATE | 336
POWER | 337
PIVOTADDDATA | 338
GETPIVOTTABLE | 339
GETPIVOTFIELD | 340
GETPIVOTITEM | 341
RADIANS | 342
DEGREES | 343
SUBTOTAL | 344
SUMIF | 345
COUNTIF | 346
COUNTBLANK | 347
SCENARIOGET | 348
OPTIONSLISTSGET | 349
ISPMT | 350
DATEDIF | 351
DATESTRING | 352
NUMBERSTRING | 353
ROMAN | 354
OPENDIALOG | 355
SAVEDIALOG | 356

Command-equivalent functions

Function | Number
BEEP | 32768
OPEN | 32769
OPENLINKS | 32770
CLOSEALL | 32771
SAVE | 32772
SAVEAS | 32773
FILEDELETE | 32774
PAGESETUP | 32775
PRINT | 32776
PRINTERSETUP | 32777
QUIT | 32778
NEWWINDOW | 32779
ARRANGEALL | 32780
WINDOWSIZE | 32781
WINDOWMOVE | 32782
FULL | 32783
CLOSE | 32784
RUN | 32785
SETPRINTAREA | 32790
SETPRINTTITLES | 32791
SETPAGEBREAK | 32792
REMOVEPAGEBREAK | 32793
FONT | 32794
DISPLAY | 32795
PROTECTDOCUMENT | 32796
PRECISION | 32797
A1R1C1 | 32798
CALCULATENOW | 32799
CALCULATION | 32800
DATAFIND | 32802
EXTRACT | 32803
DATADELETE | 32804
SETDATABASE | 32805
SETCRITERIA | 32806
SORT | 32807
DATASERIES | 32808
TABLE | 32809
FORMATNUMBER | 32810
ALIGNMENT | 32811
STYLE | 32812
BORDER | 32813
CELLPROTECTION | 32814
COLUMNWIDTH | 32815
UNDO | 32816
CUT | 32817
COPY | 32818
PASTE | 32819
CLEAR | 32820
PASTESPECIAL | 32821
EDITDELETE | 32822
INSERT | 32823
FILLRIGHT | 32824
FILLDOWN | 32825
DEFINENAME | 32829
CREATENAMES | 32830
FORMULAGOTO | 32831
FORMULAFIND | 32832
SELECTLASTCELL | 32833
SHOWACTIVECELL | 32834
GALLERYAREA | 32835
GALLERYBAR | 32836
GALLERYCOLUMN | 32837
GALLERYLINE | 32838
GALLERYPIE | 32839
GALLERYSCATTER | 32840
COMBINATION | 32841
PREFERRED | 32842
ADDOVERLAY | 32843
GRIDLINES | 32844
SETPREFERRED | 32845
AXES | 32846
LEGEND | 32847
ATTACHTEXT | 32848
ADDARROW | 32849
SELECTCHART | 32850
SELECTPLOTAREA | 32851
PATTERNS | 32852
MAINCHART | 32853
OVERLAY | 32854
SCALE | 32855
FORMATLEGEND | 32856
FORMATTEXT | 32857
EDITREPEAT | 32858
PARSE | 32859
JUSTIFY | 32860
HIDE | 32861
UNHIDE | 32862
WORKSPACE | 32863
FORMULA | 32864
FORMULAFILL | 32865
FORMULAARRAY | 32866
DATAFINDNEXT | 32867
DATAFINDPREV | 32868
FORMULAFINDNEXT | 32869
FORMULAFINDPREV | 32870
ACTIVATE | 32871
ACTIVATENEXT | 32872
ACTIVATEPREV | 32873
UNLOCKEDNEXT | 32874
UNLOCKEDPREV | 32875
COPYPICTURE | 32876
SELECT | 32877
DELETENAME | 32878
DELETEFORMAT | 32879
VLINE | 32880
HLINE | 32881
VPAGE | 32882
HPAGE | 32883
VSCROLL | 32884
HSCROLL | 32885
ALERT | 32886
NEW | 32887
CANCELCOPY | 32888
SHOWCLIPBOARD | 32889
MESSAGE | 32890
PASTELINK | 32892
APPACTIVATE | 32893
DELETEARROW | 32894
ROWHEIGHT | 32895
FORMATMOVE | 32896
FORMATSIZE | 32897
FORMULAREPLACE | 32898
SENDKEYS | 32899
SELECTSPECIAL | 32900
APPLYNAMES | 32901
REPLACEFONT | 32902
FREEZEPANES | 32903
SHOWINFO | 32904
SPLIT | 32905
ONWINDOW | 32906
ONDATA | 32907
DISABLEINPUT | 32908
ECHO | 32909
OUTLINE | 32910
LISTNAMES | 32911
FILECLOSE | 32912
SAVEWORKBOOK | 32913
DATAFORM | 32914
COPYCHART | 32915
ONTIME | 32916
WAIT | 32917
FORMATFONT | 32918
FILLUP | 32919
FILLLEFT | 32920
DELETEOVERLAY | 32921
NOTE | 32922
SHORTMENUS | 32923
SETUPDATESTATUS | 32927
COLORPALETTE | 32929
DELETESTYLE | 32930
WINDOWRESTORE | 32931
WINDOWMAXIMIZE | 32932
ERROR | 32933
CHANGELINK | 32934
CALCULATEDOCUMENT | 32935
ONKEY | 32936
APPRESTORE | 32937
APPMOVE | 32938
APPSIZE | 32939
APPMINIMIZE | 32940
APPMAXIMIZE | 32941
BRINGTOFRONT | 32942
SENDTOBACK | 32943
MAINCHARTTYPE | 32953
OVERLAYCHARTTYPE | 32954
SELECTEND | 32955
OPENMAIL | 32956
SENDMAIL | 32957
STANDARDFONT | 32958
CONSOLIDATE | 32959
SORTSPECIAL | 32960
GALLERY3DAREA | 32961
GALLERY3DCOLUMN | 32962
GALLERY3DLINE | 32963
GALLERY3DPIE | 32964
VIEW3D | 32965
GOALSEEK | 32966
WORKGROUP | 32967
FILLGROUP | 32968
UPDATELINK | 32969
PROMOTE | 32970
DEMOTE | 32971
SHOWDETAIL | 32972
UNGROUP | 32974
OBJECTPROPERTIES | 32975
SAVENEWOBJECT | 32976
SHARE | 32977
SHARENAME | 32978
DUPLICATE | 32979
APPLYSTYLE | 32980
ASSIGNTOOBJECT | 32981
OBJECTPROTECTION | 32982
HIDEOBJECT | 32983
SETEXTRACT | 32984
CREATEPUBLISHER | 32985
SUBSCRIBETO | 32986
ATTRIBUTES | 32987
SHOWTOOLBAR | 32988
PRINTPREVIEW | 32990
EDITCOLOR | 32991
SHOWLEVELS | 32992
FORMATMAIN | 32993
FORMATOVERLAY | 32994
ONRECALC | 32995
EDITSERIES | 32996
DEFINESTYLE | 32997
LINEPRINT | 33008
ENTERDATA | 33011
GALLERYRADAR | 33017
MERGESTYLES | 33018
EDITIONOPTIONS | 33019
PASTEPICTURE | 33020
PASTEPICTURELINK | 33021
SPELLING | 33022
ZOOM | 33024
RESUME | 33026
INSERTOBJECT | 33027
WINDOWMINIMIZE | 33028
SIZE | 33029
MOVE | 33030
SOUNDNOTE | 33033
SOUNDPLAY | 33034
FORMATSHAPE | 33035
EXTENDPOLYGON | 33036
FORMATAUTO | 33037
GALLERY3DBAR | 33040
GALLERY3DSURFACE | 33041
FILLAUTO | 33042
CUSTOMIZETOOLBAR | 33044
ADDTOOL | 33045
EDITOBJECT | 33046
ONDOUBLECLICK | 33047
ONENTRY | 33048
WORKBOOKADD | 33049
WORKBOOKMOVE | 33050
WORKBOOKCOPY | 33051
WORKBOOKOPTIONS | 33052
SAVEWORKSPACE | 33053
CHARTWIZARD | 33056
DELETETOOL | 33057
MOVETOOL | 33058
WORKBOOKSELECT | 33059
WORKBOOKACTIVATE | 33060
ASSIGNTOTOOL | 33061
COPYTOOL | 33063
RESETTOOL | 33064
CONSTRAINNUMERIC | 33065
PASTETOOL | 33066
PLACEMENT | 33068
FILLWORKGROUP | 33069
WORKBOOKNEW | 33070
SCENARIOCELLS | 33073
SCENARIODELETE | 33074
SCENARIOADD | 33075
SCENARIOEDIT | 33076
SCENARIOSHOW | 33077
SCENARIOSHOWNEXT | 33078
SCENARIOSUMMARY | 33079
PIVOTTABLEWIZARD | 33080
PIVOTFIELDPROPERTIES | 33081
PIVOTFIELD | 33082
PIVOTITEM | 33083
PIVOTADDFIELDS | 33084
OPTIONSCALCULATION | 33086
OPTIONSEDIT | 33087
OPTIONSVIEW | 33088
ADDINMANAGER | 33089
MENUEDITOR | 33090
ATTACHTOOLBARS | 33091
VBARESET | 33092
OPTIONSCHART | 33093
START | 33094
VBAEND | 33095
VBAINSERTFILE | 33096
VBAPROCEDUREDEFINITION | 33098
VBAREFERENCES | 33099
VBASTEPINTO | 33100
VBASTEPOVER | 33101
VBATOGGLEBREAKPOINT | 33102
VBACLEARBREAKPOINTS | 33103
ROUTINGSLIP | 33104
ROUTEDOCUMENT | 33106
MAILLOGON | 33107
INSERTPICTURE | 33110
EDITTOOL | 33111
GALLERYDOUGHNUT | 33112
VBAOBJECTBROWSER | 33113
VBADEBUGWINDOW | 33114
VBAADDWATCH | 33115
VBAEDITWATCH | 33116
VBAINSTANTWATCH | 33117
CHARTTREND | 33118
PIVOTITEMPROPERTIES | 33120
WORKBOOKINSERT | 33122
OPTIONSTRANSITION | 33123
OPTIONSGENERAL | 33124
FILTERADVANCED | 33138
MAILADDMAILER | 33141
MAILDELETEMAILER | 33142
MAILREPLY | 33143
MAILREPLYALL | 33144
MAILFORWARD | 33145
MAILNEXTLETTER | 33146
DATALABEL | 33147
INSERTTITLE | 33148
FONTPROPERTIES | 33149
MACROOPTIONS | 33150
WORKBOOKHIDE | 33151
WORKBOOKUNHIDE | 33152
WORKBOOKDELETE | 33153
WORKBOOKNAME | 33154
GALLERYCUSTOM | 33156
ADDCHARTAUTOFORMAT | 33158
DELETECHARTAUTOFORMAT | 33159
CHARTADDDATA | 33160
AUTOOUTLINE | 33161
TABORDER | 33162
SHOWDIALOG | 33163
SELECTALL | 33164
UNGROUPSHEETS | 33165
SUBTOTALCREATE | 33166
SUBTOTALREMOVE | 33167
RENAMEOBJECT | 33168
WORKBOOKSCROLL | 33180
WORKBOOKNEXT | 33181
WORKBOOKPREV | 33182
WORKBOOKTABSPLIT | 33183
FULLSCREEN | 33184
WORKBOOKPROTECT | 33185
SCROLLBARPROPERTIES | 33188
PIVOTSHOWPAGES | 33189
TEXTTOCOLUMNS | 33190
FORMATCHARTTYPE | 33191
LINKFORMAT | 33192
TRACERDISPLAY | 33193
TRACERNAVIGATE | 33198
TRACERCLEAR | 33199
TRACERERROR | 33200
PIVOTFIELDGROUP | 33201
PIVOTFIELDUNGROUP | 33202
CHECKBOXPROPERTIES | 33203
LABELPROPERTIES | 33204
LISTBOXPROPERTIES | 33205
EDITBOXPROPERTIES | 33206
PIVOTREFRESH | 33207
LINKCOMBO | 33208
OPENTEXT | 33209
HIDEDIALOG | 33210
SETDIALOGFOCUS | 33211
ENABLEOBJECT | 33212
PUSHBUTTONPROPERTIES | 33213
SETDIALOGDEFAULT | 33214
FILTER | 33215
FILTERSHOWALL | 33216
CLEAROUTLINE | 33217
FUNCTIONWIZARD | 33218
ADDLISTITEM | 33219
SETLISTITEM | 33220
REMOVELISTITEM | 33221
SELECTLISTITEM | 33222
SETCONTROLVALUE | 33223
SAVECOPYAS | 33224
OPTIONSLISTSADD | 33226
OPTIONSLISTSDELETE | 33227
SERIESAXES | 33228
SERIESX | 33229
SERIESY | 33230
ERRORBARX | 33231
ERRORBARY | 33232
FORMATCHART | 33233
SERIESORDER | 33234
MAILLOGOFF | 33235
CLEARROUTINGSLIP | 33236
APPACTIVATEMICROSOFT | 33237
MAILEDITMAILER | 33238
ONSHEET | 33239
STANDARDWIDTH | 33240
SCENARIOMERGE | 33241
SUMMARYINFO | 33242
FINDFILE | 33243
ACTIVECELLFONT | 33244
ENABLETIPWIZARD | 33245
VBAMAKEADDIN | 33246
MAILSENDMAILER | 33250

See Also

Excel built-in function numbers (Alphabetical order) | Walkthrough: Calling an Excel built-in function from your add-in


Functions with no arguments have no description in the Excel Formula Wizard

Functions with no arguments have no description in the Excel Formula Wizard

Symptoms

When an XLL+ function with no arguments is displayed in the Excel Formula Wizard, the following message is displayed.

No help available.
This occurs even when a help string for the function has been defined.

Summary

  1. The Excel Formula Wizard offers two types of behaviour for XLL+ add-in functions which have no arguments:
    1. Display the string "No help available." as discussed above.
    2. Display an empty text box, prompting for a non-existent argument:

      We consider the first behaviour - displaying no help - to be less bad than the second behaviour - displaying a misleading prompt.

  2. The XLL+ run-time library defaults to the first behaviour ("No help available.") You can use a work-around to force the second behaviour.
  3. We are working to find an optimum solution (i.e. displaying the correct help text, and not displaying the irrelevant and misleading edit box).

Procedure for applying the work-around

In the module's InitInstance() function, call something like the following:

CopyC++
FindFn("NoArgs_VersionInfo")->m_stArgNames = " ";
The trick here is to convince the XLL+ run-time that there are some arguments to the function, thereby triggering the second class of behaviour.

The argument to FindFn() should be the exported (Excel) function name. The string assigned, as the right-hand-side value, should be a single blank: " ".

It is essential that the work-around be called after the call to AddStaticFns(). For example:

CopyC++
BOOL CNoArgsApp::InitInstance()
{
    // Call the base class
    if ( !CXllApp::InitInstance() )
        return FALSE;

    // Set the name of the library to the default value
    m_stName = m_pszDefName;

    // Add the statically defined function specifications
    AddStaticFns();

    // TODO: Add your specialized code here
    FindFn("NoArgs_VersionInfo")->m_stArgNames = " ";

    return TRUE;
}


Limits of argument descriptions

The last arguments' descriptions are the same as the description of an earlier argument

Problem

If a function description is long, then the last N arguments' descriptions are lost, and the description for the (N+1) from last argument is used instead.

Summary

  1. There is a limit (imposed by Excel, not by XLL+) to the total number of characters and words of description that can be associated with one function.
  2. The table below describes the limits.
  3. A checking function XlCheckFnStrings() is provided below, which can be used to check whether the strings provided are too long. This function can be called during initialisation to print warnings to the console.

String size limits

Arguments | Maximum characters in function description + argument list
8 | 452
9 | 429
10 | 238
11 | 238
12 | 216
13 | 180
14 | 163
15 | 156
16 | 142
16 | 123
18 | 111
19 | 99

Size checking functions

Add the functions below to your code, before the InitInstance() event handler.

CopyC++
BOOL XlCheckFnStrings(CXllFn* pfn) {
    static int anLimits[] = {
        8,  452,
        9,  429,
        10, 238,
        11, 238,
        12, 216,
        13, 180,
        14, 163,
        15, 156,
        16, 142,
        17, 123,
        18, 111,
        19, 99,
        0, 0
    };
    int i;
    int cChars = pfn->m_stArgNames.GetLength() + pfn->m_stHelpText.GetLength();
    for (i = 0; anLimits[i]; i += 2) {
        if (pfn->m_astArgHelpText.GetSize() < anLimits[i])
            return TRUE;
        if (pfn->m_astArgHelpText.GetSize() == anLimits[i])
        {
            if (cChars <= anLimits[i+1])
                return TRUE;
            else
                break;
        }
    }
    if (anLimits[i])
    {
        TRACE("!!WARNING\n"
              "  Function '%s': m_stArgNames.GetLength()=%d; m_stHelpText.GetLength()=%d\n"
              "  Total = %d; limit for combined length = %d\n\n",
            (LPCSTR)pfn->m_stName,
            pfn->m_stArgNames.GetLength(),
            pfn->m_stHelpText.GetLength(),
            pfn->m_stArgNames.GetLength()+pfn->m_stHelpText.GetLength(),
            anLimits[i+1]);
    }
    else
    {
        TRACE("!!WARNING\n"
              "  Function '%s': argument count > 19\n"
              "  %d argument(s) will have no descriptions\n\n",
            (LPCSTR)pfn->m_stName,
            pfn->m_astArgHelpText.GetSize() - 19);
    }
    return FALSE;
}

BOOL XlCheckFnStrings(CXllApp* app, const char* pszExportedName) {
    CXllFn* pfn = app->FindFn(pszExportedName);
    if (pfn == 0)
    {
        TRACE("Function '%s' not found\n", pszExportedName);
        return FALSE;
    }
    return XlCheckFnStrings(pfn);
}

BOOL XlCheckFnStrings(CXllApp* app) {
    CXllApp::POSITION pos = app->GetStartFnPosition();
    CXllFn* pfn;
    CString fnName;
    BOOL bAnyBad = FALSE;
    while (pos != NULL) {
        app->GetNextFnAssoc(pos, fnName, pfn);
        if (!XlCheckFnStrings(pfn))
            bAnyBad = TRUE;
    }
    return !bAnyBad;
}

Call the string size checker in your InitInstance() function

Add a call to XlCheckFnStrings(app) in your InitInstance() function, as in the example below:

CopyC++
BOOL CCarefulApp::InitInstance()
{
    // Call the base class
    if ( !CXllApp::InitInstance() )
        return FALSE;

    // Set the name of the library to the default value
    m_stName = m_pszDefName;

    // Add the statically defined function specifications
    AddStaticFns();

    // TODO: Add your specialized code here
#ifdef _DEBUG
    if (!XlCheckFnStrings(this))
    {
        MessageBox(NULL, "At least one function will lose its argument descriptions.\n"
            "See the console Debug window for more information", "XLL+",
            MB_OK+MB_ICONEXCLAMATION);
    }
#endif
    return TRUE;
}


Linker Error LNK2005

After saving a project, the linker fails with error LNK2005

Symptoms

After adding a new source file or library to an XLL+ project and saving the project, the following linker error occurs:

LNK2005: symbol multiply defined

In particular, this can occur in a project which previously linked perfectly.

Summary

  1. The Microsoft run-time libraries use weak external linkage to resolve the linking of some important functions, including new, delete and DllMain().
    Optionally, see MSDN articles Q148652 and Q72651 for more details of this technique and its implications, in order to gain a deeper understanding of what is occurring.
  2. To be sure of curing the problem, put the appropriate XLL+ run-time library at the start of the list of the Additional Dependencies which can be found in the Linker / Input page of the Project Properties window. A list of the libraries required for the various builds is below.

Procedure for fixing the problem

Determine the name of the appropriate XLL+ run-time library, using the list below. In the Link / Input page of the Project Settings dialog, put the name of the library at the start of the Additional Dependencies field. Note that you will need to do this for both configurations, Debug and Release, and that each configuration will use a different library.

In the Additional Dependencies field add the required libraries at the beginning (i.e. left-hand side) of the list. The required libraries are as follows. Ensure that you select the correct libraries for the builds you are using.

Build | Configuration | Character set | Library
MFC | Debug | ANSI | xlllibd.lib
MFC | Release | ANSI | xlllibr.lib
MFC | Debug | Unicode | xlllibdw.lib
MFC | Release | Unicode | xlllibrw.lib
STL | Debug | ANSI | xlllibsd.lib
STL | Release | ANSI | xlllibsr.lib
STL | Debug | Unicode | xlllibsdw.lib
STL | Release | Unicode | xlllibsrw.lib


Microsoft Excel 4 Function Reference

It is becoming more difficult to get hold of the Microsoft Excel 4 Function Reference. However almost all of the necessary documentation can still be found in MSDN. Search MSDN using the search strings below to find it. (Make sure you retain the quotes.)

Search string | Topic | Version
"Microsoft Excel Macro Functions Contents" and "Listed by category" | Macro function references for all Excel built-in functions, including macros. | Excel 95.
"Converting C-API Add-Ins to 32-bit Microsoft Excel" | Copies of the SDK files XLCALL.H and XLCALL32.LIB. Click on the link "Click to open or copy the CAPI project files" to extract the files. | Excel 95.
"The Microsoft Excel Developer's Kit provides information for software" | The last release of the SDK documentation. | Excel 97.


Requirements

XLL+ 7.0 for Visual Studio 2013

Developers

The table below lists the requirements for developers using XLL+ 7.0 with Microsoft Visual Studio 2013. Note that Microsoft Visual Studio 2013 Express Editions are not supported and that Excel as part of Office 365 is not supported.

Operating system | Windows Vista (32-bit or 64-bit)
 | Windows 7 (32-bit or 64-bit)
 | Windows 8.1 (32-bit or 64-bit)
Microsoft Visual Studio | Microsoft Visual Studio 2013 - Professional edition
 | Microsoft Visual Studio 2013 - Premium edition
 | Microsoft Visual Studio 2013 - Ultimate edition
Microsoft Help Compiler | Microsoft HTML Help Studio 1.4
Microsoft Excel | Excel 95
 | Excel 97
 | Excel 2000
 | Excel XP (2002)
 | Excel 2003
 | Excel 2007
 | Excel 2010 (32-bit or 64-bit)
 | Excel 2013 (32-bit or 64-bit)

Users

The table below lists the requirements for running XLLs built using XLL+ 7.0 for Visual Studio 2013. Note that Excel as part of Office 365 is not supported.

Operating system | Windows 2000 Professional
 | Windows XP
 | Windows Vista (32-bit or 64-bit)
 | Windows 7 (32-bit or 64-bit)
 | Windows 8.1 (32-bit or 64-bit)
Microsoft Excel | Excel 95
 | Excel 97
 | Excel 2000
 | Excel XP (2002)
 | Excel 2003
 | Excel 2007
 | Excel 2010 (32-bit or 64-bit)
 | Excel 2013 (32-bit or 64-bit)

See also Deployment in the User Guide.

XLL+ 7.0 for Visual Studio 2012

Developers

The table below lists the requirements for developers using XLL+ 7.0 with Microsoft Visual Studio 2012. Note that Microsoft Visual Studio 2012 Express Editions are not supported and that Excel as part of Office 365 is not supported.

Operating system | Windows Vista (32-bit or 64-bit)
 | Windows 7 (32-bit or 64-bit)
 | Windows 8.1 (32-bit or 64-bit)
Microsoft Visual Studio | Microsoft Visual Studio 2012 - Professional edition
 | Microsoft Visual Studio 2012 - Premium edition
 | Microsoft Visual Studio 2012 - Ultimate edition
Microsoft Help Compiler | Microsoft HTML Help Studio 1.4
Microsoft Excel | Excel 95
 | Excel 97
 | Excel 2000
 | Excel XP (2002)
 | Excel 2003
 | Excel 2007
 | Excel 2010 (32-bit or 64-bit)
 | Excel 2013 (32-bit or 64-bit)

Users

The table below lists the requirements for running XLLs built using XLL+ 7.0 for Visual Studio 2012. Note that Excel as part of Office 365 is not supported.

Operating system | Windows 2000 Professional
 | Windows XP
 | Windows Vista (32-bit or 64-bit)
 | Windows 7 (32-bit or 64-bit)
 | Windows 8.1 (32-bit or 64-bit)
Microsoft Excel | Excel 95
 | Excel 97
 | Excel 2000
 | Excel XP (2002)
 | Excel 2003
 | Excel 2007
 | Excel 2010 (32-bit or 64-bit)
 | Excel 2013 (32-bit or 64-bit)

See also Deployment in the User Guide.

XLL+ 7.0 for Visual Studio 2010

Developers

The table below lists the requirements for developers using XLL+ 7.0 with Microsoft Visual Studio 2010. Note that Microsoft Visual Studio 2010 Express Editions are not supported and that Excel as part of Office 365 is not supported.

Operating system | Windows XP
 | Windows Vista (32-bit or 64-bit)
 | Windows 7 (32-bit or 64-bit)
 | Windows 8.1 (32-bit or 64-bit)
Microsoft Visual Studio | Microsoft Visual Studio 2010 - Professional edition
 | Microsoft Visual Studio 2010 - Premium edition
 | Microsoft Visual Studio 2010 - Ultimate edition
Microsoft Help Compiler | Microsoft HTML Help Studio 1.4
Microsoft Excel | Excel 95
 | Excel 97
 | Excel 2000
 | Excel XP (2002)
 | Excel 2003
 | Excel 2007
 | Excel 2010 (32-bit or 64-bit)
 | Excel 2013 (32-bit or 64-bit)

Users

The table below lists the requirements for running XLLs built using XLL+ 7.0 for Visual Studio 2010. Note that Excel as part of Office 365 is not supported.

Operating system | Windows XP
 | Windows Vista (32-bit or 64-bit)
 | Windows 7 (32-bit or 64-bit)
 | Windows 8 (32-bit or 64-bit)
Microsoft Excel | Excel 95
 | Excel 97
 | Excel 2000
 | Excel XP (2002)
 | Excel 2003
 | Excel 2007
 | Excel 2010 (32-bit or 64-bit)
 | Excel 2013 (32-bit or 64-bit)

See also Deployment in the User Guide.

XLL+ 7.0 for Visual Studio 2008

Developers

The table below lists the requirements for developers using XLL+ 7.0 with Microsoft Visual Studio 2008. Note that Microsoft Visual Studio 2008 Express Editions are not supported and that Excel as part of Office 365 is not supported.

Operating system | Windows 2000 Professional
 | Windows XP
 | Windows Vista (32-bit or 64-bit)
 | Windows 7 (32-bit or 64-bit)
Microsoft Visual Studio | Microsoft Visual Studio 2008
Microsoft Help Compiler | Microsoft HTML Help Studio 1.4
Microsoft Excel | Excel 95
 | Excel 97
 | Excel 2000
 | Excel XP (2002)
 | Excel 2003
 | Excel 2007
 | Excel 2010 (32-bit or 64-bit)

Users

The table below lists the requirements for running XLLs built using XLL+ 7.0 for Visual Studio 2008. Note that Excel as part of Office 365 is not supported.

Operating system | Windows 2000 Professional
 | Windows XP
 | Windows Vista (32-bit or 64-bit)
 | Windows 7 (32-bit or 64-bit)
Microsoft Excel | Excel 95
 | Excel 97
 | Excel 2000
 | Excel XP (2002)
 | Excel 2003
 | Excel 2007
 | Excel 2010 (32-bit or 64-bit)

See also Deployment in the User Guide.

XLL+ 7.0 for Visual Studio 2005

Developers

The table below lists the requirements for developers using XLL+ 7.0 with Microsoft Visual Studio 2005. Note that Microsoft Visual Studio 2005 Express Edition is not supported and that Excel as part of Office 365 is not supported.

Operating system | Windows 2000 Professional
 | Windows XP
 | Windows Vista (32-bit or 64-bit)
 | Windows 7 (32-bit or 64-bit)
Microsoft Visual Studio | Microsoft Visual Studio 2005 SP1 or above
Microsoft Help Compiler | Microsoft HTML Help Studio 1.4
Microsoft Excel | Excel 95
 | Excel 97
 | Excel 2000
 | Excel XP (2002)
 | Excel 2003
 | Excel 2007
 | Excel 2010 (32-bit or 64-bit)
 | Excel 2013 (32-bit or 64-bit)

Please note that XLL+ 7.0 for Visual Studio 2005 will work with Visual Studio 2005 SP0, but add-ins built using the MFC libraries, the /MD libraries or the Common Language Runtime libraries will not work properly, and will not load into Excel.

Please also see the technical note .NET requirements, to be sure that your .NET add-ins load into Excel properly.

Users

The table below lists the requirements for running XLLs built using XLL+ 7.0 for Visual Studio 2005. Note that Excel as part of Office 365 is not supported.

Operating system | Windows 2000 Professional
 | Windows XP
 | Windows Vista (32-bit or 64-bit)
 | Windows 7 (32-bit or 64-bit)
Microsoft Excel | Excel 95
 | Excel 97
 | Excel 2000
 | Excel XP (2002)
 | Excel 2003
 | Excel 2007
 | Excel 2010 (32-bit or 64-bit)
 | Excel 2013 (32-bit or 64-bit)

See also Deployment in the User Guide.


ResHelp.cpp

ResHelp.cpp can be found in the Docs\Source sub-directory of the XLL+ installation directory.

This file contains the source code of the XLL+ run-time libraries which deals with loading string resources from resource files, when the resource file contains multiple languages. Much of the code is to replace the MS implementation of LoadString(), which appears to have been broken in Win2k and has not yet been repaired.


System limits

Functions

Description | Excel 2003 | Excel 2007
Maximum length of a function name | 249 | 249
Maximum arguments to an add-in function | 30 | 255
Maximum length of an argument name | 255 | 255
Maximum number of characters in an add-in function’s argument list (including commas | 245 | Unlimited
Maximum number of argument descriptions for an add-in function | 20 | 245

Argument names

Although it is possible to have an argument with 255 characters in its name, it is not a good idea. In addition, other constraints apply under Excel 2003 and below.

  1. There is only room to display 14 characters in the Excel 95 function wizard.
  2. There is a limit of 245 characters for the entire list of up to 30 arguments (including commas). It is therefore a good idea to limit yourself to an average of 7 characters per name if you can.

Argument descriptions

Since a function under Excel 2003 and below can take at most 30 arguments, and since only 20 of these arguments can have descriptions, the following rules are applied by the XLL Plus library.

Arguments | Action
20 or less | All arguments have descriptions
21 to 30 | Descriptions are available for arguments 1 to 19. All descriptions for arguments from argument 20 onwards contain the text "No description available".

XLL Plus Function Wizard

The Function Wizard issues warnings when any of the limits above are violated.

Arrays

Array sizes are ultimately limited by the size of Excel worksheets, but other limits also apply.

Description | Excel 2003 | Excel 2007
Maximum columns in a range | 256 | 16384
Maximum rows in a range (Excel 95) | 16384 |
Maximum rows in a range (Excel 97 and above) | 65536 | 1048576
Maximum number of cells passed in a CXlOper from Excel to an add-in function (Excel 95) | 5458 |
Maximum number of rows passed in a COper from Excel to an add-in function (Excel 95) | 5458 / number of columns |
Maximum number of cells passed in a COper from Excel to an add-in function (Excel 97 and above) | 16777216 | 17179869184
Maximum number of rows passed in a COper from Excel to an add-in function (Excel 97 and above) | 65535 More... | 1048575

See also Comparison of CXlOper and CXlArray.

Strings

Strings under Excel 2003 and below can contain at most 255 8-bit characters.

Strings under Excel 2007 and above can contain at most 32767 16-bit characters.


Visual Studio .NET and Visual Studio 2005

Libraries

There have been significant changes to the internal structure of Microsoft's C/C++ runtime libraries, especially with regard to the STL implementation.

We therefore supply four different builds of the XLL+ run-time libraries, for use with each environment.

  • Users of Visual Studio 6 or Visual C++ 6 should link to the libraries in the Lib sub-directory.
  • Users of Visual Studio .NET 2002 should link to the libraries in the Lib7 sub-directory.
  • Users of Visual Studio .NET 2003 should link to the libraries in the Lib71 sub-directory.
  • Users of Visual Studio 2005 should link to the libraries in the Lib8 sub-directory.

The AppWizard automatically sets the correct LIB path for new projects. If you need to port a project made in Visual Studio 6 to VS.NET or VS 2005, or a project made in VS .NET to VS 2005, then read the note on Porting below.

Porting projects built in an older version of Visual Studio

If you open a Visual Studio project file or workspace file in a newer version of Visual Studio, then it will be converted to the new version's format.

You will also need to make one further change to the Project properties: you should set the linker path to include either the Lib7 directory (for Visual Studio.NET 2002), the Lib71 directory (for Visual Studio.NET 2003) or the Lib8 directory (for Visual Studio.NET 2005). instead of the corresponding Lib directory.

In the picture below, note that the Configuration field has been set to "All Configurations" so that the change can be made in one step.

Wizards

The appearance of the XLL+ user interface is slightly different between VS6 and othe Visual Studio versions.

The Visual Studio .NET and 2005 implementation offers access to the XLL+ Function Wizard via two items on the Tools menu, rather than through a toolbar. If you want to add a toolbar, just use the Tools - Customize command to create your own.

The AppWizard has only one page in VS.NET & 2005 (it had two in VS6). The default setting for the VersionInfo function is now off (it was on by default in VS6).


XLL+ User Guide - Old Topics

Some topics have been retired from the User Guide, because the features they support or the techniques that they use are now deprecated. For the sake of developers who continue to make use of these features, these topics are retained here.


Real-time data overview

If a function takes a very long time to complete, Excel is locked and unusable in the meantime. It is sometimes useful to run the function asynchronously, in a separate thread, so that Excel remains available while the function completes. While the calculation is continuing, the target cell will display "#WAIT!", and when it is complete, the result will automatically be updated to display the result.

This chapter shows how to implement an asynchronous model, using the AvgOpt sample as a starting point, and converting it into an asynchronous calculation.

Before you begin using or building the sample code, make sure that your development platform and target environment will support the model: check the requirements in Real-time data requirements.

Next: Real-time data requirements >>


Real-time data requirements

Requirements

Excel version
This model uses Excel's RTD mechanism, which is only available in Excel XP upwards. It cannot be used with Excel 97 or Excel 2000.
Operating system
The model requires Windows 2000 or above, since Windows 98 does not support multi-threading.
XLL+
The sample code requires XLL+ 4.3.1 or above.

Deliverables

The deliverables required for the projects discussed here include the following files and folders:

File | Description
Samples/AvgOptAsync | Source code for the asynchronous Excel add-in discussed below.
Samples/XllRtdLink | Source code for the RTD server discussed below.
Samples/Bin/XllRtdLink.dll | Compiled RTD server module.
Include/ThreadManager.h | Simple mechanism for managing a thread pool.
Include/XllRtdLink_common.h | Functions used by the sample XLL to communicate with the RTD server.
Docs/XllRtdLink.pdf | This document.

Installation

The model uses a COM module (XllRtdLink.dll) to support Excel's RTD mechanism. You should register the RTD server module XllRtdLink.dll, in one of the following ways:

  1. Use REGSVR32 at the command line, e.g.

    REGSVR32 "C:\Servers\win32\XllRtdLink.dll"

    Ensure that you register the correct version of the DLL: on a machine with 64-bit Excel, you should register the 64-bit version of the file, which can be found in redist\x64, whereas on a machine with 32-bit Excel, you should register the 32-bit version of the file, which can be found in redist\win32.

  2. Build the project Samples\XllRtdLink\XllRtdLink.dsp (or Samples\XllRtdLink\XllRtdLink.sln if you are using VS.NET 2002, or Samples\XllRtdLink\XllRtdLink71.sln if you are using VS.NET 2003, or Samples\XllRtdLink\XllRtdLink8.sln if you are using VS.NET 2005). Choose either the Debug or the Release MinDependency build.

Next: Flow >>


Flow

The design uses a data cache and a pool of worker threads. There are three main stages to the process, which are discussed below.

Stage 1: Initiation

  1. Excel tries to calculate the value of a cell by calling the add-in function.
  2. The add-in function looks in the cache, to see if the result is available, and it is not. So it passes the calculation to a worker thread.
  3. The add-in function immediately returns a place-holder result, e.g. "#WAIT!".

Stage 2: Calculation

  4. The worker thread completes its calculation, and puts the results into the cache.
  5. The worker thread sends a signal to Excel, informing it that new data is available for the cell containing the add-in function. (This is done by making use of Excel's RTD mechanism.)

Stage 3: Update

  6. Excel calls the add-in function again.
  7. The add-in function looks in the cache and finds the desired result.
  8. The add-in function returns the result to Excel, and the calling cell will now display the result.

Next: ThreadManager class >>


ThreadManager class

The add-in uses an external class, ThreadManager, to handle the pool of worker threads. The code of the class is all contained in the header file ThreadManager.h, and a detailed discussion of its mechanics is beyond the scope of this document.

The only methods used by the add-in are the following public functions:

Function | Description
Init() | Prepares a ThreadManager instance for use. Returns false if initialization fails. Must be called from main thread.
Term() | Terminates a ThreadManager. Stops all worker threads. Must be called from main thread.
StartThread(fn, userData) | Creates a new task, to be run when a thread becomes available. Must be called from main thread.

Next: RTD mechanism >>


RTD mechanism

The add-in uses a very simple implementation of Excel's real-time data (RTD) interface. RTD is a pull-push protocol: Excel periodically enquires of a server whether there is any new data available with regard to a particular topic; the server responds with a list of the data it would like to push into Excel.

Communication between worker thread and RTD

The mechanism used to pass messages from a worker thread and RTD must be thread-safe. The implementation chosen is to use a shared file containing a sequence number. When the worker thread needs to indicate that something has happened, that Excel needs to know about, it does the following:

  1. Locks the appropriate file.
  2. Reads the number contained in it.
  3. Increments the number by one and writes it to the file.
  4. Unlocks the file.

The RTD module is periodically interrogated by Excel, to ask whether there is any new information of interest. The module responds by reading the appropriate shared file and checking the sequence number contained therein. If the number is higher than it was the last time the module looked at it, it informs Excel.

All the code for the communication mechanism is contained in the header file Include\XllRtdLink_common.h.

Granularity

RTD is capable of supporting complex hierarchies of topics. However, the implementation in this sample does not make use of this complexity. The only message it passes to Excel is:

"A function with the name 'AvgOpt' has completed."

Alternatively, we could have chosen to pass the message:

"A function 'AvgOpt', called by a particular cell, has completed."

We have chosen not to specify which AvgOpt function has completed, and as a result, if there are multiple instances of the function in a spreadsheet, Excel will refresh all of them. While this is not optimal if there are many cells depending on the results of these calculations, it was considered worthwhile because:

  1. The use model in the spreadsheet is extremely simple. The asynchronous functions can be called in a way that is only very slightly different from calling their synchronous equivalents.
  2. The code for the implementation in the add-in function is much simpler.
  3. The performance cost of repeating the calculations for cells which have already completed is tiny: the add-in function just looks up the results in the cache.

Next: AvgOptData class >>


AvgOptData class

The first step in converting the project from synchronous to asynchronous operation is to implement a class which contains all the inputs and outputs of a single calculation. It will be used in several ways:

  1. The add-in function creates it and populates it with all the input values passed by Excel.
  2. It is passed to a worker thread, which uses all its inputs for the calculation.
  3. The worker thread populates the outputs when the calculation is complete.
  4. It is placed in the cache, where it can be compared with the inputs of the add-in function in future calls.

Data members

The class contains three sets of data:

  1. Input values, as passed from Excel.
  2. Output values, as calculated by the worker thread.
  3. A state flag, which indicates whether the output values are valid.

The signature of the existing calculation function is:

CopyC++
extern "C"
int eval_avg_opt
(
    int     put,
    double  spot,
    double  sigma,
    double  loan,
    double  discount,
    double  div_yield,
    long    value_date,
    long    maturity,
    long    avg_in_count,
    long    *avg_in_dates,
    long    avg_out_count,
    long    *avg_out_dates,
    long    iters,
    double* result,
    char*   err_buf,
    int     err_buf_size
);

The data members of the AvgOptData class will therefore be as follows:

CopyC++
class AvgOptData
{
    // Data members
public:
    // Inputs
    int                 put;
    double              spot;
    double              sigma;
    double              loan;
    double              discount;
    double              div_yield;
    long                value_date;
    long                maturity;
    std::vector<long>   avg_in_dates;
    std::vector<long>   avg_out_dates;
    long                iters;

    // Outputs
    double              result;
    char                err_buf[512];
    int                 rc;
    bool                done;
    ...
};

Methods

The class contains three functions and an overloaded operator:

CopyC++
class AvgOptData
{
    ...
    // Constructor
    AvgOptData(int put_, double spot_, double sigma_, double loan_,
        double discount_, double div_yield_, long value_date_,
        long maturity_, const std::vector<long>& avg_in_dates_,
        const std::vector<long>& avg_out_dates_, long iters_)
    {
        // Initialize output
        ...
        // Copy inputs
        ...
    }

    // Evaluation
    void Evaluate()
    {
        rc = eval_avg_opt(put ? 1 : 0, spot, sigma, loan, discount,
            div_yield, value_date, maturity, avg_in_dates.size(),
            avg_in_dates.size() ? &avg_in_dates[0] : 0,
            avg_out_dates.size(),
            avg_out_dates.size() ? &avg_out_dates[0] : 0,
            iters, &result, err_buf, sizeof(err_buf));
        done = true;
    }

    // Comparison
    static int Compare(const AvgOptData& x, const AvgOptData& y)
    {
        // Compare only inputs
        ...
    }
    bool operator<(const AvgOptData& c) const
    {
        return Compare(*this, c) < 0;
    }
};

The methods are used as follows:

  1. The constructor is called by the add-in function, to populate the object with the inputs passed from Excel.
  2. The evaluation function is called by a worker thread.
  3. The comparison function and operator are used by the cache, to look up an AvgOptData object based on the value of its inputs.

Multithreaded access

The AvgOptData object is used by the main thread and by a worker thread. It is therefore important to make sure that there are no thread conflicts when writing and reading the object.

There are 4 points at which the object is accessed:

Creation
This includes: construction, population of inputs and insertion into the cache. The main thread is responsible for this. The object is then passed to the ThreadManager.
Calculation
The worker thread is responsible for calculation. This includes: reading the inputs, passing them to the calculation function eval_avg_opt(), populating the results and finally, setting the done flag.
Reading results
The main thread may at any time after construction attempt to read the results. First, the done flag is inspected. If it is false, then no further reading takes place. If it is true, then we know that the worker thread has finished using the object and that the outputs are fully populated. The main thread can therefore safely read the outputs and pass them back to Excel.
Closedown
During closedown, the main thread deletes all the AvgOptData objects from the cache. However it does this only after the ThreadManager has terminated all the worker threads; thus contention is not a problem.

Next: AvgOptDataCache class >>


AvgOptDataCache class

The AvgOptDataCache object contains all the AvgOptData objects for the add-in instance. This includes (i) new objects, waiting to be calculated, (ii) objects currently being calculated by a worker thread and (iii) objects whose calculation are complete.

The cache uses an STL std::set to map the objects against their inputs. Thus when the add-in function is called it can build a new AvgOptData object and compare it with those already in the cache; if it is matched, then the existing object can be used, and there is no need to create a new one.

Only three methods are provided by the class:

Function | Description
Find(AvgOptData* t) | If an object in the cache has the same inputs as *t then a pointer to the existing object is returned. If no match is found, then zero is returned.
Add(AvgOptData* t) | The object is added to the cache.
Clear() | All objects are removed from the cache.
CopyC++
class AvgOptDataCache
{
protected:
    typedef std::set<AvgOptData*, AvgOptData_less> set_t;
    set_t m_set;
public:
    AvgOptData* Find(AvgOptData* t)
    {
        set_t::iterator itF = m_set.find(t);
        return itF == m_set.end() ? 0 : *itF;
    }
    void Add(AvgOptData* t)
    {
        ASSERT(t != 0);
        m_set.insert(t);
    }
    void Clear()
    {
        for (set_t::iterator it = m_set.begin(); it != m_set.end(); it++)
            delete *it;
        m_set.clear();
    }
};

AvgOptData_less

This helper class acts as the predicate for a set containing the AvgOptData pointers. A set normally compares two contained objects using "x < y"; however since our set contains pointers, we need to compare "*x < *y". The AvgOptData_less class implements this behavior.

Next: Converting a project to RTD >>


Converting a project to RTD

The next few topics discuss how to convert a synchronous add-in to asynchronous operation.

The AvgOpt sample is used as an example for conversion. The add-in function AvgOptValue(...) provides an ideal example of a very slow function.

The main steps for converting the project are listed below:

Remove argument cache | The AvgOpt sample uses an argument cache to preserve the results of all calls to the function. Remove this mechanism, which will be replaced by our specialized cache.
Insert AvgOptDataCache | Insert our specialized cache, AvgOptDataCache, and handle initialization and termination.
Add a worker thread | Add an instance of the ThreadManager class and write a worker thread function.
Modify add-in function | Change the add-in function AvgOptValue to use a worker thread.
Modify "Clear cache" command | Change the add-in function AvgOptClearCache.

Next: Step 1 - Remove argument cache >>


Step 1 - Remove argument cache

Remove argument cache

The built-in argument cache (generated by the XLL+ AppWizard) is no longer required and should be removed.

In AvgOpt.h, remove the two lines shaded below.

CopyC++
class CAvgOptApp : public CXllApp
{
public:
    CAvgOptApp();

// Names
public:
    static LPCSTR m_pszDefName;

// Data
    CXlOperCache m_cache;
    CString m_strCacheFile;

// Menu
    CXlMenu m_menu;

    ...
};

In AvgOpt.cpp, remove the lines shaded below.

CopyC++
BOOL CAvgOptApp::OnXllOpenEx()
{
    // Calculate the full path of the cache data file.
    // This is the same as the add-in, with the extension "dat".
    m_strCacheFile = CXllApp::GetXllName();
    m_strCacheFile = m_strCacheFile.Left(m_strCacheFile.GetLength() - 3) + "dat";

    // Restore cache, ignoring failure
    m_cache.Restore(m_strCacheFile);

    // Set up menu
    m_menu.SetTexts("&AvgOpt");
    m_menu.AddItem("&Clear cache", "AvgOptClearCache");
    m_menu.Create();

    return TRUE;
}

void CAvgOptApp::OnXllClose()
{
    // Save cache
    m_cache.Save(m_strCacheFile);

    // Delete menu
    m_menu.Destroy();
}

Use the XLL+ Function Wizard to switch off the argument cache for the AvgOptValue function in AvgOpt.cpp:

This will remove all of the generated code within the add-in function that supports the argument cache.

Next: Step 2 - Insert AvgOptDataCache >>


Step 2 - Insert AvgOptDataCache

Insert AvgOptDataCache

Add an instance of AvgOptDataCache to the class definition in AvgOpt.h, and include the file that contains the class definition, data_avgopt.h:

CopyC++
...
#include <xlserialize.h>
#include <xlmenu.h>
#include "data_avgopt.h"
...

class CAvgOptApp : public CXllApp
{
public:
    CAvgOptApp();

// Names
public:
    static LPCSTR m_pszDefName;

// Data
    AvgOptDataCache m_cacheAvgOpt;

// Operations
    void ClearCache();

// Menu
    CXlMenu m_menu;

    ...
};

This declaration creates a single instance of the specialized cache class. We will be adding code to the add-in function later to "wire it up".

Next: Step 3 - Add a worker thread >>


Step 3 - Add a worker thread

Add a worker thread

In AvgOpt.h, add an instance of ThreadManager.:

CopyC++
...
#include <xlserialize.h>
#include <xlmenu.h>
#include "ThreadManager.h"
#include "data_avgopt.h"
...

class CAvgOptApp : public CXllApp
{
public:
    CAvgOptApp();

// Names
public:
    static LPCSTR m_pszDefName;

// Data
    AvgOptDataCache m_cacheAvgOpt;

// Operations
    void ClearCache();

// Multiple thread manager
    psl::ThreadManager m_threadManager;
    static size_t m_maxThreads;

// Menu
    CXlMenu m_menu;

...
};

In AvgOpt.cpp, amend the constructor, so that the ThreadManager instance is initialized.

CopyC++
/////////////////////////////////////////////////////////////////////////////
// CAvgOptApp construction

size_t CAvgOptApp::m_maxThreads = 4;

CAvgOptApp::CAvgOptApp()
: m_threadManager(m_maxThreads)
{
    // TODO: add construction code here,
    // Place all significant initialization in InitInstance
}

Amend the OnXllOpenEx() and OnXllCose() event handlers, so that the ThreadManager is initialized and terminated.

CopyC++
BOOL CAvgOptApp::OnXllOpenEx()
{
    // Set up menu
    m_menu.SetTexts("&AvgOpt");
    m_menu.AddItem("&Clear cache", "AvgOptClearCache");
    m_menu.Create();

    // Start the thread manager
    if (!m_threadManager.Init())
    {
        XlMessageBox("Failed to initialize thread manager",
              XlMessageBoxTypeExclamation);
        return FALSE;
    }

    return TRUE;
}

void CAvgOptApp::OnXllClose()
{
    // Stop all threads
    m_threadManager.Term();

    // Delete menu
    m_menu.Destroy();
}

Worker thread

Add a new function to be called by worker threads:

CopyC++
void __stdcall AvgOptValue_threadfn(void* pvData)
{
    AvgOptData* args = (AvgOptData*)pvData;

    args->Evaluate();
    args->done = true;
    psl::XllRtdSharedData::IncrementChannelSeqNum("AvgOpt");
}

The following points are of interest in the worker thread function:

  • The __stdcall calling convention is required for the worker thread.
  • The argument to the function is the pointer originally passed to ThreadManager:: StartThread().
  • The worker thread evaluates the data object, and thereby (eventually) populates the outputs of the data object.
  • The worker thread sets the done flag to true, indicating to the add-in function that the outputs are now valid.
  • The worker thread uses the XllRtdSharedData interface to increment the sequence number of the named channel "AvgOpt", and thereby informs the RTD module that new data is available for this function.

Next, we will modify the add-in function so that it passes all the work of calculation to a worker thread.

Next: Step 4 - Modify add-in function >>


Step 4 - Modify add-in function

Modify add-in function using function wizard

The first change we need to make to the add-in function is to add a new argument. This will contain the sequence number discussed in Communication between worker thread and RTD. When a calculation completes, the sequence number changes and, since it is an argument to the function AvgOptValue, the function is refreshed by Excel.

Use the XLL+ Function Wizard to add a new argument to AvgOptValue:

The new argument is of type Long and is named RtdSeqNum.

Existing add-in function's logic

The next step is to change the add-in function's body, so that calls are passed to a worker thread, instead of being immediately calculated.

The original function looked as shown below:

CopyC++
extern "C" __declspec( dllexport )
LPXLOPER AvgOptValue(BOOL Put, double Spot, double Vol, double
    Loan, double Discount, double DivYield, long ValueDate, long
    Maturity, const COper* AvgInDates, const COper* AvgOutDates,
    long Iterations)
{
    ...
//}}XLP_SRC

    // Call the library function
    double dResult = 0.0;
    char achErr[256];
    int calc_ok = eval_avg_opt(Put ? 1 : 0, Spot, Vol, Loan, Discount, DivYield,
        ValueDate, Maturity, vecAvgInDates.size(), &vecAvgInDates[0],
        vecAvgOutDates.size(), &vecAvgOutDates[0], Iterations,
        &dResult, achErr, sizeof(achErr));

    // Put the result or an error string in xloResult
    if (calc_ok)
        xloResult = dResult;
    else
        xloResult.Format("#ERROR: %s", achErr);

    return xloResult.Ret();
}

New logic for add-in function

The new logic should work as follows:

  1. Construct a new AvgOptData object, populated with the function's inputs.
  2. Look up the inputs in the cache.
  3. If the inputs are matched, extract a result from the cached data object. If the object is marked as done=true, then the outputs can be used. If the calculation is not complete, then the value "#WAIT!" is returned.
  4. If the inputs are not matched, add the data object to the cache, send the calculation to a worker thread, and return "#WAIT!".

Modify add-in function's code

This logic is implemented as shown below:

CopyC++
extern "C" __declspec( dllexport )
LPXLOPER AvgOptValue(BOOL Put, double Spot, double Vol, double
    Loan, double Discount, double DivYield, long ValueDate, long
    Maturity, const COper* AvgInDates, const COper* AvgOutDates,
    long Iterations, long RtdSeqNum)
{
    ...
//}}XLP_SRC

    AvgOptData* argsIn = new AvgOptData(
        Put, Spot, Vol, Loan, Discount, DivYield,
        ValueDate, Maturity, vecAvgInDates,
        vecAvgOutDates, Iterations);

    AvgOptData* argsOld = ::XllGetTypedApp()->m_cacheAvgOpt.Find(argsIn);
    if (argsOld != 0)
    {
        delete argsIn;
        if (argsOld->done)
            xloResult = argsOld->result;
        else
            xloResult = "#WAIT!";
        return xloResult.Ret();
    }

    XllGetTypedApp()->m_cacheAvgOpt.Add(argsIn);

    if (!::XllGetTypedApp()->m_threadManager.StartThread(
            AvgOptValue_threadfn, argsIn))
        return CXlOper::RetError(xlerrNull);
    xloResult = "#WAIT!";

    return xloResult.Ret();
}

Note that the old call to eval_avg_opt() is replaced with a call to ThreadManager::StartThread(), passing the address of our worker thread function and the AvgOptData object that it will use.

Next: Step 5 - Modify "Clear cache" command >>


Step 5 - Modify "Clear cache" command

Modify "Clear cache" command

The final change to the project is to change the menu function AvgOptClearCache(). In AvgOpt.cpp, add a new method:

CopyC++
void CAvgOptApp::ClearCache()
{
    m_threadManager.Term();
    m_cacheAvgOpt.Clear();
    m_threadManager.Init();
}

As you can see, it is necessary to stop and restart the thread manager, and thereby kill any worker threads that are still running, to ensure that there is no contention between threads for the data objects in the cache.

Amend the menu function to call the new method.

CopyC++
extern "C" __declspec( dllexport )
BOOL AvgOptClearCache()
{
    XLL_FIX_STATE;
//}}XLP_SRC

    CString strMsg;
    strMsg = "This command will clear all cached calculations from memory.\n\n"
        "Do you wish to continue?";
    if (CXllApp::XlMessageBox(strMsg, XlMessageBoxTypeQuestion) != 0)
    {
        ::XllGetTypedApp()->ClearCache();
    }
    return 0;
}

This step completes the changes required to make the add-in function AvgOptValue() run asynchronously.

Next: Using the function in a spreadsheet >>


Using the function in a spreadsheet

RTD update

In order to use the function in a spreadsheet, you first need to add a cell that will be updated by the RTD mechanism. For this we use the built-in Excel function RTD. The function's arguments are summarized below.

Argument | Description
progid | The unique program ID of the RTD server module. In our case this is always XllRtdLink.XllRtdSeqNumServer.
server | The remote machine on which the RTD server is running. We omit this argument, since the server is run locally as an in-process DLL.
topic1, topic2... | A list of strings which uniquely identify the data which has changed. We only use one topic, which should match the channel name used in the worker thread function: i.e. "AvgOpt".

Thus we add a formula as follows:

=RTD("XllRtdLink.XllRtdSeqNumServer",,"AvgOpt")

Every time the sequence number of the channel AvgOpt is changed, the cell will automatically update. You should then use it as an input to the cell containing the formula AvgOptValue, so that the cell will automatically be recalculated.

Using the RTD value

You will remember that we added a new argument to the add-in function AvgOptValue(...), to contain the value of the cell which is updated by RTD. The value itself is ignored by the add-in function. However, Excel does not ignore it: every time it changes, the Excel calls the function again.

If the calculation has completed, then the add-in function will now return the result instead of "#WAIT!".

See the sample spreadsheet Samples\AvgOptAsync\AvgOpt.xls for an example of this technique in use.

Benefits

When you use the sample spreadsheet, you will see some major improvements over the original synchronous model:

Unintrusive
While the calculations are running, you can continue to use Excel, with very little noticeable loss of responsiveness.
Performance improvement
If you are using a computer with multiple processors, you will see a significant improvement in performance when running multiple calculations. This is because the various threads can run on any processor, instead of being tied to the processor which is running Excel's main thread.
Responsive
If you start a long calculation, and then find that one of the inputs must be changed, you don't have to wait for the calculation to end. You can change it right away, and launch the new calculation immediately (or as soon as a thread is available from the thread pool).

Next: Tuning RTD >>


Tuning RTD

The RTD mechanism is a pull-push protocol. You can control the frequency of the pull (i.e. the frequency with which Excel looks for changes in an RTD server), by using the property Application.RTD.ThrottleInterval through VBA.

  1. From Excel, type Alt+F11 to show the VBA editor.
  2. Type Ctrl+G to show the immediate window.
  3. To show the current throttle interval in milliseconds, type:
    CopyVBA
    ?Application.RTD.ThrottleInterval
  4. To change the throttle interval to 1/10 of a second, type:
    CopyVBA
    Application.RTD.ThrottleInterval = 100

Next: Further enhancements >>


Further enhancements

There are many enhancements you may choose to add to the model. Some of the most obvious are discussed below.

Multiple results

If a function returns multiple results, you should have a single add-in function for each distinct result; the functions will vary only in that they will extract different output data members from the data object.

Persistent cache

The cache could be saved to disk whenever the add-in is closed - i.e. during OnXllClose(). One might choose to stream it to a binary file, or more usefully, store it in a database.

When designing the serialization mechanism, it is worth remembering that there may be multiple instances of Excel open, each of them with a separate in-memory cache. Thus, when saving the in-memory cache, it is advisable to perform the following steps as a single atomic operation.

  1. Lock the persistent cache file.
  2. Read the cache file into memory.
  3. Add any records from the in-memory cache built by this add-in.
  4. Save the merged cache to disk.

Multiple caches

If you have multiple functions in a single add-in which you wish to run asynchronously, you should have multiple caches in a single add-in. Each cache should use a different named channel. For example, if the new function BarrierOptValue() was added to the add-in, it would use a new data object class, e.g. BarrierOptData, a new cache class BarrierOptDataCache and an instance of BarrierOptDataCache in the application class CAvgOptApp.

Most important, when the worker thread for the BarrierOptData object completed, it should use a different channel to inform RTD of its completion, e.g.:

CopyC++
void __stdcall BarrierOptValue_threadfn(void* pvData)
{
    BarrierOptData* args = (BarrierOptData*)pvData;

    args->Evaluate();
    args->done = true;
    psl::XllRtdSharedData::IncrementChannelSeqNum("BarrierOpt");
}

In addition, the cell containing the sequence number passed to BarrierOptValue() should contain the appropriate channel name, e.g.:

=RTD("XllRtdLink.XllRtdSeqNumServer",,"BarrierOpt")

This pattern will keep updates of the two functions separate from each other.

Next: COM server module: XllRtdLink >>


COM server module: XllRtdLink

The XllRtdLink module is a very simple implementation of Excel's RTD interface, built using ATL. It's code is based on the Microsoft Visual Basic 6 sample, "How To Create a RealTimeData Server for Excel", which can be found at http://support.microsoft.com/kb/285339/EN-US/.

In the retail vesrion of XLL+, the source code is provided in the directory Samples\XllRtdLink.

Next: Object handles >>


Object handles

Many programmers wish to be able to hold objects in memory and access them from Excel worksheets. A calculation may produce a vast amount of data, including for example:

  • multiple results;
  • arrays that are too large to display in Excel; and
  • diagnostic results.
The developer may wish to represent the entire object in Excel by a "handle" of some kind, and then use "getter" functions to inspect the data contained in the object.

For example, a function MonteCarlo(...) may produce a final value, statistical measures indicating the certainty of the value, a very large series of random numbers used by the calculation, and performance figures that show the cost of the calculation. The entire result set can be placed in an object, and exposed in Excel as a numeric handle to the object.

Thus the main function, MonteCarlo(...) returns a long integer, which is a handle to the result set. Various getter functions, such as MonteCarlo.Value(handle), MonteCarlo.Statistics(handle) and MonteCarlo.RandomSeries(handle, index) can be used to show the interesting results in the worksheet.

CXlHandleStore<T, S> template class

This pattern can be implemented very simply using the CXlHandleStore<T, S> template class. The arguments to the template are as follows:

Argument | Description
class T | The class of the object to be stored
class S | The scoping class, which ensures that the object stored remains alive as long as it is needed, and that it is destroyed when it is no longer needed. The scoping class argument can be omitted, in which case the class scope_ptr<T> will be used.

The CXlHandleStore object provides three methods that can be used to transform objects to handles and vice-versa, and to manage the liftimes of the objects contained in the store.

Method | Description
AddObjectHandle | Convert an object pointer to a handle, and add it to the store.
ObjectFromHandle | Convert a handle passed from Excel to an object pointer.
Clear | Clear all objects from the store.

Using the CXlHandleStore class

There are 5 important steps in implementing a handle store in an add-in.

  1. Create a class which will represent the object. This will usually be either an existing object class or a thin wrapper around an existing object.

  2. Add an instance of the handle store class to the add-in's application object, e.g. CXlHandleStore<MyObject>.

  3. Write an add-in function that creates the object, adds it to the handle store and returns the add-in's handle to Excel. (This function is referred to as the "object creation function".)

  4. Write "getter" add-in functions that take a handle as their first argument, transform the handle to an object pointer, extract data from the object, and return the data to Excel.

  5. Write two macro add-in functions that force a recalculation of any cell that contains an object creation function. These are required for "house-keeping" purposes.

The examples which follow this topic demonstrate each step of the implementation.

CXlHandleStore code

The CXlHandleStore class is very simple. It's full implementation is shown below.

CopyC++
template <class T, class S = scope_ptr<T> >
class CXlHandleStore {
public:
    typedef CXlHandleStore<T, S> this_type;
    typedef T value_type;
    typedef S scope_type;
    typedef long handle_type;
public:
    CXlHandleStore<T, S>() {}
    ~CXlHandleStore<T, S>() {}

    const value_type* ObjectFromHandle(handle_type handle) const {
        coll_type::const_iterator itF = m_coll.find((value_type*)handle);
        return (itF != m_coll.end()) ? itF->first : 0;
    }
    handle_type AddObjectHandle(value_type* value) {
        m_coll[value] = scope_type(value);
        return (handle_type)value;
    }
    void Clear() {
        m_coll.clear();
    }
protected:
    typedef std::map<value_type*, scope_type> coll_type;
    coll_type m_coll;
};

You can observe that the collection m_coll contains a map in which values of type T* are used to index values of type S. In addition each instance of S is constructed from the corresponding T*. Since S is a smart pointer to T, it manages the lifetime of the object pointed to by T*. Thus, when a key is removed from the map, it is automatically released by the desctruction of the smart pointer.

You can also see that a handle is simply a numeric representation of a pointer, and that the handle and the pointer can be transformed into each other by casting.

Next: Object handles using pointers >>


Object handles using pointers

The first example of an add-in that uses object handles can be found in the HandleAPI sample, and all the source code discussed below can be found in the Samples/HandleAPI sub-directory.

The data class

First we need to define the class that will hold the data for our example, MyObj. This is a simple class which holds two numbers X and Y, and the vector results of a calculation that uses them.

CopyC++
class MyObj {
public:
    MyObj(double X, double Y);
    MyObj(double X);
    ~MyObj();
    double X() const { return m_dX; }
    double Y() const { return m_dY; }
    const std::vector<double>& Vec() const { return m_vec; }
protected:
    double m_dX, m_dY;
    std::vector<double> m_vec;
};

You will notice that the object has two constructors (each of which also performs a calculation), and three getter functions, X(), Y() and Vec().

The HandleStore class

We add a line of code to the application class, CHandleAPIApp, in HandleAPI.h, which declares a handle store at application level, containing instances of MyObj:

CopyC++
class CHandleAPIApp : public CXllApp
{
public:
    ...
    CXlHandleStore<MyObj> m_hsMyObj;
    ...
};

Note that the second argument to the template - the scoping class - is omitted. The default value scope_ptr<MyObj> will therefore be used. This is a very simple pointer container class, which will destroy the MyObj instance when the handle is removed from the handle store. In effect, the handle store "owns" each MyObj instance, and has complete control of its lifetime.

Next, we add some wrapper functions which expose the handle store's functionality, to be used by add-in functions.

CopyC++
class CHandleAPIApp : public CXllApp
{
public:
    ...
    long AddObjectHandle(MyObj* obj) {
        return m_hsMyObj.AddObjectHandle(obj);
    }
    const MyObj* ObjectFromHandle(long Handle) const {
        return m_hsMyObj.ObjectFromHandle(Handle);
    }
    ...
};

When an add-in function (specifically, an object creation function) needs to create a MyObj and return its handle, it calls AddObjectHandle() and returns the handle to Excel.

When a getter add-in function needs to translate a handle received from Excel, it calls ObjectFromHandle() and extracts the desired data from the returned MyObj pointer.

Note that ObjectFromHandle() returns a const pointer, because the MyObj instance should generally be read-only in a getter function.

Object creation functions

We add the object creation functions to the project as new add-in functions. The first creation function takes two arguments, X and Y:

CopyC++
IMPLEMENT_XLLFN2(MyObjCreate1, "JBB", "MyObj.Create1", "X,Y",
    "User Defined", "Object creation function", "No description p"
    "rovided\000No description provided\000", "\0\0appscope=1\0",
    1)

extern "C" __declspec( dllexport )
long MyObjCreate1(double X, double Y)
{
    XLL_FIX_STATE;

    MyObj* o = new MyObj(X, Y);return XllGetTypedApp()->AddObjectHandle(o);
}

Note that the function returns a long integer.

Almost all the work of coding is done by the XLL+ Function Wizard; we only have to add the lines shown above in bold. First we create a MyObj instance, passing the add-in function's arguments to the constructor. The constructor performs its calculations and retains the results within the object.

The second line calls the AddObjectHandle() method of the application object, which adds the new object to the handle store, and returns the resulting handle to Excel.

One more thing to notice about this function is that it is exposed in Excel as MyObj.Create1, since dot notation is more natural in Excel than using an underscore.

The second object creation function is very similar, and takes only one argument (X) for the calculation of MyObj:

CopyC++
IMPLEMENT_XLLFN2(MyObjCreate2, "JB", "MyObj.Create2", "X",
    "User Defined", "Object creation function", "No description p"
    "rovided\000", "\0appscope=1\0", 1)

extern "C" __declspec( dllexport )
long MyObjCreate2(double X)
{
    XLL_FIX_STATE;

    MyObj* o = new MyObj(X);
    return XllGetTypedApp()->AddObjectHandle(o);
}

Getter functions

Now we add the getter functions which extract data from an object and return it to Excel. Again, note the dot notation used for the function name in Excel.

CopyC++
IMPLEMENT_XLLFN2(MyObj_X, "RJ", "MyObj.X", "Handle", "User Define"
    "d", "No description provided", "No description provided\000"
    , "\0appscope=1\0", 1)

extern "C" __declspec( dllexport )
LPXLOPER MyObj_X(long Handle)
{
    XLL_FIX_STATE;
    CXlOper xloResult;

    const MyObj* obj = XllGetTypedApp()->ObjectFromHandle(Handle);if (obj != 0)xloResult = obj->X();elsexloResult = xlerrRef;
    return xloResult.Ret();
}

Let us examine the interesting code (shown in bold above). First we pass the Handle argument to the application object, to translate it to an object pointer. If the translation fails, because the handle is not valid, then ObjectFromHandle() returns a null pointer and the add-in function returns #REF! to Excel.

If the translation succeeds, then the add-in function extracts the value of X and returns that to Excel.

Other getter functions follow an identical pattern. For example, to return the vector of data contained in a MyObj object:

CopyC++
IMPLEMENT_XLLFN2(MyObj_Vec, "RJ", "MyObj.Vec", "Handle",
    "User Defined", "No description provided", "No description pr"
    "ovided\000", "\0appscope=1\0", 1)

extern "C" __declspec( dllexport )
LPXLOPER MyObj_Vec(long Handle)
{
    XLL_FIX_STATE;
    CXlOper xloResult;
//}}XLP_SRC

    const MyObj* obj = XllGetTypedApp()->ObjectFromHandle(Handle);
    if (obj != 0)
        xloResult = obj->Vec();
    else
        xloResult = xlerrRef;
    return xloResult.Ret();
}

House-keeping

Readers may already have asked themselves two questions about this implementation:

  1. What about persistence - what happens to the object when the workbook containing it is closed, and what does the handle mean when the workbook is opened again?

  2. What about garbage collection - how do we release the memory used by MyObj instances that are no longer required?

Both questions are addressed by making use of a utility class, CXlFormulaRefresh. This class contains methods for forcing a recalculation of any cell that contains an object creation function. We use the class on two occasions.

Persistence

Firstly, whenever the add-in is closed (i.e. when Excel is shut down), all the MyObj instances are thrown away. So when a workbook containing handles is reopened, they are invalid, since they refer to the memory occupied by objects which no longer exist. To ensure that all handles in a newly opened workbook are valid, we must ensure that they are all recalculated - as if the user selected the cell and then pressed F2 then Enter.

We need to add a method to the application class to force this recalculation. The application class method is declared inline as follows:

CopyC++
class CHandleAPIApp : public CXllApp
{
public:
    ...
    static const char* mc_apszMyObjCreationFns[];
    ...
    void RefreshWorkbook(const char* pszWorkbookName) {
        CXlFormulaRefresh refr(mc_apszMyObjCreationFns);
        refr.RefreshWorkbook(pszWorkbookName);
    }
    ...
};

The static array mc_apszMyObjCreationFns contains a null-terminated list of the names of each of our object creation functions, as they appear in Excel:

CopyC++
const char* CHandleAPIApp::mc_apszMyObjCreationFns[] = {
    "MyObj.Create1",
    "MyObj.Create2",
    0
};

The RefreshWorkbook method creates a CXlFormulaRefresh object and loads it up with a list of the names of our object creation functions. It then runs the CXlFormulaRefresh::RefreshWorkbook() method, which searches through the named workbook and finds each cell that has a formula which contains a call to either of the functions. For every cell found it forces a recalculation.

Finally, we need to make sure that the RefreshWorkbook() method is called for every workbook as it is opened. We do this by writing an add-in function to call the method, and by registering the add-in function as an event handler for the WorkbookOpen event.

The add-in function is a simple shell, which has the signature required for a WorkbookOpen event handler (see CXllApp::SetComEventHandler() for details).

CopyC++
IMPLEMENT_XLLFN2(HandleAPI_WorkbookOpen, "RC", "HandleAPI_WorkbookOpen"
    , "WorkbookName", "User Defined", "No description provided",
    "No description provided\000", "\0appscope=1\0", 2)

extern "C" __declspec( dllexport )
LPXLOPER HandleAPI_WorkbookOpen(const char* WorkbookName)
{
    XLL_FIX_STATE;
    CXlOper xloResult;

    // Update all handles in this workbook
    XllGetTypedApp()->RefreshWorkbook(WorkbookName);

    // Return value is ignored
    return xloResult.Ret();
}

To register the function as an event handler, we add a couple of lines to the application class's OnXllOpenEx() method:

CopyC++
BOOL CHandleAPIApp::OnXllOpenEx()
{
    ...

    SetSinkEvents(TRUE);SetComEventHandler(EVT_WORKBOOKOPEN, "HandleAPI_WorkbookOpen");

    return TRUE;
}

The first line switches on event handling for this XLL, and the second registers the add-in function HandleAPI_WorkbookOpen as the event handler for WorkbookOpen events.

Garbage collection

From time to time we may wish to recover the memory used by MyObj instances that are no longer of interest to any getter function. We need to add the required functions:

  1. a method in the application object;
  2. a macro add-in function which calls the application object method; and
  3. a menu item which allows the user to call the macro add-in function.

The first method is declared inline in the application class definition:

CopyC++
class CHandleAPIApp : public CXllApp
{
public:
    ...
    void RefreshAllWorkbooks() {
        // Clear all existing objects from handle store
        m_hsMyObj.Clear();

        // Recreate all handles
        CXlFormulaRefresh refr(mc_apszMyObjCreationFns);
        refr.RefreshAllWorkbooks();
    }
    ...
};

First, the method clears the handle store, removing all handles and deleting all the corresponding objects. Second, the method uses an instance of CXlFormulaRefresh to recalculate every object creation function in all open workbooks. This has the effect of removing all handles that are no longer used, and creating new handles for all objects that are in use.

(Note: there is a performance cost to this approach, since all objects are completely recreated each time garbage is collected. The example following this one demonstrates a technique for avoiding this cost.)

The add-in function is a simple wrapper:

CopyC++
IMPLEMENT_XLLFN2(HandleAPI_RefreshAll, "A", "HandleAPI_RefreshAll"
    "", "", "User Defined", "Refresh all object handles, and"
    " collect garbage", "", "appscope=1\0", 2)

extern "C" __declspec( dllexport )
BOOL HandleAPI_RefreshAll()
{
    XLL_FIX_STATE;

    XllGetTypedApp()->RefreshAllWorkbooks();
    return 0;
}

The add-in function is plugged into a menu by the application class's OnXllOpenEx method:

CopyC++
BOOL CHandleAPIApp::OnXllOpenEx()
{
    // Set up menu
    m_menu.SetTexts("H&andles");
    m_menu.AddItem("&Refresh", "HandleAPI_RefreshAll");
    m_menu.Create();

    ...

    return TRUE;
}

Summary

Implementing the object handle technique in this add-in required the following steps:

  1. Instantiate a handle store of type CXlHandleStore<MyObj> as a member of the application class CHandleAPIApp, and add two wrapper functions to expose it's methods.

  2. Write an add-in function for each method that creates a MyObj data set. The add-in function should call AddObjectHandle() in order to add the object to the store, and return the handle to Excel.

  3. Write getter add-in functions for each method which will extract data from MyObj. A getter function takes an object handle as one of its arguments. Each getter function should call ObjectFromHandle() to transform the handle to an object pointer, and then return data extracted from the object.

  4. Write an add-in function that will force a recalculation of any cell in a particular workbook that contains an object creation function. Register the add-in function as a WorkbookOpen event handler.

  5. Write an add-in function that will clear the handle store and then recalculate any cell in any workbook that contains an object creation function. Make the function available from a menu.

It is worth noting that the implementation itself is considerably shorter than this discussion of it.

Next: Object handles using references and cached data >>


Object handles using references and cached data

Our second example of an add-in that uses object handles is the HandleAPICached sample, and all the source code discussed below can be found in the Samples/HandleAPICached sub-directory.

The sample is a variation on the previous sample, HandleAPI.

The data class

MyObj2, The class that will hold the data for our example, based on the previous class MyObj. It has two differences:

  1. It contains a reference count m_refCount, and supports the AddRef()/Release() paradigm familiar to COM programmers.
  2. For simplicity, it has only one public constructor.

CopyC++
class MyObj2 {
protected:
    MyObj2() : m_refCount(0) {}
public:
    MyObj2(double X, double Y) : m_refCount(0) { set(X, Y); }
    ~MyObj2();

    long AddRef() { return ++m_refCount; }
    void Release() {
        if (--m_refCount == 0)
            delete this;
    }

    double X() const;
    double Y() const;
    const std::vector<double>& Vec() const;
protected:
    long m_refCount;
    double m_dX, m_dY;
    std::vector<double> m_vec;
    ...
};

The MyObj2 class can therefore be used with a reference template, so that ownership is shared between owners, and the object is only destroyed when all references to the object are released.

Smart reference class

The MyObj2 class can be stored in a reference counting smart pointer, ref_ptr<T>.

CopyC++
template<class T>
class ref_ptr {
public:
    ref_ptr<T>() : p_(0) {}
    ~ref_ptr<T>() { set(0); }

    ref_ptr<T>(T* t) : p_(0) { set(t); }
    ref_ptr<T>(const ref_ptr<T>& ptr) : p_(0) { set(ptr.p()); }
    const ref_ptr<T>& operator=(const ref_ptr<T>& ptr) {
        set(ptr.p());
        return *this;
    }
    const ref_ptr<T>& operator=(T* t) {
        set(t);
        return *this;
    }

    void set(T* t) {
        if (p_ != t) {
            if (p_) p_->Release();
            if (t) t->AddRef();
            p_ = t;
        }
    }
    T* p() const { return p_; }

    operator T*() const { return p(); }
protected:
    T* p_;
};

The HandleStore class

We add a line of code to the application class, CHandleAPIApp, in HandleAPI.h, which declares a handle store at application level, containing instances of MyObj2. This is slightly different from the store used in the previous example, in that the smart pointer class is explicitly defined.

CopyC++
class CHandleAPICachedApp : public CXllApp
{
public:
    ...
    CXlHandleStore<MyObj2, ref_ptr<MyObj2> > m_hsMyObj;
    ...
};

The object cache

The application class also contains a cache of MyObj2 references. A MyObj2 instance that is referenced by the cache will not be destroyed by garbage collection, since it's reference count will remain greater than 0.

CopyC++
class CHandleAPICachedApp : public CXllApp
{
public:
    ...
    typedef std::map<std::pair<double, double>, ref_ptr<MyObj2> > cache_type;
    cache_type m_cache;
    enum { m_cacheMax = 4 };
    MyObj2* FindOrAdd(double X, double Y) {
        cache_type::const_iterator itF = m_cache.find(std::pair<double, double>(X, Y));
        if (itF != m_cache.end())
            return itF->second;
        // Trim the cache
        while (m_cache.size() >= m_cacheMax) {
            ...
        }
        // Create new object and add to cache
        MyObj2* obj = new MyObj2(X, Y);
        m_cache[std::pair<double, double>(X, Y)] = obj;
        return obj;
    }
    ...
};

Object creation function

The only other difference between this example and the previous example concerns the object creation function. Instead of creating a new MyObj2 instance directly, it uses the application cache. If an appropriate instance already exists in the cache, then it is used. If not, then a new instance is created and added to the cache.

CopyC++
IMPLEMENT_XLLFN2(MyObj2Create, "JBB", "MyObj2.Create", "X,Y", "User Defi"
    "ned", "Object creation function", "No description provided\0"
    "00No description provided\000", "\0\0appscope=1\0", 1)

extern "C" __declspec( dllexport )
long MyObj2Create(double X, double Y)
{
    XLL_FIX_STATE;

    MyObj2* obj = XllGetTypedApp()->FindOrAdd(X, Y);
    return XllGetTypedApp()->AddObjectHandle(obj);
}

Summary

This example differed from the previous example by using reference-counted data objects. This technique allows data objects to be maintained intact between garbage collections.

Many other techniques are applicable for managing object life-times, and different techniques will be found to be appropriate for different class libraries.


intro

intro are listed here.

Requirements

Header:

See Also

cpplog.h


myxll

myxll are listed here.

Requirements

Header:

See Also

cpplog.h


tech

tech are listed here.

Requirements

Header:

See Also

cpplog.h