Reputation: 1842
I need to call a DLL in 64-bit Excel for use in VBA. i.) I've been told I can't use a 32-bit dll in a 64-bit program, is this true? ii.) Does anyone know of an example they know to be working demonstrating loading a dll into VBA.
At the moment they're not even loading. I can call the DLL's fine from within C++.
The example code is as follows and compiles fine in 64 bit mode. I've tried registering the function. The VBA error is "compile error: expected lib"
Failing calling function in VBA
Public Declare PtrSafe Function getNumber_Lib "C:\Users\james.allsop\Documents\Visual Studio 2010\Projects\DynamicLibrary\x64\Debug\MathFuncsDll.dll" () As Integer
The following all compiles and runs.
MathFuncsDll.h
// MathFuncsDll.h
// Returns a + b
__declspec(dllexport) double Add(double a, double b);
// Returns a - b
__declspec(dllexport) double Subtract(double a, double b);
// Returns a * b
__declspec(dllexport) double Multiply(double a, double b);
// Returns a / b
// Throws DivideByZeroException if b is 0
__declspec(dllexport) double Divide(double a, double b);
__declspec(dllexport) double getNumber();
MathFuncsDll.cpp
#include "MathFuncsDll.h"
double Add(double a, double b)
{
return a + b;
}
double Subtract(double a, double b)
{
return a - b;
}
double Multiply(double a, double b)
{
return a * b;
}
double Divide(double a, double b)
{
if (b == 0)
{
return -1.0;
}
return a / b;
}
double getNumber()
{
return 1000;
}
MyExecRefsDll.cpp
// MyExecRefsDll.cpp : Defines the entry point for the console application.
//
// MyExecRefsDll.cpp
// compile with: /EHsc /link MathFuncsDll.lib
#include <iostream>
// Returns a + b
__declspec(dllimport) double Add(double a, double b);
// Returns a - b
__declspec(dllimport) double Subtract(double a, double b);
// Returns a * b
__declspec(dllimport) double Multiply(double a, double b);
// Returns a / b
// Throws DivideByZeroException if b is 0
__declspec(dllimport) double Divide(double a, double b);
__declspec(dllimport) double getNumber();
int main()
{
double a = 7.4;
int b = 99;
std::cout << "a + b = " << Add(a, b) << "\n";
std::cout << "a - b = " << Subtract(a, b) << "\n";
std::cout << "a * b = " << Multiply(a, b) << "\n";
std::cout << "a / b = " << Divide(a, b) << "\n";
return 0;
}
Any help would be greatly appreciated! James
Upvotes: 1
Views: 3714
Reputation: 78815
Your declaration in VBA contains an error. It should be:
Public Declare PtrSafe Function getNumber Lib "C:\Users\james.allsop\Documents\Visual Studio 2010\Projects\DynamicLibrary\x64\Debug\MathFuncsDll.dll" () As Integer
instead of:
Public Declare PtrSafe Function getNumber_Lib "C:\Users\james.allsop\Documents\Visual Studio 2010\Projects\DynamicLibrary\x64\Debug\MathFuncsDll.dll" () As Integer
Note the removed underscore.
And yes, you cannot call 32-bit DLLs from 64-bit applications and vice versa. That's a general restriction for all applications, not just for VBA or Excel.
Upvotes: 2