【问题标题】:Google Sheets scripts: How do I include a formula in a new row that references cells in that new row?Google 表格脚本:如何在新行中包含引用该新行中单元格的公式?
【发布时间】:2019-09-27 11:42:41
【问题描述】:

我正在尝试编写一个脚本,该脚本将添加一个新行,其中包含一个引用该新行中单元格的公式。在新行中,A 列将是我开始的时间,B 列是我完成的时间,C 列将是 B - A 给出持续时间。我认为对于大多数阅读本文的人来说这应该是相当简单的,但是我看过的所有帖子都试图实​​现更复杂的结果,而我对此并不陌生。这是我的“伪代码”:

function newRow() {

  var spreadsheet = SpreadsheetApp.getActive();
  var row1 = spreadsheet.getActiveCell().getRow(); // Gets the current row number
  spreadsheet.appendRow(['00:00:00','00:00:00', "=B(row1+1)-A(row1+1)" ]); // add the new row, filling column A & B with time place holders, then in column C calculate the difference between A & B of this new row.  

}

任何答案、帮助、指导或参考以前曾问过这个问题(我只是找不到),我们将不胜感激。

【问题讨论】:

    标签: google-apps-script google-sheets google-sheets-api google-sheets-formula


    【解决方案1】:

    Sheets 有一个相对公式表示法,您可以使用它来引用相对于您要插入的单元格的单元格:

    function newRow() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var formula = '=INDIRECT("R[0]C[-1]", FALSE)-INDIRECT("R[0]C[-2]",FALSE)';
      ss.appendRow(['00:00:00', '00:00:00', formula]);
    }
    

    【讨论】:

      【解决方案2】:

      可能是这样的

      function newRow() {
        var sheet = SpreadsheetApp.getActiveSheet();
        var nextRow = sheet.getLastRow() + 1;
        var formula = Utilities.formatString('=B%s-A%s', nextRow, nextRow);
        sheet.appendRow(['00:00:00', '00:00:00', formula]);
      }
      

      还有另一种获取公式的方法

      var formula = '=B%s-A%s'.replace(/%s/g, nextRow);
      

      我都想要。

      【讨论】:

      • 所有三个解决方案都对我有用,并帮助我理解如何编写 Google Apps 脚本
      • @SimonThomson 如果您发现有用的答案,请接受它,以便将来有类似问题的其他用户也可以找到他们需要的解决方案。
      • 对不起,我是新手,我不明白勾号是一个按钮..也很遗憾我不能同时接受这两个,因为两者都很好用。因此我发表了评论。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 2022-09-24
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 2020-12-26
      相关资源
      最近更新 更多