I want to recalculate an Excel worksheet every 1 second using Office Script. Here is my failed attempt.
function sendMessage(sheet: ExcelScript.Worksheet) {
console.log('hi');
sheet.calculate(true);
}
function main(workbook: ExcelScript.Workbook) {
let sheet = workbook.getActiveWorksheet();
setInterval(sendMessage, 1000, sheet);
}
Nothing printed at the console and there is no recalculation.
2
Answers
I’m not familiar with
offise-js
, but following general principles I can guess what thesheet
variable have no proper value on the timer event. You need to define it globally (if possible) or get the sheet insidesendMessage
.I helped develop the Office Script runtime.
Generally, Office Scripts are designed to execute a sequence of steps and complete. i.e. Office Scripts aren’t designed to continually run in the background.
Currently
setInterval
won’t work due to how Office Scripts are executed, additionally only a single Office Script can execute at a time.Generally, I wouldn’t recommend continually running an Office Script (the runtime isn’t designed to support it).
That said,
I have used busy waiting in the past to create a delay, which you could use to pause between calls. See
sleep
function below:https://github.com/wandyezj/office-script/blob/main/functions/sleep.ts