Skip to content

Instantly share code, notes, and snippets.

@chrispsn
Last active July 2, 2021 03:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrispsn/a27635f194953c8109a23e191d49ade9 to your computer and use it in GitHub Desktop.
Save chrispsn/a27635f194953c8109a23e191d49ade9 to your computer and use it in GitHub Desktop.
Example of using JavaScript (specifically JScript) to automate Excel. To execute, run 'cscript excel.js' at Command Prompt.
// Imports - inspired by http://stackoverflow.com/a/10295725
var FS = new ActiveXObject("Scripting.FileSystemObject");
eval(FS.OpenTextFile("Util_GlobalsMgmt.js", 1).ReadAll());
// Set up Excel
var app = new ActiveXObject("Excel.Application");
var directory = WScript.CreateObject("WScript.Shell").CurrentDirectory + '\\'
var wb = app.Workbooks.Open(directory + "excel_test.xlsx", false)
var lo = wb.Worksheets("Sheet1").ListObjects("table_test")
// Do something
function change_data(lo) {
with (lo.DataBodyRange.Cells(2, 1)) {
Value2 = Math.random();
return Value2
}
}
var result = Utils_GlobalsMgmt.temp_disable_screenupdating(
app,
function() { return change_data(lo); }
)
// Tear down Excel
Utils_GlobalsMgmt.temp_disable_displayalerts(app, function(){ wb.Save(); });
app.Quit();
WScript.Echo(result);
var Utils_GlobalsMgmt = {
temp_disable_screenupdating: function(excel_app, func) {
var original_setting = excel_app.ScreenUpdating
excel_app.ScreenUpdating = false;
var output = func();
excel_app.ScreenUpdating = original_setting;
return output;
},
temp_disable_displayalerts: function(excel_app, func) {
var original_setting = excel_app.DisplayAlerts
excel_app.DisplayAlerts = false;
var output = func();
excel_app.DisplayAlerts = original_setting;
return output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment