Search code examples
google-apps-scriptgoogle-sheetsruntime-errorgoogle-sheets-api

Google Apps Script runs out of time when I try to access spreadsheet using openByUrl() or openById()?


I am trying to get data of 2 columns (B, C) from one spreadsheet and paste it into another spreadsheet. It was working perfectly before yesterday. But for the past 2 days the script is running out of time and crashing without copying values. Sometimes it runs successfully but only gets the first 1000 rows of a total of 12000 rows of data. Here is the script:

function importRangeV1(sourceURL, sourceRange, destinationURL, sheetName){

  var sourceSS = SpreadsheetApp.openByUrl(sourceURL);
  var sourceRng = sourceSS.getRange(sourceRange)
  var sourceVals = sourceRng.getValues();

 
   SpreadsheetApp.flush();
  var destinationSS = SpreadsheetApp.openByUrl(destinationURL);
  var destSheet = destinationSS.getSheetByName(sheetName);
  destSheet.clearContents();

  var destRange = destSheet.getRange(1,1,sourceVals.length,sourceVals[0].length);
  destRange.setValues(sourceVals);  
}

Now the following 2 statements in the above code are similar in terms of working:

   var sourceSS = SpreadsheetApp.openByUrl(sourceURL);
   var destinationSS = SpreadsheetApp.openByUrl(destinationURL);

However, the issue arises in this statement:

var destinationSS = SpreadsheetApp.openByUrl(destinationURL);

This statement takes so much time that the script throws the following error:

“Service Spreadsheets timed out while accessing spreadsheet with id [spreadsheet id here]”

Here is the link to the destinationURL: https://docs.google.com/spreadsheets/d/1T-vbfHdCNqULCY4voyxdPhR0v_EIxTsQZszfn9mWJ9Y/edit?usp=sharing

Here is how I run this script in the sheet:

enter image description here

I found this question somewhat similar to my issue but it does not address openByUrl() or openById(), any help in this regard would be much appreciated.


Solution

  • It seems your sheet is heavily loaded with formulas or data which is the main cause of this issue, I had the same issue with one of my sheets so how about this one for a solution:

        function importRangeV1(sourceURL, sourceRange, destinationURL, sheetName){
           
         var sourceId = sourceURL.match(/\/d\/(.+)\//)[1];      //extract id from url
         var destId =   destinationURL.match(/\/d\/(.+)\//)[1]; //extract id from url
        
         var any = {};
         var srcValues = Sheets.Spreadsheets.Values.get(sourceId, sourceRange).values;
         Sheets.Spreadsheets.Values.clear(any,destId,sheetName+"!A1:B");
         Sheets.Spreadsheets.Values.update({values: srcValues}, destId, sheetName, {valueInputOption: "USER_ENTERED"});
    };
    

    This script uses Sheets API instead of openByUrl() to access the required sheet and put the data in the specified range. Test it and let me know.