Get document's URL/ID after a file was copied

蓝咒 提交于 2019-12-11 00:49:59

问题


I am trying to have the newly copied document to be updated upon completion of being copied, added to a different folder and its root file removed. The Google script is not able to find the newly copied file. The error is in the lower half of the code surrounded by asterisks with TypeError.

I suspect it has to do with the line of var doc = DocumentApp.getActiveDocument();. I am not sure how to get the URL of the newly copied document (file2 or Date - Weekly Agenda).

  function copyupdateWeeklyAgenda() {
  var file = DriveApp.getFileById("FILEKEY");
  var source_folder = DriveApp.getFolderById("FOLDERKEY");
  var dest_folder = DriveApp.getFolderById("FOLDERKEY");
  // Make a backup copy.
  var file2 = file.makeCopy('Date - Weekly Agenda');
  dest_folder.addFile(file2);
  source_folder.removeFile(file2);

//START Update Weekly Agenda Data ---
  var ssUrl = 'https://whydoyouwanttoknow.com';
  var sheetName = 'Sheet1';   // name of sheet to use
  var rangeName = 'A1:B2';    // range of values to include 
  var values = SpreadsheetApp.openByUrl(ssUrl)
                             .getSheetByName(sheetName)
                             .getRange(rangeName)
                             .getValues();
  var doc = DocumentApp.getActiveDocument();
  **var body = doc.getBody();** <--- TYPEERROR: Cannot call method "getBody" of null.
  var ranges = doc.getNamedRanges('embeddedSheet-range');
  if (ranges.length == 0) {
    var table = body.appendTable(values);
  ...ETC.

回答1:


Your file2 variable is an object of class File, because this is what File#makeCopy returns. To get the corresponding Document, use

var doc = DocumentApp.openById(file2.getId());

Remarks

  1. The method getActiveDocument refers to the Document to which the script is attached (if any). It does not mean "the thing that the script is currently handling".

  2. If you were dealing with a spreadsheet, then var ss = SpreadsheetApp.open(file2) would return the Spreadsheet contained in file2. Apparently, the API designers forgot to include the open method in DocumentApp, so we have to go through the file ID as above.



来源:https://stackoverflow.com/questions/41071264/get-documents-url-id-after-a-file-was-copied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!