How to pass a C#.net Dictionary to VBA

1

I am trying to pass a Dictionary from c# to vba but this error occurs

System.Runtime.InteropServices.COMException: 'Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))'

I also tried converting my list of string into vb collection but the same error occurs. here are my codes

private void btn_macrorunner_Click(object sender, EventArgs e)
{
    Dictionary<string, string> xlist_dictvb = new Dictionary<string, string>();
//xlist_names has been properly initialized and already has some items
    xlist_names.ForEach(x => xlist_dictvb.Add(x, x));

    ExcelFire(xlist_dictvb);
}

private void ExcelFire(Dictionary<string, string> pcoll = null)
{
    //~~> Define your Excel Objects
    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlWorkBook;

    //~~> Start Excel and open the workbook.
    xlWorkBook = xlApp.Workbooks.Open(@"C:\Users\Hutanginamo\Documents\xlkalat\0928ExcelFile.xlsm");

    if(pcoll != null)
    {
        //calls Sub ShowDict(pdict1 As Dictionary) 
        xlApp.Run("ShowDict", pcoll); //WHERE ERROR OCCURS
    }

    //~~> Clean-up: Close the workbook
    xlWorkBook.Close(false);

    //~~> Quit the Excel Application
    xlApp.Quit();

    //~~> Clean Up
    ReleaseObject(xlApp);
    ReleaseObject(xlWorkBook);
}

here are my vba codes

Sub ShowDict(pdict1 As Dictionary)
   Dim x As Variant

   For Each x In pdict1.keys
        MsgBox (pdict1.Item(x))
   Next
End Sub
c#
vba
excel
asked on Stack Overflow Sep 28, 2018 by Pamingkas Sevada • edited Sep 28, 2018 by Pamingkas Sevada

1 Answer

2

To achieve what you want, you have to pass the right dictionary. C# dictionary can't be used in VBA like this. The easiest way to achieve what you want is to use VBA dictionary in C# and then pass that.

See this example.

C# Code

Scripting.Dictionary dict = new Scripting.Dictionary();
dict.Add("Apples", 50);
dict.Add("Oranges", 60);

Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;

// ~~> Opens an existing Workbook. Change path and filename as applicable
xlWorkBook = xlApp.Workbooks.Open("C:\\Sample.xlsm");

// ~~> Display Excel
xlApp.Visible = true;
xlApp.Run("ShowDict", dict);

VBA Code

Sub ShowDict(pdict1 As Dictionary)
   Dim x As Variant

   For Each x In pdict1.keys
        MsgBox (pdict1.Item(x))
   Next
End Sub

References in C#

enter image description here

References in VBA

enter image description here

answered on Stack Overflow Sep 28, 2018 by Siddharth Rout

User contributions licensed under CC BY-SA 3.0