Google Apps脚本神秘地停止for for循环

时间:2018-05-18 16:05:04

标签: google-apps-script

我正在建立一个系统,用于将数据从一张纸复制到另一张纸(在不同的电子表格中)。它运行良好,直到它应该复制数据。之后,它什么也没做。不会引发任何错误,但for循环中不会弹出警告框。这是我的代码:

function onEdit() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var master = SpreadsheetApp.openById('13x7AvyYTaocCVBxVZ3ckBjzgxcZfjg9RYM1cE_0VNbU');
  var sheets = master.getSheets();
  var test = DriveApp.createFile('Test', 'fetching user data...');
  var name = test.getOwner().getName();
  test.setTrashed(true);
  var add = true;
  for (var i = 0, n; i < sheets.length; i++) {
    n = sheets[i];
    if (n.getName() == name) {
      add = false;
      updateSheet(n, name);
    }
  }
  if (add) {
    newSheet(master, name);
  }
}

function updateSheet(m, name) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn());
  var nr = range.getNumRows();
  var nc = range.getNumColumns();
  for (var i = 1; i <= nr.length; i++) {
    for (var n = 1, s; n <= nc.length; n++) {
      s = range.getCell(i, n);
      m.getRange(i, n).getCell(1, 1).setValue(s.getValue());
    }
  }
}

function newSheet(master, name) {
  var m = master.insertSheet(name);
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn());
  var nr = range.getNumRows();
  var nc = range.getNumColumns();
  for (var i = 1; i <= nr.length; i++) {
    for (var n = 1, s; n <= nc.length; n++) {
      s = range.getCell(i, n);
      m.getRange(i, n).getCell(1, 1).setValue(s.getValue());
    }
  }
}

我搜索了代码,但找不到任何错误。

2 个答案:

答案 0 :(得分:1)

https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#insertsheetsheetname的Google文档中,它说......

insertSheet(sheetName)

使用给定名称将新工作表插入电子表格中。 新工作表成为活动工作表。

在您的代码中

function newSheet(master, name) {
  var m = master.insertSheet(name);  // after calling this function m becomes the active sheet
  var sheet = SpreadsheetApp.getActiveSheet();  // you've assigned m to sheet

我建议使用getSheetByName('SheetName')。

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SheetName");

请参阅此链接https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getsheetbynamename

答案 1 :(得分:1)

明显的答案(谢谢@Rubén)

for循环中,它显示nc.lengthnr.lengthgetNumRowsgetNumColumns都会返回数字。由于这些是整数,因此不需要.length