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 中的 Dictionary 。如果是这种情况,您也应该在 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 回答