Calling C++ DLL From Excel
Calling C++ DLL From Excel
Edward M. Rosen
EMR Technology Group
Background
Microsoft’s Excel 2000 is a widely used spreadsheet program. Its macro language, Visual
Basic for Applications (VBA) (1,2) , provides an attractive means for performing a
variety of engineering computations.
Rosen and Partin (3) have described how legacy chemical engineering technology
developed in FORTRAN can be utilized by calling the FORTRAN routines from VBA.
In addition to FORTRAN, VBA can also directly utilize functions and/or subroutines
written in the popular C++ programming language (4,5).
Visual C++ 6.0 offers a wizard to enable rapid development of C++ DLLs (dynamic link
libraries). However, despite the coaching the wizard supplies and the many Internet help
sites, the development of the DLL can be confusing. In this article the author describes
the use of Visual C++ 6.0 to generate a DLL which can be called directly from the VBA
code. An example Excel spreadsheet which utilizes the DLL is described.
Figure 1a shows ddd.cpp file with the coding for the ddd.dll that we are creating. The
line starting with double _stdcall Vari (double indata[], long NumItems) defines a C++
routine named “Vari” to calculate the variance of a list which is NumItems long.
Figure 1b is an additional file file (ddd.def) that must be inserted into the project. It
allows for the export of the “Vari” function.
After the file ddd.dll is debugged and built (with Win32 Release) it must be placed where
it can be found. Here we have placed it in “C:\Ctest\ddd\Release\ddd.dll.
The VBA module (Rtest) is shown in Figure 2. Note that DECLARE statement points to
the location of the dll library (ddd.dll) The array dd is passed by to the dll by reference
and the first element of the array dd is indicated in the call to “Vari”.
The spreadsheet can now invoke the Rtest function like any other spreadsheet function.
Figure 3 illustrates its use to find the variance of three lists. The variance is first
calculated using the spreadsheet function Var. Next the worksheet function Count is used
to determine the length of the list. Then the Rtest function is invoked passing the location
of the first item of the list and its length to Rtest. For example: Rtest (B6,B19). Note
that the “Vari” C++ routine gives the same answer as the spreadsheet routine VAR.
Conclusions
C++ dlls can be called directly from VBA code. However, care must be taken to build the
dll properly for use in VBA.
References
2. Getz, Ken and Mike Gilbert, VBA Developer’s Handbook, Sybex, San Francisco
(1997).
#include "stdafx.h"
{
//Function : Vari
//Description : Returns the variance for array in_data
long j;
double sumx=0, sumsquared=0;
double vari=0;
return(vari);
LIBRARY "DDD"
DESCRIPTION 'DDD Windows Dynamic Link Library'
EXPORTS
Vari @1
kdex = NumItems
For I = 1 To kdex
dd(I) = x(I)
Next I
Rtest = var
End Function
5 8 1345
6 9 1301
8 20 1368
9 33 1322
12 56 1310
33 1370
19 1318
22 1350
1303
1299