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.
SubandFunctioncan have parameters... msdn.microsoft.com/en-us/vba/language-reference-vba/articles/… I think I know what you meant but calling this aFunctionis incorrect.