MATLAB Excel Builder    

When to Use a Formula Function or a Subroutine

Visual Basic for Applications (VBA) provides two basic procedure types, functions and subroutines. You access a VBA function directly from a cell in a worksheet as a formula function and access a subroutine as a general macro. Function procedures are useful when the original MATLAB function takes one or more inputs and returns one scalar output. When the original MATLAB function returns an array of values or multiple outputs, you need a subroutine procedure to map these outputs into multiple cells/ranges in the worksheet. When you create a MATLAB Excel Builder component, you produce a VBA module (.bas file). This file contains simple call wrappers, each implemented as a function procedure for each method of the class.

Initializing Excel Builder Libraries with Excel

Before you use any MATLAB Excel Builder component, initialize the supporting libraries with the current instance of Excel. Do this once for an Excel session that uses MATLAB Excel Builder components. To do this initialization, call the utility library function MWInitApplication, a member of the MWUtil class. This class is part of the MWComUtil library. See the section Utility Library Classes for a detailed discussion of the functionality provided with this library.

One way to add this initialization code into a VBA module is to provide a subroutine that does the initialization once, and simply exits for all subsequent calls. The following Visual Basic code sample initializes the libraries with the current instance of Excel. A global variable of type Object named MCLUtil holds an instance of the MWUtil class, and another global variable of type Boolean named bModuleInitialized stores the status of the initialization process. The private subroutine InitModule() creates an instance of the MWComUtil class and calls the MWInitApplication method with an argument of Application. Once this function succeeds, all subsequent calls exit without reinitializing.

This code is similar to the default initialization code generated in the VBA module created when the component is built. Each function that uses MATLAB Excel Builder components can include a call to InitModule at the beginning to ensure that the initialization always gets performed as needed.


  Programming with Excel Builder Components Creating an Instance of a Class