以编程方式将代码模块导入Excel工作簿

时间:2012-08-21 07:09:02

标签: c# excel vba

我动态创建工作簿。我想在创建它时导入代码模块(Module1.bas)和(UserForm1.frm)。

有没有办法使用工作簿或工作表对象附加此类文件?

Microsoft.Office.Interop.Excel.Workbook wkBk;
Microsoft.Office.Interop.Excel.Worksheet wkSht; 
app = new Microsoft.Office.Interop.Excel.Application();
app = new Microsoft.Office.Interop.Excel.Application();
app.DisplayAlerts = false;
app.Visible = false;
wkBk = app.Workbooks.Open(strFile, oMissing); 
wkSht = (Microsoft.Office.Interop.Excel.Worksheet)wkBk.Sheets.get_Item(2); 
wkBk.Save(); 

1 个答案:

答案 0 :(得分:4)

$oExcel = ObjCreate("Excel.Application")
    With $oExcel
        .Visible = 0
        .WorkBooks.Open("C:\Excel.xls")
    EndWith

    $oModules = $oExcel.ActiveWorkbook.VBProject.VBComponents
    $oModules.Import("C:\Module1.bas")
    $oModules.Import("c:\Program Files\Microsoft Office\Office11\UserForm1.frm")