0

I am importing a function into Excel VBA from a DLL. The DLL was created in Microsoft Visual C++ (with a mostly unmodified version of the default example). The return value of the function call in VB is not correct, but I do not know the reason why.

The value I see is 0, but I expect to get a value of 42.

I found an almost identical question here. I tried their experiment, where I called the function from the spreadsheet. I saw the same behavior, the spreadsheet return was correct and the return in vba code was not.

The C++ code looks like this:

addnum.h

#ifdef ADDNUM_EXPORTS
#define ADDNUM_API __declspec(dllexport)
#else
#define ADDNUM_API __declspec(dllimport)
#endif

extern "C" {
ADDNUM_API int  fnaddnum(void);
}

addnum.cpp

#include "stdafx.h"
#include "addnum.h
ADDNUM_API int fnaddnum(void)
{
    return 42;
}

The VB code looks like this:

Declare Function fnaddnum _
   Lib " ... path to dll ... " _
   () As Integer


Sub use_dll()
   Dim return_val As Integer
   return_val = fnaddnum()
   MsgBox ("Value is" & Str(return_var))
End Sub
Community
  • 1
  • 1
beeflobill
  • 317
  • 1
  • 10
  • 1
    You have a calling convention mismatch. The VBA is stdcall, the C++ code is cdecl. – David Heffernan Oct 18 '13 at 22:35
  • @david heffeman Yes, that is the fundamental issue. Since, I must use stdcall, I can't use __declspec(dllimport). Since I'm not using __declspec(dllimport), I need a def file. – beeflobill Oct 22 '13 at 21:04
  • You can use dllexport with stdcall – David Heffernan Oct 22 '13 at 21:11
  • Sorry to speak untruths. What I meant was that I have not gotten VBA to accept dll's with dllexport and stdcall together since I've been working on it. Because it could be my error, I can't rightly conclude that they *can't* be used together in this context. I'm just happy I can get something to work now. Thanks. – beeflobill Oct 22 '13 at 21:30
  • You just need to use the decorated name. Or a def file, but you knew that. – David Heffernan Oct 22 '13 at 21:32

1 Answers1

0

The problem is that I had a typo. I was referencing 'return_var' instead of 'return_val'. Indeed, the dll function reference was returning the value correctly.

beeflobill
  • 317
  • 1
  • 10