Thursday, March 1, 2012

JavaScript (cscript) and Excel.Application

// to run the code
//    cscript.exe  file.js

// instantiating
var oExcel = new ActiveXObject("Excel.Application");

// opening a document
var oWorkbook = oExcel.Workbooks.open(filepath);

// closing
oWorkbook.Close(bSave);

// retrieves the ThisWorkbook module
var oModule = oBook.VBProject.VBComponents("ThisWorkBook");

// deleting code from a module
var nLines = parseInt(  oModule  .CodeModule.CountOfLines );
oModule .CodeModule.DeleteLines(1, nLines);

// inserting code to the module
oModule .CodeModule.AddFromString( codestring );

// the current security
var nCurrSecurity = oExcel.AutomationSecurity;

// disable automation, set security to very high
oExcel.AutomationSecurity = 3;


Others,  to enable the Trust  Access to VB Projects set the following registry


[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\11.0\Excel\Security]
"AccessVBOM"=dword:00000001