Bala Kumar
Bala Kumar

Reputation: 667

Import code modules programmatically to Excel workbook

I create a workbook dynamically. I want to import code modules (Module1.bas) and (UserForm1.frm) when creating it.

Is there any way to attach such files by using workbook or worksheet objects?

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(); 

Upvotes: 2

Views: 7265

Answers (1)

perilbrain
perilbrain

Reputation: 8187

The following code opens an Excel file and adds to it one VBA module and one VBA user form, taken from files on your disk.

So that it works, you must first switch on the "Trust Access to Visual Basic Project" setting. It can be found in Tools -> Macro -> Security, on the "Trusted Publishers" tab. (This is for Excel 2003; for 2007, it can be found in Excel Options -> Trust Center -> Trust Center Settings -> Macro Settings). You need to ensure that this setting is enabled wherever Excel is running (independently of where the Excel files you are processing are stored). (You can't change this setting programatically - that would make it a completely pointless setting).

$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")

Upvotes: 6

Related Questions