skip to Main Content

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


  1. I’m not familiar with offise-js, but following general principles I can guess what the sheet variable have no proper value on the timer event. You need to define it globally (if possible) or get the sheet inside sendMessage.

    Login or Signup to reply.
  2. 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

    
    function sleep(seconds: number) {
    
      const millisecondDelay = seconds * 1000
      const start = Date.now()
      let now = Date.now();
    
      while((now - start) < millisecondDelay) {
        now = Date.now();
        // busy wait
        for (let i = 0; i < 1000; i++){}
      }
    
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search