javascript - 在谷歌应用程序脚本中错误地声明当前单元格变量

标签 javascript google-apps-script google-sheets

我在 Google 表格中编写公式以实现从 Google 表单输入数据的自动化方面非常有经验。

我现在正在尝试通过学习 Apps 脚本来在此基础上进行构建。我正在尝试编写一个脚本,它将

  1. 打开工作表时启动
  2. 在后台持续运行,检查当前单元格是否为A1。 (我正在尝试使用 while 循环来实现这一点,因为条件始终为真。)
  3. 删除F1的内容

目前,无论哪个单元格处于事件状态,代码都会运行。通过调试我认为这是因为 if 语句写得不正确,而且变量 CurrentCell 没有正确声明。

这是我目前拥有的代码:

    function DeleteCell() {
 var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var num1 = 1


  // run the following loop
  do {


    // add 1 to num1
    num1++;

var CurrentCell = sheet.getCurrentCell();    
    // if the current cell is A1
    if(CurrentCell==1,1)
       {

  sheet.getCurrentCell().offset(0, 5, 1, 1).activate();
  sheet.getActiveRangeList().clear({contentsOnly: true, skipFilteredRows: true});
  var CurrentCell = sheet.getCurrentCell()
       }

  }while (num1 > 5); // continue running the loop while num1 is greater than five


};

最佳答案

也许这就是想要的意思:

function clearRange() {
  var ss=SpreadsheetApp.getActive();
  var sheet=ss.getActiveSheet();
  var num1=1;
  do {
    num1++;
    var CurrentCell=sheet.getCurrentCell();//Current cell is a range    
    if(CurrentCell.getA1Notation()=='A1') {
      sheet.getCurrentCell().offset(0, 5, 1, 1).clear({contentsOnly: true, skipFilteredRows: true});
    }
  }while(num1<5);
}

不幸的是,它不会在后台运行,如果您让它运行,它会在某个时刻超时,并且它运行的超时时间将从您的每日配额中扣除。

我不确定您想要完成什么,但我的猜测是使用 onEdit 触发器可能会更好。

triggers

在大多数脚本中使用 activate 的理由并不多。他们在宏中使用它们,因为它们本质上遵循您所采取的每一步。当您运行脚本时,您实际上并不想在每个步骤之间停止,如果您这样做,您可以通过模式对话框更好地通知用户。

关于javascript - 在谷歌应用程序脚本中错误地声明当前单元格变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59938583/

相关文章:

javascript - 为什么显示所有表格行?

javascript - 使用 JavaScript 的罗马数字转换器

javascript - 在maven Spark java应用程序中运行html文件

javascript - 如何使用 Google Apps 脚本列出云端硬盘中非 "google"mime 类型的所有文件?

google-sheets - 添加新行时,Google 表格条件格式会发生变化

google-docs - 通过 Google Docs 或 Spreadsheet API 将新工作表添加到 Google 电子表格

javascript - Slick Slider 在开始时转到第 n 个 slider

javascript - Google 脚本 - 仅从字符串创建 HtmlOutput? (即将字符串转换为 html)

javascript - file.getOwner() 返回 'DriveUser' 值而不是谷歌应用程序脚本中文件的实际所有者

regex - 从数据中提取所需的结果