Home > Software design >  How can I include a cell reference in a searchFolders function?
How can I include a cell reference in a searchFolders function?

Time:12-01

I'm attempting to search for folders that contain a text string which is located in a specific cell in my spreadsheet, and then return the folder ID. This code works fine other than my folderID line.

Here is the code: `

function getFilesAndFolders() {
  var folderName = SpreadsheetApp.getActiveSheet().getRange(2,1).getValue();
  var folderID = DriveApp.searchFolders("title contains" folderName).next().getId();
  var file = DriveApp.getFolderById(folderID).getFilesByName("app.csv");
  var contents = Utilities.parseCsv(file.next().getBlob().getDataAsString());
  var sheetName = writeDataToSheet(contents);
  var home = SpreadsheetApp.getActive().getSheetByName("Manage");
  home.activate();
}

`

I've tried a few variations of the searchFolders query but it keeps returning errors.

CodePudding user response:

Modification points:

  • In the case of the search query of DriveApp.searchFolders, please enclose the search value of contains by the single quotes and/or the double quotes.

  • In your script, DriveApp.searchFolders("title contains" folderName).next() is the Class Folder object.

When these points are reflected in your script, how about the following modification?

Modified script:

function getFilesAndFolders() {
  var folderName = SpreadsheetApp.getActiveSheet().getRange(2, 1).getValue();
  var folder = DriveApp.searchFolders("title contains '"   folderName   "'"); // or var folder = DriveApp.searchFolders(`title contains '${folderName}'`);
  if (folder.hasNext()) {
    var file = folder.next().getFilesByName("app.csv");
    var contents = Utilities.parseCsv(file.next().getBlob().getDataAsString());
    var sheetName = writeDataToSheet(contents);
    var home = SpreadsheetApp.getActive().getSheetByName("Manage");
    home.activate();
  }
}
  • In your script, it seems that sheetName is not used.

Reference:

  • Related