c++ - 从 C++ 代码通过 excel 访问 DLL

标签 c++ vba excel dll

我正在尝试使用 visual studio 2015 从 C++ 代码创建 DLL。

我有一个 DLL_Tutorial.h 文件:

#ifndef _DLL_TUTORIAL_H_
#define _DLL_TUTORIAL_H_
#include <iostream>


extern "C"
{
   DECLDIR int Add( int a, int b );
}

#endif
\\

\然后我创建了一个DLL_Tutorial.cpp

#include <iostream>
#include "DLL_Tutorial.h"

#define DLL_EXPORT

extern "C"
{
    __declspec(dllexport) int Add(int a, int b)

    {
        return(a + b);
    }

}

我得到了一个Dll文件

我想在 VBA 中调用我的函数并将其应用于 Excel 工作表

所以在 VBA 中我做了:

Public Declare Function Add _
Lib "C:\Users\hasna\Desktop\Projet VBA-C++\projet5\Debug\projet5.dll" (byval a As integer,byval b As integer) As integer

然后在 Excel 工作表中,我输入 2 个值(例如 6 和 4)我调用添加函数但它给了我:#VALEUR!

问题出在哪里? 你能帮我解决一下吗

谢谢

最佳答案

在您的 DLL 头文件中,您似乎没有为导出的 API 添加前缀 __declspec(dllexport)。这通常被定义为 API 可以在构建 DLL 时使用 __declspec(dllexport),在外部项目中使用 header 时使用 __declspec(dllimport)。最好的办法是只使用 VS 2015 项目模板创建 DLL,它包含正确的 header ,并为您导出定义,因此您只需要专注于编写 API。这是 VS 2015 项目的一个工作示例:

例子 *.h:

#pragma once

// The following ifdef block is the standard way of creating macros which make exporting 
// from a DLL simpler. All files within this DLL are compiled with the DLLAPI_EXPORTS
// symbol defined on the command line. This symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see 
// DLLAPI_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#ifdef DLLAPI_EXPORTS
#define DLLAPI_API __declspec(dllexport)
#else
#define DLLAPI_API __declspec(dllimport)
#endif

// This is an example of an exported function.
DLLAPI_API int fnDLLAPI(void);

示例 *.cpp:

// DLLAPI.cpp : Defines the exported functions for the DLL application.
//

#include "DLLAPI.h"

// This is an example of an exported function.
DLLAPI_API int fnDLLAPI(void)
{
    return 42;
}

Windows Via C/C++ 书也是有关编写 DLL 的非常好的资源。现在关于 VB 导入,我不确定,因为我不熟悉通过 VB 导入 API。

关于c++ - 从 C++ 代码通过 excel 访问 DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386112/

相关文章:

vba - 如何仅删除一系列单元格的格式...也就是说,保持内容不变

vba - 如何替换列中的所有错误值

c++ - 在C++中将std::sort与迭代器和模板一起使用

c++ - C++ 中 T* 类型上 std::move 的意外行为

c++ - 程序运行到一半就停止了?

excel - 使用单元格公式从文件路径获取父文件夹路径

vb.net - 在 Excel 中从 VBA 调用 VB.Net

c++ - 函数: 'find' 未为 std::vector 定义

c - 微软 Access : Search through Table for the same part of the String

Excel VBA application.visible 立即设置回 True