問題

我有’else if’語句,我需要只在前面的’if’不執行時呼叫它.第一個’if’(檢查狀態)工作完美,第二個工作,但每次都完成’else if’,因為表中有不同的型別(A,B,Ce.t.c)

編輯: 1. 如果沒有開啟的A,必須加上新的行; 2. 如果開放一個以上A -- -- 所有這些都必須關閉; 3. 忽略所有其他型別,只有在沒有開放的情況下才新增新行;

這是我的程式碼:

 function myFunction() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetName');
  var data = sheet.getRange(2,1,sheet.getLastRow(),2).getValues();
  var nextRow = SpreadsheetApp.getActiveSheet().getDataRange().getLastRow()+1;

  for (var i=0; i<data.length; i++){
    var row = data[i];
    var type = row[0];
    var status = row[1];

//check it always     
    if (status != 'close'){

//check first and if it's true don't do 'else if'      
       if (type == 'A') {
         sheet.getRange(i+2,2).setValue('close')
       }

//this should only be called if the previous 'if' is not true      
      else if (type != 'A' && type != ''){
        var values = [['A','open']];
        sheet.getRange("A"+nextRow+":B"+nextRow).setValues(values); 
      }
    }
  }
}
 

enter image description here

  最佳答案

流:

  • 迴圈遍歷所有資料以查詢是否有“A:開啟”
  • 如果在所有資料中找到,就關閉該行
  • 否則,新增一個新行:“A:開啟”
  • 使用布林變數(isThereASingleAOpen)來跟蹤A:打開發現狀態

示例指令碼:

 function closeAandAddOpenA() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetName');

  //Separate range and data
  var range = sheet.getRange(2, 1, sheet.getLastRow(), 2);
  var data = range.getValues();

  //Is there a A Open in the data? Let's assume there's none
  var isThereASingleAOpen = false;

  //Loop through data array
  for (var i = 0; i < data.length; i++) {
    var row = data[i];
    var type = row[0];
    var status = row[1];

    //If status is != close and type == 'A'
    if (status != 'close' && type == 'A') {
      //Change current row status to close in the data array
      row[1] = 'close';
      //Oops We were wrong. There was a A open in the data
      isThereASingleAOpen = true;
    }
  } //Loop closed

  //Set the modified data back to the range
  //Batch  operations are faster
  range.setValues(data);

  //if there is NOT a single A open in all of data, Append a new line
  if (!isThereASingleAOpen) {
    sheet.appendRow(['A', 'Open']);
  }
}
 

  相同標籤的其他問題

if-statementgoogle-apps-script