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

时间:2018-05-26 08:40:45

标签: javascript google-apps-script google-sheets do-loops

我要做的就是在一系列细胞中加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)
}

1 个答案:

答案 0 :(得分:0)

我没有使用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);
}
}