Barry Piccinni
Barry Piccinni

Reputation: 1791

C# running a excel macro with parameters

I am trying to programatically open an excel workbook and run a macro which accepts a parameter typed into the command line. So far, I am able to open the workbook and execute the macro, but I am having trouble passing in the parameter.

My code at the moment:

 public void runTemplate(string templateName, string sourceFile, string destinationFile, string ITPath, string date)
    {
        string template = templateName + "!DoTheImport";
        Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
        ExcelApp.DisplayAlerts = false;
        object misValue = System.Reflection.Missing.Value;
        ExcelApp.Visible = false;
        Microsoft.Office.Interop.Excel.Workbook ExcelWorkBook = ExcelApp.Workbooks.Open(sourceFile);
        RunMacro(ExcelApp, new Object[] { template });
        ExcelWorkBook.SaveCopyAs(destinationFile);
        ExcelWorkBook.SaveCopyAs(ITPath);
        ExcelWorkBook.Close(false, misValue, misValue);
        ExcelApp.Quit();
        if (ExcelWorkBook != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelWorkBook); }
        if (ExcelApp != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp); }
    }

    private void RunMacro(object oApp, object[] oRunArgs)
    {
        oApp.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, oApp, oRunArgs);
    }

My Macro looks like:

Sub DoTheImport(sDate As String)


With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;\\filePath\DecisionsByRegion-" + sDate + ".txt", 
    Destination:=Range("$A$2") _)
    .Name = "test"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = True
    .TextFileSemicolonDelimiter = True
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
Columns("A:G").EntireColumn.AutoFit
Columns("H").EntireColumn.Delete

End Sub

As I said, this works fine for executing a macro (sDate was originally Now() formatted as a string in the sub, not passed in as shown), but I am trying to take the 'date' variable being passed into runTemplate and pass it into my Macro as sDate. I have tried simply adding it into the parameter object RunMacro(ExcelApp, new Object[] { template, date }); but this threw an error.

Upvotes: 4

Views: 5590

Answers (1)

Barry Piccinni
Barry Piccinni

Reputation: 1791

Whilst I have not been able to pass in multiple variables using my existing approach, I have found an alternative method for executing the macro which has allowed me to pass parameters as required.

public void runTemplate(string templateName, string sourceFile, string destinationFile, string ITPath, string date)
{
    string sDate = date;
    Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
    ExcelApp.DisplayAlerts = false;
    object misValue = System.Reflection.Missing.Value;
    ExcelApp.Visible = false;
    Microsoft.Office.Interop.Excel.Workbook ExcelWorkBook = ExcelApp.Workbooks.Open(sourceFile);
    ExcelApp.Run("DoTheImport", sDate);
    ExcelWorkBook.SaveCopyAs(destinationFile);
    ExcelWorkBook.SaveCopyAs(ITPath);
    ExcelWorkBook.Close(false, misValue, misValue);
    ExcelApp.Quit();
    if (ExcelWorkBook != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelWorkBook); }
    if (ExcelApp != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp); }
}

I have removed the RunMacro method and simply used ExcelApp.Run("DoTheImport", sDate); to execute the macro. This method allows me to pass parameters into the macro, which can be accessed in the macro by adding the 'ByVal' parameter passing mechanism:

Sub DoTheImport(ByVal sDate As String)

Upvotes: 2

Related Questions