parser to convert .net dictionary or list to VBA&#

2019-06-05 21:19发布

问题:

i have to pass the .net dictionary or list type of object to VBA. but when i am passing the .net dictionary at VBA side i am not able to see the elements of dictionary on .net side.

My code in C#

Dictionary<string,object> dict = new Dictionary<string,object>();
dict.Add("First", "1");
dict.Add("Second", "2");
dict.Add("third", "3");
dict.Add("Forth", "4");

i am calling the VBA macro from C# as

Application.Run("MyVBAMacro", dict);

in VBA side My Macro is

public Sub MyVBAMacro(var as variant)

end Sub

i also tried with

public Sub MyVBAMacro(var as Scripting.Dictionary)

end Sub

but didn't work for me.

in the WATCH window of VBA i am not getting the dictionary elements.

so i think .net and VBA objects are not same. so is there any parsing class by which i can convert my .net objects to equivalent VBA objects?

problem is also with the .net List object. .net array is working fine but i want to pass dictionary or collection type of objects to VBA.

please let me know if there is some solution to this.

Thanks, Monil Gangar

回答1:

You need to use COM when doing interop between VBA and .NET This is a simple start: COM Interop

But it can get a bit more intricate quite quickly, i'd recommend reading up on the topics of general COM, marshaling, reference counting and type libraries when undertaking such a task.

Simple example for making that dictionary COM Visible

[ComVisible(true)]
public interface IDictWrapper
{
    object GetByKey(string key);
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IDictWrapper))]
public class DictWrapper: Dictionary<string,object>, IDictWrapper
{
    public object GetByKey(string key)
    {
        return base[key];
    }
}