0

コレクションデータディクショナリをC#コードからExcelマクロに渡したい。私が今直面している問題は、辞書をマクロに渡す際のエラーです。

これは私が使用するExcelモジュールに存在するマクロコードの簡単な例です:

Public Sub dictionaryTest1(dataku As Variant)

Dim I As Integer
For Each v In dataku.Keys
    MsgBox "Name: " & v & " Age: " & dataku.Item(v)
Next
End Sub

私と以下は私のc#コードです:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using System.Reflection;
using System.IO;
namespace WindowsMacro
{
    public partial class Form1 : Form
    {
public Form1()
    {
        InitializeComponent();
    }

private void RunMacro(object oApp, object[] oRunArgs)
    {
        oApp.GetType().InvokeMember("Run",
            System.Reflection.BindingFlags.Default |
            System.Reflection.BindingFlags.InvokeMethod,
            null, oApp, oRunArgs);
    }

private void button1_Click(object sender, EventArgs e)
    {
        Dictionary<string, int> dataku = new Dictionary<string, int>()
        {
            {"cat", 2},
            {"dog", 1},
            {"llama", 3},
            {"iguana", 5}
        };

        object oMissing = System.Reflection.Missing.Value;

        Excel.ApplicationClass oExcel = new Excel.ApplicationClass();
        oExcel.Visible = true;
        Excel.Workbooks oBooks = oExcel.Workbooks;
        Excel._Workbook oBook = null;


        //path to excel file at bin folder
        string executableLocation =   Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        string xslLocation = Path.Combine(executableLocation, "File.xls");

        oBook = oBooks.Open(xslLocation, oMissing, oMissing,
            oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
            oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

        //Run macros with passing the dictionary data "dataku".
        RunMacro(oExcel, new Object[] { "dictionaryTest1", dataku });
        // Quit Excel and clean up.
        oBook.Close(false, oMissing, oMissing);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook);
        oBook = null;
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks);
        oBooks = null;
        oExcel.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
        oExcel = null;
        GC.Collect();   //Garbage collection.
    }
}
}
4

1 に答える 1

0

発生するエラーについて、より具体的に説明する必要があります。とにかく、あなたの問題は、マクロに間違ったタイプのオブジェクトを渡しているという事実だと思います。Dictionary<string, int>つまり、VBA では認識されないを作成しています。

DictionaryTest1 マクロで受け入れられる型を指定していませんが、Microsoft Scripting Runtime の辞書だと思います。その場合は、C# でもこの種のオブジェクトを作成する必要があります。これは、Microsoft Scripting Runtime を .NET プロジェクトの参照に追加し、次の方法でマクロに渡される辞書を作成する必要があることを意味します。

        Scripting.Dictionary dataku = new Scripting.DictionaryClass();
        dataku.Add("cat", 2);
        dataku.Add("dog", 1);
        dataku.Add("llama", 3);
        dataku.Add("iguana", 5);
于 2012-08-28T06:01:54.020 に答える