添加使用 c#(或 c++/cli)访问 vba 的功能

Add functionality to access vba with c# (or c++/cli)

本文关键字:cli 访问 vba 功能 c++ 添加      更新时间:2023-10-16

我需要在访问中向 vba 添加新功能。我已经尝试了很多教程:http://www.office-loesung.de/ftopic268792_0_0_asc.php(德语)和http://www.codeproject.com/Articles/555660/Extend-your-VBA-code-with-Csharp-VB-NET-or-Cpluspl(无法发布更多代表的原因)

但它们都不适合我。客户有 Office 2013,我使用的是 .net 4.5。

我们希望为客户提供一个已经用 c#/.net 编写的 rest api,它需要一些 .net 世界的加密 dll。

我尝试创建一个打开"互操作 COM"开关的 dll,并且可以将 dll 的引用添加到我的 VBA 测试表中,但对象和静态测试函数都没有工作。在 VBA 中甚至没有智能。重新启动程序也没有解决问题。(虽然之前有些地方出错了)

我检索到的错误消息是"运行时错误 429 - ActiveX 组件无法创建对象"(适用于我自己的代码以及来自 codeplex 的代码(包含所有模块、C#、VBA、C++/Cli))

还有其他方法可以去,向 VBA 添加新功能/使用自己的功能扩展它吗?

好的,所以我终于找到了自己的方法。

在这篇文章中,从非托管 c++ 调用托管 c# 函数,链接了 NuGet 包非托管导出。因此,我创建了一个新的 C# DLL 项目,插入用于测试目的的以下代码:

using RGiesecke.DllExport;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClassLibrary1
{
    internal static class Class1
    {
        [DllExport("square", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
        static Double Square(Double dateValue)
        {
            return dateValue * dateValue;
        }
        [DllExport("test", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
        static String Test()
        {
            return " ok";
        }
        [DllExport("mytest2", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
        static void Test4(String doSomething)
        {
            // Manipulate (and obisously create new) String
            doSomething += " ok";
        }
    }
}

在打开x64开关的情况下对其进行编译,并使用以下内容在excel中创建VBA工作表:

Option Explicit
Private Declare PtrSafe Function square Lib "C:Users<Name>documentsvisual studio 2013ProjectsClassLibrary1ClassLibrary1binx64ReleaseClassLibrary1.dll" (ByVal dateValue As Double) As Double
Private Declare PtrSafe Function test Lib "C:Users<Name>documentsvisual studio 2013ProjectsClassLibrary1ClassLibrary1binx64ReleaseClassLibrary1.dll" () As String
Private Declare PtrSafe Function mytest2 Lib "C:Users<Name>documentsvisual studio 2013ProjectsClassLibrary1ClassLibrary1binx64ReleaseClassLibrary1.dll" (ByRef dateValue As String)
Private Sub CommandButton1_Click()
    Dim zahl As Double
    zahl = CInt(TextBox1.text)
    zahl = square(zahl)
    Label1.Caption = CStr(zahl)
    Dim text As String
    text = "This is"
    mytest2 (text)
    MsgBox text
End Sub

我仍然遇到的唯一错误是在调用测试函数时。返回字符串似乎会破坏 excel。(程序立即退出)但我认为这应该在另一个问题中解决。