public void RunMacros(Excel.Application xlApp, string file, string macroFileName, string macroString) { { string time = DateTime.Now.ToString("yyyyMMddhhmmss"); string newFile = file.Insert(file.LastIndexOf("."), "_" + time); System.IO.File.Copy(file, newFile + "_orig"); System.IO.File.Copy(file, newFile); file = newFile; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlWorkBook = xlApp.Workbooks.Open(file, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); string[] macros = macroString.Split('|'); //macroBook = xlApp.Workbooks.Open(macroFile); xlWorkBook.Activate(); try { foreach (string macroName in macros) xlApp.Run(macroFileName + "!" + macroName); this.file = file = file.Substring(0, file.LastIndexOf(".")) + ".csv"; xlWorkBook.SaveAs(file, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows);//, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //xlWorkBook.Close(true, misValue, misValue); } catch (Exception e) { this.success = false; Console.WriteLine("Failed to run report " + file); Console.WriteLine(e.ToString()); System.Windows.Forms.MessageBox.Show("Running macro on " + this.shortname + " failed.", "Report Failed", System.Windows.Forms.MessageBoxButtons.OK); //throw new Exception("Macro Failed"); } finally { xlWorkBook.Close(false); Console.WriteLine("Excel Workbook Closed. Report: " + this.file); } } }