我正在尝试以编程方式打开一个 Excel 工作簿并运行一个宏,该宏接受输入到命令行中的参数。到目前为止,我能够打开工作簿并执行宏,但是我无法传递参数。
我目前的代码:
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);
}
我的宏看起来像:
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
正如我所说,这适用于执行宏(sDate 最初在子文件中格式化为字符串,而不是如图所示传入),但我试图将“日期”变量传递给 runTemplate 并通过它作为 sDate 进入我的宏。我曾尝试简单地将它添加到参数对象中,RunMacro(ExcelApp, new Object[] { template, date });但这引发了错误。
胡子哥哥
相关分类