如何使用C#运行VBmacros脚本?

我有一个VB脚本macros用于Excel文件及其作品(手动)。 我正试图将其转换为小型APP使用:

private static void RunMacro() { Excel.Application book = null; Excel.Workbooks workbooks = null; Excel.Workbook macroWorkbook = null; Excel.Workbook destinationWorkbook = null; try { book = new Excel.Application(); workbooks = book.Workbooks; macroWorkbook = workbooks.Open(System.Windows.Forms.Application.StartupPath + "\\NewMacro.xltm"); destinationWorkbook = workbooks.Open(System.Windows.Forms.Application.StartupPath + "\\TEST.csv"); book.Run("NewMacro.xltm"); macroWorkbook.Close(false); destinationWorkbook.Close(true); } catch (Exception ex) { throw ex; // the finally will be executed before this is thrown } finally { book.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(macroWorkbook); System.Runtime.InteropServices.Marshal.ReleaseComObject(destinationWorkbook); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks); System.Runtime.InteropServices.Marshal.ReleaseComObject(book); macroWorkbook = null; destinationWorkbook = null; workbooks = null; book = null; } } 

我得到以下错误:

其他信息:无法运行macros'NewMacro.xltm'。 macros可能不在此工作簿中可用或所有macros可能被禁用。

  book.Run("NewMacro.xltm"); 

这意味着您尝试打开启用macros的电子表格,而不是macros本身。

http://filext.com/file-extension/XLTM

一个古老的问题…这样的事情会起作用

通过C#运行Excelmacros:在另一个工作簿上运行macros?

 public void WebTest_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; // Define Workbooks Excel.Workbooks oBooks = oExcel.Workbooks; Excel._Workbook oBook = null; // Get the file path string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); path = path + "\\Worksheet02.csv"; //Open the file, using the 'path' variable oBook = oBooks.Open(path, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); // Run the macro, "First_Macro" RunMacro(oExcel, new Object[]{"Worksheet01.xlsm!First_Macro"}); // 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; //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); }