I need to perform an existing Excel Macro (written in VB, can be copied from Excel using the Macro editor) on an existing csv file using C#. I already have working code that I can use to perform the Macro on an xlsm file, which looks like this:
using System;
using Excel = Microsoft.Office.Interop.Excel;
namespace MacroBuddy
{
public class test
{
public static void go_Macro()
{
object oMissing = System.Reflection.Missing.Value;
//create new Excel application instance
Excel.Application oExcel = new Excel.Application();
oExcel.Visible = true;
Excel.Workbooks oBooks = oExcel.Workbooks;
Excel._Workbook oBook = null;
string path = @"C:\Users\user\Desktop\test.csv";
//open file located at path
oBook = oBooks.Open(path, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
//run Macro by referencing file and the name of the Macro
RunMacro(oExcel, new Object[] { "test.xlsm!TestMacro" });
//save and close workbook
oBook.Save();
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();
}
private static void RunMacro(object oApp, object[] oRunArgs)
{ oApp.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, oApp, oRunArgs); }
static void Main()
{ go_Macro(); }
}
}
However, it does not work if the file specified is a csv file. So I need help make similar code work on a csv file, or an automated process to convert the csv file to an xlsm file from C#.
Also, it would be helpful to be able to take the VB macro code as a string and be able to run a macro using a method that would take the string as an argument or some similar process.