Search code examples
google-apps-scriptgoogle-sheetsgoogle-apps

Google code does not work


I am new to Google Apps Script programming. Recently, I had tried to follow this tutorial by Google but it looks like their code is outdated. However, I would still like to do what the tutorial does except that it will now search for files in Google Drive.

The following is my code:

function onOpen() {
    var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var searchMenuEntries = [
        {
            name: "Search in all files",
            functionName: "search"
        }
    ];
    spreadsheet.addMenu("Search Document", searchMenuEntries);
}

function search() {
    // Prompt the user for a search term
    var searchTerm = Browser.inputBox("Enter the string to search for:");

    // Get the active sheet
    var sheet = SpreadsheetApp.getActiveSheet();

    // Set up the spreadsheet to display the results
    var headers = [
        ["File Name",
         "File Type",
         "URL"
        ]
    ];
    sheet.clear();
    sheet.getRange("A1:C1").setValues(headers);

    // Search the files in the user's Drive for the search term
    var files = DriveApp.getFilesByName(searchTerm);

    // Loop through the results and display the file name, file type, and URL
    var i = 0;
    while (files.hasNext()) {
        files = files.next();
        sheet.getRange(i+2, 1, 1, 1).setValue(files.getName());
        sheet.getRange(i+2, 2, 1, 1).setValue(files.getMimeType());
        sheet.getRange(i+2, 3, 1, 1).setValue(files.getDownloadUrl());
        i++;
    }
}

When I tried to run the code, there were no major errors that gave me a warning. However, the code does not work and the output in Google Sheets is as follow:

+---------------+----------------+----------------+
| File name     | File type      | URL            |
+---------------+----------------+----------------+
|               |                |                |
+---------------+----------------+----------------+

even though I am quite sure that there are file matches in my Drive. I tried to debug the code but the while loop does not seem to be executing. Any help would be appreciated!


Solution

  • There were a few typos in this code, I don't know where / how you did copy it... here is the working code (see comments in code):

    function onOpen() {
        var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
        var searchMenuEntries = [
            {
                name: "Search in all files",
                functionName: "search"
            }
        ];
        spreadsheet.addMenu("Search Document", searchMenuEntries);
    }
    
    function search() {
        // Prompt the user for a search term
        var searchTerm = Browser.inputBox("Enter the string to search for:");
    
        // Get the active sheet
        var sheet = SpreadsheetApp.getActiveSheet();
    
        // Set up the spreadsheet to display the results
        var headers = [
            ["File Name",
             "File Type",
             "URL"
            ]
        ];
        sheet.clear();
        sheet.getRange("A1:C1").setValues(headers);
    
        // Search the files in the user's Drive for the search term
        var files = DriveApp.getFilesByName(searchTerm);
    
        // Loop through the results and display the file name, file type, and URL
        var i = 0;
        while (files.hasNext()) { // files is the iterator
            var file = files.next();// file is the drive document object
            sheet.getRange(i+2, 1, 1, 1).setValue(file.getName());// file is the drive document object
            sheet.getRange(i+2, 2, 1, 1).setValue(file.getMimeType());// file is the drive document object
            sheet.getRange(i+2, 3, 1, 1).setValue(file.getDownloadUrl());// file is the drive document object
            i++;
        }
    }
    

    EDIT :

    By the way, this script is badly implemented, it uses API calls in a loop which is very inefficient... below is a faster version (and more compact as well)

    function search() {
      // Prompt the user for a search term
      var searchTerm = Browser.inputBox("Enter the string to search for:");
      
      // Get the active sheet
      var sheet = SpreadsheetApp.getActiveSheet();
      
      // Set up the spreadsheet to display the results
      var result = [];
      result.push(["File Name","File Type","URL"])
     // Search the files in the user's Drive for the search term
      var files = DriveApp.getFilesByName(searchTerm);
      
      // Loop through the results and display the file name, file type, and URL
      while (files.hasNext()) {
        var file = files.next();
        result.push([file.getName(),file.getMimeType(),file.getDownloadUrl()]);
      }
    sheet.getRange(1,1,result.length,result[0].length).setValues(result);
    }
    

    Note :

    to change the search criteria, just use the DriveApp.search call and add arguments as specified in the documentation.

    example to look into file content :

      var files = DriveApp.searchFiles('fullText contains "'+searchTerm+'"');