Wednesday, July 8, 2009

How to create C++ DLL and use it in VBA?

To create a new dynamic link library (DLL) project

  1. From the File menu, select New and then Project….

  2. From the Project types pane, under Visual C++, select Win32.

  3. From the Templates pane, select Win32 Console Application.

  4. Choose a name for the project, such as DLL3, and enter it in the Name field. Choose a name for the solution, such as DLL3, and enter it in the Solution Name field.

  5. Press OK to start the Win32 application wizard. From the Overview page of the Win32 Application Wizard dialog, press Next.

  6. From the Application Settings page of the Win32 Application Wizard, under Application type, select DLL if it is available or Console application if DLL is not available. Some versions of Visual Studio do not support creating a DLL project using wizards. You can change this later to make your project compile into a DLL.

  7. From the Application Settings page of the Win32 Application Wizard, under Additional options, select Empty project.

  8. Press Finish to create the project.


To add a class to the dynamic link library

  1. To create a header file for a new class, from the Project menu, select Add New Item…. The Add New Item dialog will be displayed. From the Categories pane, under Visual C++, select Code. From the Templates pane, select Header File (.h). Choose a name for the header file, such as DLL3.h, and press Add. A blank file will be displayed.

  2. Use same steps in (1) to add .cpp file (for the code) and .def file (for the functions and subroutine names to be used in VBA).
Note: __stdcall is required for any C/C++ function that you want to use with VB.

Calling a DLL C++ function from a VB application

DLL3.h

__declspec(dllexport) double __stdcall Multiply(double a, double b);

DLL3.cpp

#include "DLL3.h"

__declspec(dllexport) double __stdcall Multiply(double a, double b)
{
return a * b;
}


DLL3.def

EXPORTS
Multiply

VBA CODE

Private Declare Function Multiply Lib "PATH\DLL3.dll" (ByVal n1 As Double, ByVal n2 As Double) As Double

Sub testDLLFunctions()

Dim r As Double
r = Multiply(5, 6)
MsgBox r

End Sub

Calling a DLL C++ class from a VB application

http://www.codeproject.com/KB/DLL/XDllPt3.aspx