Using a C# dll inside EXCEL VBA

后端 未结 3 1176
深忆病人
深忆病人 2020-12-05 01:13

I am running into a little problem here and need you guys\' help.

I have a C# DLL exposed through COM interop. It is working alright, but apparently the deployment o

3条回答
  •  北海茫月
    2020-12-05 01:51

    These are the using statements to put at the top of your class which are key:

    using System.Diagnostics; using RGiesecke.DllExport;

    Also ensure that you have a project started before the Nuget PM statement to install the template above. I am new at this - I am sure there are others as well. I am using AutoCAD VBA and got another error since it is 64 bit - I had to use PtrSafe (etc) in the Declare statement for VBA to continue without errors (see MS docs for this http://support.microsoft.com/kb/983043)

    It worked btw!

    My final code (based on the above)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.Diagnostics;
    using RGiesecke.DllExport;
    
    namespace ClassLibrary3
    {
        [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual)]
        public class Class1
        {
            public string Text
            {
                [return: MarshalAs(UnmanagedType.BStr)]
                get;
                [param: MarshalAs(UnmanagedType.BStr)]
                set;
            }
    
            [return: MarshalAs(UnmanagedType.BStr)]
            public string TestMethod()
            {
                return Text + "...";
            }
        }
    
        static class UnmanagedExports
        {
            [DllExport]
            [return: MarshalAs(UnmanagedType.IDispatch)]
            static Object CreateDotNetObject(String text)
            {
                return new Class1 { Text = text };
            }
        }
    }
    

    and my vba code:

    #If VBA7 Then
        Private Declare PtrSafe Function CreateDotNetObject Lib "G:\gitRepository\VS\ClassLibrary3\ClassLibrary3\bin\Debug\ClassLibrary3.dll" (ByVal text As String) As Object
    #Else
        Private Declare Function CreateDotNetObject Lib "G:\gitRepository\VS\ClassLibrary3\ClassLibrary3\bin\Debug\ClassLibrary3.dll" (ByVal text As String) As Object
    #End If
    
    Sub test()
    
      Dim instance As Object
    
      Set instance = CreateDotNetObject("Test 1")
      Debug.Print instance.text
    
      Debug.Print instance.TestMethod
    
      instance.text = "abc 123" ' case insensitivity in VBA works as expected'
    
      Debug.Print instance.text
    End Sub
    

提交回复
热议问题