将 1 加到两列的每一行中的每个单元格,直到达到空白单元格 - Google 电子表格

Add 1 to each cell in every row of two columns until a blank cell is reached - Google Spreadsheet

我要做的就是将 1 加到一系列单元格中,直到它到达一个空白单元格。我也从另一个单元格范围减去 1,直到它到达一个空白单元格。我目前已经对每个单元格进行了单独编码,但是具有变化的数据的单元格数量并不实用。

这是我编写的代码的摘录,有人可以帮助我吗?

function Calculations() {
  //Week Number & Week Pay
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  s=SpreadsheetApp.setActiveSheet(spreadsheet.getSheetByName("Money")

  var currVal=s.getRange("C2").getValue()
  var plusVal= currVal +1
  s.getRange("C2") .setValue(plusVal)
  var currVal=s.getRange("B2").getValue()
  var minusVal= currVal -1
  s.getRange("B2") .setValue(minusVal)

  var currVal=s.getRange("C3").getValue()
  var plusVal= currVal +1
  s.getRange("C3") .setValue(plusVal)
  var currVal=s.getRange("B3").getValue()
  var minusVal= currVal -1
  s.getRange("B3") .setValue(minusVal)

  var currVal=s.getRange("C4").getValue()
  var plusVal= currVal +1
  s.getRange("C4") .setValue(plusVal)
  var currVal=s.getRange("B4").getValue()
  var minusVal= currVal -1
  s.getRange("B4") .setValue(minusVal)
}

我发现在获取单元格位置(范围)时只使用数字更容易,而不是使用 A1 或 R1C1 表示法。

在循环结束时增加行号。循环将迭代最大行数的数据,如果找到空单元格,它将中断。

function Calculations() {
try{
  //Week Number & Week Pay
  var currVal,i,L,lastRow,minusVal,plusVal,ss,sh,theColumn,theRng,theRow;

  ss = SpreadsheetApp.getActiveSpreadsheet();//Get the active spreadsheet
  sh = ss.getSheetByName("Money");//Get a sheet tab by name
  lastRow = sh.getLastRow();//Get the number of the last row with data

  L = lastRow;
  theRow = 2;//Start in row 2

  for (i=0;i<L;i++) {//Loop as many times as there is number of rows with data
    theColumn = 3;//Column C

    theRng = sh.getRange(theRow,theColumn);//Get the range which is one cell

    currVal = theRng.getValue();//Get the value in one cell
    //Logger.log('currVal: ' + currVal);

    if (!currVal) {//If there is a blank cell then
      break;//quit the loop
    }

    plusVal= currVal +1;
    theRng.setValue(plusVal);

    theColumn = 2;//Column B

    theRng = sh.getRange(theRow,theColumn);

    currVal = theRng.getValue();
    minusVal = currVal - 1;
    theRng.setValue(minusVal);

    if (!currVal) {//If there is a blank cell then
      break;//quit the loop
    }

    theRow = theRow + 1;//Increment to the next row
  }

}catch(e) {
  Logger.log('message: ' + e.message);
  Logger.log('stack: ' + e.stack);
}
}