C++ – Adding C++ function to VBA/Excel

After adding a c# library to VBA I have decided to take a look how to do a similar trick with C++.

cpp

C++ is a bit fancier in a way. And it works somehow else. So, let’s start. Imagine that we want to calculate the sum of all the numbers between 0 and n. The easiest way to do it (without thinking) is to take all the numbers and to sum them up. In C++ this formula would look like this:

Thus, in order to export this “beauty” to Excel with Visual Studio, we should do the following:

First create a new DLL project (Win32 Project) with VS.

cpp001

Then select a DLL project and then check “Empty project”

cpp002

Once in the empty project we need 2 files – a *.cpp file and a *.def file.

cpp003

In the *.def file we write the following:

Before compiling, we go to Properties of the project>Linker>Input>Module Definition File and we write the name of the def file.

cpp004

Compile the project with F6. And than go to VBA and have fun:

The TestMe Sub routine now works! Taking the formula from the SSMath.dll, as we have written it in C++. Super 🙂

Tagged with: , , ,