Last active
July 2, 2021 03:32
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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