c++ - 从 Excel VBA 编写并调用 C++ DLL

标签 c++ vba

我正在使用 Visual Studio 2010 用 C++ 编写一个 32 位 DLL,我打算从 Excel VBA 调用它。

C++ cpp 文件包含以下内容:

    #include "windows.h"
    #include "stdafx.h"

    int _stdcall fnGetData (const LPCSTR someText) {
        MessageBoxA(0, someText, "wizzle wuzzle", MB_OK | MB_ICONINFORMATION);
        return 42;
    }

虽然 DEF 文件有这样的内容:

    LIBRARY getpdata
    EXPORTS
    GetData=fnGetData

Excel VBA是这样的:

    Option Explicit
    Private Declare Function GetData Lib "getpdata.dll" (ByRef someText As String) As Integer
    Public Sub PassSomeText()
    Dim ret As Integer, someText As String
    someText = "Hello from my Excel Subroutine."
    ret = GetData(someText)
    End Sub

代码编译良好,并生成一个 DLL。但是当我从Excel VBA调用DLL中的函数时,消息框中的文本是乱码: Result of MessageBoxA cpp call: d³ô³ or other garbled nonsense

我可能看到了指针的文本表示?如何获取Excel VBA传入的文本值?

最佳答案

正当我要发布我的问题时就弄清楚了。答案是在VBA函数声明中将ByRef更改为ByVal:

    Private Declare Function GetData Lib "getpdata.dll" (ByVal someText As String) As Integer

关于c++ - 从 Excel VBA 编写并调用 C++ DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29498179/

相关文章:

vba - 用逗号(,)拆分字符串并将对象添加到集合中

excel - 范围类的自动调整方法失败(运行时错误 1004)

excel - 向形状添加超链接

c++ - 在 Mac OS X Lion 上使用 OpenMP 编译失败(memcpy 和 SSE 内在函数)

c++ - 在运行时将指针推送到 vector C++

c++ - 获取模板化对象方法的返回类型

excel - 如何使用 VBA 将形状粘贴到 Excel 工作表中的现有形状之后?

c++ - OpenCV:是否可以从角落检测矩形?

c++ - 在 opencv2 和 opencv3 中使用 findContours 时的输出差异

vba - 如何防止 Excel 加载项文件将单元格引用更改为 R1C1/列更改为字母