如何确保一个变量总是在Google工作表中指向相同的范围(而不是相同的地址)



我想给一个变量分配一个范围,然后设置它的一些单元格,即使在此期间,由于一些行/列插入/删除,它的地址已经改变。

在下面的代码片段中,即使我需要写入两个不同的行,即第一个创建的行和第二个创建的行,也将字符串写入同一行。

function addingRows() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var r1=sheet.getRange("1:1")
sheet.insertRowBefore(1);
// now r1 continue to refer to the first row even if it has became the second one!
var r2=sheet.getRange("1:1")
// I want to write on the second row (the first row that shifted one row below due to the row insertion) 
// but the following line writes to the first row!
r1.getCell(1,1).setValue("first created row")
// the following line writes to the first row as expected
r2.getCell(1,2).setValue("second created row")
}

换句话说,我想写"第一个创建的行"在先前的第一行中,在插入行之后成为第二行,但似乎变量r1甚至在插入行之后指向第一行。

怎么做?

function addingRows() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getActiveSheet();
const r1 = sh.getRange("1:1")
let n = 0;
sh.insertRowBefore(1);
n++;
const r2 = sh.getRange("1:1")
r1.getCell(n + 1, 1).setValue("first created row")
}

最新更新