Google Apps 脚本中的 try/catch 语句后 setValues 不工作

setValues not working after try/catch statement in Google Apps Script

我的 Google Apps 脚本代码找到一个特定的 sheet,如果它不存在则创建它;然后它在 header 下面添加了一行新数据。当它必须创建一个新的 sheet 时,我想设置 header 行,但它不会在它应该的地方工作,我不明白为什么。此代码按原样工作,但您可以看到我想将我的代码行移到哪里。感谢任何帮助。

// for each work order
for (var i = headerCount; i < data.length; i++) {
  var workOrder = data[i][workOrderColumn];
  var inspector = data[i][inspectorColumn];

  // find or create sheet in logSpreadsheet
  var logSheet = logSpreadsheet.getSheetByName(workOrder);
  if(logSheet == null) {

    try {
      logSheet = logSpreadsheet.insertSheet(workOrder);
    } catch(e) {
      Logger.log(e);
      continue;
    }

    //This is where I want this line to be, but it doesn't work here:
    //logSheet.getRange("A1:B1").setValues([["Date", "Inspector"]]);
  }

  // log data
  logSheet.insertRows(1);
  logSheet.setFrozenRows(1);

  //Here, the code works, but it shouldn't be here (it only needs to happen when the sheet is created)
  logSheet.getRange("A1:B1").setValues([["Date", "Inspector"]]);
  logSheet.getRange("A2:B2").setValues([[date, inspector]]);
}

试试这个

if(logSheet == null) {

    try {
      logSheet = logSpreadsheet.insertSheet('testsheet');
    } catch(e) {
      Logger.log(e);
    }

    // then create the header
    logSheet.setFrozenRows(1);
    logSheet.getRange("A1:B1").setValues([["Date", "Inspector"]]);
  } 
  // then, just add the data starting at row 2. Row 1 is the header
  logSheet.insertRows(2);
  logSheet.getRange("A2:B2").setValues([[Date, Inspector]]);

你的代码不工作的原因是因为这组情况。

logSheet.getRange("A1:B1").setValues([["Date", "Inspector"]]);
//The above line adds the header to row one
logSheet.insertRows(1);
//The above code inserts a new line at row 1
//That so header line is effectively in row 2 ("A2:B2")

所以稍后在代码中,当您像这样设置 ("A2:B2") 的值时

logSheet.getRange("A2:B2").setValues([[date, inspector]]);

in 覆盖 header 值。

我会做如下修改

logSheet.insertRows(2); // or remove this code

您的最终代码:

for (var i = headerCount; i < data.length; i++) {
  var workOrder = data[i][workOrderColumn];
  var inspector = data[i][inspectorColumn];

  // find or create sheet in logSpreadsheet
  var logSheet = logSpreadsheet.getSheetByName(workOrder);
  if(logSheet == null) {

    try {
      logSheet = logSpreadsheet.insertSheet(workOrder);
    } catch(e) {
      Logger.log(e);
      continue;
    }

    logSheet.getRange("A1:B1").setValues([["Date", "Inspector"]]);
    logSheet.setFrozenRows(1);
  }

  logSheet.insertRows(2);


  //Here, the code works, but it shouldn't be here (it only needs to happen when the sheet is created)
  //logSheet.getRange("A1:B1").setValues([["Date", "Inspector"]]);
  logSheet.getRange("A2:B2").setValues([[date, inspector]]);
}