Google Script - DriveApp.getFilesByName - Error (N

2019-06-02 22:07发布

I'm trying to call custom function pdfFile from Google Spreadsheets.

function pdfFile(number, revision) {
  // Log the name of every file in the user's Drive.
  Logger.log(number + '_R' + revision + '.pdf');

  var files = DriveApp.getFilesByName(number + '_R' + revision + '.pdf');
  while (files.hasNext()) {
    var file = files.next();
    //var name = file.getName();
    var id = file.getId();
    Logger.log(file.getName() + '|' + file.getId());

    //Return link to PDF file
    return '=HYPERLINK("https://docs.google.com/file/d/'+id+'/edit?usp=drivesdk";"PDF")';
  }
}

It works when I test it in Script Editor manually.

function test_pdfFile() {
  var range = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange("D2:E2");

  // Returns cell
  var number = range.getCell(1, 1).getValue();
  var revision = range.getCell(1, 2).getValue();

  result = pdfFile(number, revision);
  Logger.log(result);
}

But, when I use custom formula in Spreadsheet, error "You don't have permission to call function DriveApp.getFilesByName (row 5)" comes. I have already switched on Drive API in Resources->Additional Google Functions and in Developer Console. Please, find attached images (sorry, text in Russian). Please, help.

2条回答
神经病院院长
2楼-- · 2019-06-02 22:26

My solution is:
1. create a menu inside onOpen(): SpreadsheetApp.getUi().createMenu('MenuName').addItem('FooName', 'fooFunction').addToUi(); the code generates a 'FooName' menu and makes it corresponding to fooFunction().
2. in fooFunction() or later, call getFilesByName().

Here is my assumption: getFilesByName() is allowed or only allowed when you are generating a new menu or sidebar. It has nothing to do with AuthMode. Under either authorization mode None or Limited, the script works fine.

"You can not call getFilesByName() in custom function" does not mean you can not, when you create a menu and call it from the menu, it is possible then.

The following are other ways I have tried before:
1. use onInstall(), which was proven useless for this problem.
2. call getFilesByName() inside onInstall() or onOpen(), which is not essential.

Some other useful links:
When you are testing your script as an add-on, check the difference between installed and enabled:
https://developers.google.com/apps-script/add-ons/lifecycle#installed_versus_enabled

AuthMode for onInstall():
https://developers.google.com/apps-script/guides/menus

查看更多
太酷不给撩
3楼-- · 2019-06-02 22:42

If your custom function throws the error message You do not have permission to call X service., the service requires user authorization and thus cannot be used in a custom function.

Check this documentation for more details.

Hope that helps!

查看更多
登录 后发表回答