示例三個VBA宏方法:
1 Sub getTime()
2
3 Sheet1.Cells(1, 1) = Now
4
5 End Sub
6
7
8 Sub getTime2(title As String)
9
10 Sheet1.Cells(2, 1) = title & " : " & Now
11
12 End Sub
13
14 Function getTime3(title As String) As String
15
16 getTime3 = title & " : " & Now
17
18 End Function
19
對應 的三個使用方法
1 不帶參數的宏調用(兼演示執行過程顯示Excel文件)
2 帶 參數的宏調用(兼演示執行過程不顯示Excel文件)
3 有返回值的宏調用
1 private void btnExe_Click(object sender, EventArgs e) 2 { 3 try 4 { 5 // 返回對象 6 object objRtn = new object(); 7 8 // 獲得一個ExcelMacroHelper對象 9 ExcelMacroHelper excelMacroHelper = new ExcelMacroHelper(); 10 11 // 執行指定Excel中的宏,執行時顯示Excel 12 excelMacroHelper.RunExcelMacro( 13 @"E:\csharp_study\DoVBAMacro\test.xls", 14 "getTime2", 15 new Object[] { "現在時刻" }, 16 out objRtn, 17 true 18 ); 19 20 // 執行指定Excel中的宏,執行時不顯示Excel 21 excelMacroHelper.RunExcelMacro( 22 @"E:\csharp_study\DoVBAMacro\test.xls", 23 "getTime2", 24 new Object[] { "現在時刻" }, 25 out objRtn, 26 false 27 ); 28 29 // 執行指定Excel中的宏,執行時顯示Excel,有返回值 30 excelMacroHelper.RunExcelMacro( 31 @"E:\csharp_study\DoVBAMacro\test.xls", 32 "getTime3", 33 new Object[] { "現在時刻" }, 34 out objRtn, 35 true 36 ); 37 38 MessageBox.Show((string)objRtn); 39 40 } 41 catch(System.Exception ex) 42 { 43 MessageBox.Show(ex.Message); 44 } 45 }
幫助類需添加引用:Microsoft Excel 11.0 Object Library