简体   繁体   中英

Google Sheets scripts: How do I include a formula in a new row that references cells in that new row?

I'm trying to write a script that will add a new row with a formula in it that references cells in that new row. In the new row column A will be the time I start, Column B the time I finish and Column C will be B - A to give the duration. I presume this should be fairly simple for most people reading this, but all the posts I've looked at are trying to achieve more complex outcomes and I'm new at this. Here's my "pseudo code":

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.  

}

Any answers, help, guidance or reference to where this has been asked before (I just can't find it) would be appreciated.

Maybe something like this

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]);
}

There is another way to get the formula

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

I'd like both.

Sheets has a relative formula notation which you can use to reference cells relative to the one you're insering into:

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM