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
5
  • 1
    You have a calling convention mismatch. The VBA is stdcall, the C++ code is cdecl. Commented Oct 18, 2013 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. Commented Oct 22, 2013 at 21:04
  • You can use dllexport with stdcall Commented Oct 22, 2013 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. Commented Oct 22, 2013 at 21:30
  • You just need to use the decorated name. Or a def file, but you knew that. Commented Oct 22, 2013 at 21:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.