如何在Google脚本中使用“OpenbyID”对多个电子表格执行操作

时间:2016-01-07 01:32:42

标签: google-apps-script

请耐心等待我,因为我是新手,但我已经在一个文件夹中列出了我在电子表格中的ID列表,该文件夹存储在1列的工作表中。我正在尝试执行一个脚本,该脚本将进入每个电子表格并删除给定名称的表格(如果它们在那里)。到目前为止,这就是我所拥有的,但我不知道我搞砸了哪里:

function cleanAllOld () {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('fileList');
  var numberFiles = sheet.getLastRow();

  for (var i=0; i<numberFiles; i++) {

    try{

// File to be cleaned
  var fileID = sheet.getRange(2+i, 1, numberFiles-1).getValues();


  var destination = SpreadsheetApp.openById(fileID[i]);
  var sheet1 = destination.getSheetByName('Copy of CALC');
  var sheet2 = destination.getSheetByName('Copy of Print');
  var sheet3 = destination.getSheetByName('Copy of Markbook');

 if (destination.sheet1 == null) {
  } else {
    destination.deleteSheet(sheet1);
  }

  if (destination.sheet2 == null) {
  } else {
    destination.deleteSheet(sheet2);
  }

  if (destination.sheet3 == null) {
  } else {
    destination.deleteSheet(sheet3);
  }

}
    catch (e) {
      Logger.log(e);
    }
}
}

固定脚本

     function cleanAllOld () {

  var ss = SpreadsheetApp.openById('...');
  var sheet = ss.getSheetByName('fileList');
  var numberFiles = sheet.getLastRow();

  for (var i=0; i<numberFiles; i++) {

// File to be cleaned
  var fileID = sheet.getRange(1, 1, numberFiles).getValues();
 Logger.log('fileID[i][0]: ' + fileID[i][0]);       
  var destination = SpreadsheetApp.openById(fileID[i][0]);
  var sheet1 = destination.getSheetByName('Copy of CALC');
  var sheet2 = destination.getSheetByName('Copy of Print');
  var sheet3 = destination.getSheetByName('Copy of Markbook');

 if (sheet1 === null) {
  } else {
    destination.deleteSheet(sheet1);
  }

  if (sheet2 === null) {
  } else {
    destination.deleteSheet(sheet2);
  }

  if (sheet3 === null) {
  } else {
    destination.deleteSheet(sheet3);
  } 

}
}

2 个答案:

答案 0 :(得分:0)

getValues()方法返回二维数组。您收到错误信息来自:

var destination = SpreadsheetApp.openById(fileID[i])

尝试使用:

var destination = SpreadsheetApp.openById(fileID[i][0])

添加第二个索引为零。

答案 1 :(得分:0)

解决了这个问题,我在下面用粗线加了

  function cleanAllOld () {

  var ss = SpreadsheetApp.openById('...');
  var sheet = ss.getSheetByName('fileList');
  var numberFiles = sheet.getLastRow();

  for (var i=0; i<numberFiles; i++) {

// File to be cleaned
  **var fileID = sheet.getRange(1, 1, numberFiles).getValues();**
 Logger.log('fileID[i][0]: ' + fileID[i][0]);       
  var destination = SpreadsheetApp.openById(fileID[i][0]);
  var sheet1 = destination.getSheetByName('Copy of CALC');
  var sheet2 = destination.getSheetByName('Copy of Print');
  var sheet3 = destination.getSheetByName('Copy of Markbook');

 if (sheet1 === null) {
  } else {
    destination.deleteSheet(sheet1);
  }

  if (sheet2 === null) {
  } else {
    destination.deleteSheet(sheet2);
  }

  if (sheet3 === null) {
  } else {
    destination.deleteSheet(sheet3);
  } 

}
}