Apps 脚本 Google Sheet 通过睡眠改变单元格颜色

Lle*_*e.4 1 google-sheets google-apps-script

我希望能够在运行脚本时向用户展示电子表格中的一种“动画”形式,通过在脚本中发生不同的操作时更改单元格颜色。举一个简单的示例,打开一个空白电子表格并运行以下命令:

function test()
{
  let sheet = SpreadsheetApp.getActiveSheet();
  let cell = sheet.getRange('A1');
  cell.setBackground('red');
  // Perform some action here; e.g. increment cell value
  sleep(1000);
  cell.setBackground('green');
  // Perform some other action here; e.g. multiple cell value by 2
  sleep(1000);
  cell.setBackground('white');
}


function sleep(milliseconds)
{
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}
Run Code Online (Sandbox Code Playgroud)

(我在 StackOverflow 上得到了该函数的建议sleep。)但是,当您运行此函数时,如果您在运行时观看电子表格,颜色实际上不会改变 - 它只是将其设置为最终颜色。有没有办法让这些睡眠功能显示颜色闪烁?我应该使用其他睡眠功能吗?任何帮助将不胜感激; 谢谢你!

小智 6

谷歌正试图变得聪明并跳过不必要的读/写。您需要告诉谷歌在每次更新之间更新工作表。

    SpreadsheetApp.flush();
    sleep(1000)
    SpreadsheetApp.flush();
Run Code Online (Sandbox Code Playgroud)

这应该能让你的颜色发挥作用。