简体   繁体   中英

Can we pass a custom object from Excel to C# ExcelDNA?

I have an object:

public class Shampoo
{
public string Name {get;set;}
public string Id {get;set;}
public string PriceRegion {get;set;}
}

Can I pass this object to a method in C# via Excel DNA:

C# method is:

public static string PassShampoo(Shampoo shampoo)
{
//Some Code...
}

Is this possible from VBA to C# via Excel DNA?

Your .NET library can export and register the Shampoo class as a COM visible type, which you can then instantiate from VBA as Dim sh = New Shampoo() . Similarly other types could be define, like

public class Shopper()
{
    public string ReadLabel(Shampoo shampoo)
    {
        return shampoo.Name;
    }
}

and then a New Shopper() could be passed the shampoo :

Dim anne As Shopper = New Shopper()
Dim dove As Shampoo = New Shampoo()

Dim label As String
label = anne.ReadLabel(dove)

The method using Shampoo ( Shopper.ReadLabel above) would not be static and would not be available to Excel as a UDF or anything - just as a method on a .NET object onvoked via COM interop from VBA.

So far - no Excel-DNA involved. You could do all of this with a standard .NET assembly that is compiled with the right flags and attributes and registered for COM interop on your machine.

However, Excel-DNA also allows your add-in to be a COM Server. This means that the .xll can host the COM classes you've defined in your library, your add-in can do the COM registration (instead of an installer) without requiring Administrator access, and your COM Objects will live in the same AppDomain as the rest of your add-in. So Excel-DNA helps a bit in gluing things up, but the actual interaction between the VBA code and your .NET assembly is the standard .NET-to-COM interop, which works very well once you've climbed the learning curve a bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM