Accessing c# 7 dll in VBA

-- -- 957 Reputation points
2023-05-21T03:35:46.4666667+00:00

Hi

I have a com server in net 7 as per below code at the end. Building this project creates two dlls; COMServer.comhost.dll and COMServer.dll.

When I try to add either to references inside Microsoft Access I get 'Can't add a reference to the specified file.'.

How can I add the com dll reference to Microsoft Access and call the function inside the com server?

Thanks

Regards

using System;
using System.Runtime.InteropServices;

namespace COMServer
{
    internal sealed class ContractGuids
    {
        public const string ServerClass = "DB1797F5-7198-4411-8563-D05F4E904956";
        public const string ServerInterface = "BA9AC84B-C7FC-41CF-8B2F-1764EB773D4B";
    }

    [ComVisible(true)]
    [Guid(ContractGuids.ServerInterface)]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IServer
    {
        /// <summary>
        /// Compute the value of the constant Pi.
        /// </summary>
        double ComputePi();
    }

    [ComVisible(true)]
    [Guid(ContractGuids.ServerClass)]
    public class Server : IServer
    {
        double IServer.ComputePi()
        {
            double sum = 0.0;
            int sign = 1;
            for (int i = 0; i < 1024; ++i)
            {
                sum += sign / (2.0 * i + 1.0);
                sign *= -1;
            }

            return 4.0 * sum;
        }
    }
}

Microsoft 365 and Office Development Other
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. RLWA32 49,536 Reputation points
    2023-05-21T08:33:37.3866667+00:00

    The COM support in .Net is different from the .Net Framework. For COM servers created using the .Net Framework registration of the server and and generation and registration of the related type library can be performed by Regasm.exe.

    COM Servers created using .Net are registered by regsvr32.exe and there is no built-in support for creating and registering a type library (necessary for VBA).

    However, the sample at https://github.com/dotnet/samples/tree/main/core/extensions/OutOfProcCOM contains everything needed to solve the type library issue. In particular, it shows how to use an IDL file and midl.exe to generate a type library and also shows how to embed that type library within a COM Server. I suggest you pay close attention to the DllServer project included in the sample.

    Additionally, see the Answer and related comments on a similar issue here - [https://learn.microsoft.com/en-us/answers/questions/1180474/exposing-net-7-classes-as-com-for-excel-vba-(and-v](https://learn.microsoft.com/en-us/answers/questions/1180474/exposing-net-7-classes-as-com-for-excel-vba-(and-v)

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.