我想将收集数据字典从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.
}
}
}
答案 0 :(得分:0)
您应该更加具体地了解您获得的错误。无论如何,我认为你的问题是你传递宏的错误类型的对象。即您正在创建一个VBA不知道的Dictionary<string, int>
。
您没有指定您的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);