我正在运行一个宏,让我们从WorkSheet02上的WorkSheet01中将它称为Macro01。通过C#运行Excel宏:在另一个工作簿上运行宏?
使用Microsoft.Office.Interop.Excel命名空间我打开了一个WorkSheet01。
public void Main_CodedStep()
{
// Object for missing (or optional) arguments.
object oMissing = System.Reflection.Missing.Value;
// Create an instance of Microsoft Excel
Excel.ApplicationClass oExcel = new Excel.ApplicationClass();
// Make it visible
oExcel.Visible = true;
// Open Worksheet01.xlsm
Excel.Workbooks oBooks = oExcel.Workbooks;
Excel._Workbook oBook = null;
oBook = oBooks.Open("C:\\Users\\Admin\\Documents\\Worksheet01.xlsm", oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
}
然后,我使用自动脚本来拉取报告。此报告通过IE的下载提示而不是Interop打开。
问题是当我尝试运行通过C#宏(我又有了新的Excel.ApplicationClass();只有这样它编译,我相信这是我的失误之一。)
public void FirstMacro_CodedStep()
{
// Create an instance of Microsoft Excel
Excel.ApplicationClass oExcel = new Excel.ApplicationClass();
Console.WriteLine("ApplicationClass: " + oExcel);
// Run the macro, "First_Macro"
RunMacro(oExcel, new Object[]{"Worksheet01.xlsm!First_Macro"});
//Garbage collection
GC.Collect();
}
private void RunMacro(object oApp, object[] oRunArgs)
{
oApp.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, oApp, oRunArgs);
}
当此方法运行它从Worksheet01而不是Worksheet02 Works5运行宏。此外,它正在寻找我的文档中的工作表,所以我移动它看看会发生什么。
回顾:
- 打开Worksheet01
- 通过脚本获取和MSIE打开报告(Worksheet02)
- 运行Macro01从Worksheet01上Worksheet02
资源:
http://support.microsoft.com/kb/306683
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.aspx
对于那些想尝试它添加到您的使用指示谁:
using System.Reflection;
using Microsoft.Office.Core; //Added to Project Settings' References from C:\Program Files (x86)\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14 - "office"
using Excel = Microsoft.Office.Interop.Excel; //Added to Project Settings' References from C:\Program Files (x86)\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14 - "Microsoft.Office.Interop.Excel"
请检查这一项 http://stackoverflow.com/questions/27166341/run-microsoft-office-macro-using-c-sharp –