我想将 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.
}
}
}