DriveApp.getFileById() throwing a server error [duplicate] - google-apps-script

This question already has answers here:
DriveApp Error: "We're sorry, a server error occurred. Please wait a bit and try again."
(4 answers)
Closed 1 year ago.
I have a script that I am using to export a google sheet to a PDF. It has been working no problem up until now. I deployed it as a Web App so that it could be used by anyone. Since I deployed it, it has not worked. I tried archiving the Web App and that did not help.
The issue seems to be with the DriveApp.getFileById() function. I inserted numerous console.log() functions along the way of my code to try to narrow down where it actually fails and why. The execution log shows that the error is happening at the same spot that I derived, but the console.log() functions did not help me figure out why. The error I receive is:
Exception: We're sorry, a server error occurred. Please wait a bit and try again.
I have tried researching this for quite some time now, and have tried suggestions that I found. I double checked all my variables and code syntax. I also know that the pdfid is being pulled correctly, as verified by logging it. I have not altered this part of the code, or any part that it depends on, at all since it has been working. I believe the Web App deployment is the issue, but I'm not sure why or how I could fix it. It could also be something else I'm missing, as it still does not work even after archiving the Web App.
Here is the code, the last line shown is where it fails:
function exportLog(type) {
console.log('Starting Export');
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var realExp = sheet.getSheetByName('exportThis');
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export");
//console.log('Spreadsheet created');
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var sheet = realExp.copyTo(newSpreadsheet);
//console.log('Copied');
SpreadsheetApp.getActiveSpreadsheet().toast('Beginning export...','Loading...',-1);
//console.log('using new sheet');
newSpreadsheet.getSheetByName('Copy of exportThis').showSheet();
//console.log('successfully used new sheet');
newSpreadsheet.getSheetByName('Sheet1').activate();
newSpreadsheet.deleteActiveSheet();
//console.log('deleted');
var pdfid = newSpreadsheet.getId();
console.log(pdfid); // Correctly logs ID
var pdf = DriveApp.getFileById(pdfid);

function exportLog(type) {
const ss1 = SpreadsheetApp.getActive();//this returns the active spreadsheet
const xsh = ss1.getSheetByName('exportThis');
const ss2 = SpreadsheetApp.create("Spreadsheet to export");
const nsh = xsh.copyTo(ss2);
nsh.showSheet();//you can't really show the sheet because ss2 is not the active spreadsheet
ss2.getSheetByName('Sheet1').activate();//again you can't activate this sheet because ss2 is not the active spreadsheet
ss2.deleteActiveSheet();//This is not the active spreadsheet
const pdfid = ss2.getId();//I don't know why you call this a pdf it's a spreadsheet
const pdf = DriveApp.getFileById(pdfid); //again ss2 is a newly created spreadsheet
}
//Input parameter is never used
You should get in the habit of referring to the documentation while you write your code and pay special attention to the types that are returned by methods.

Related

Google Apps Script copies spreadsheet every time I run the script

I'm trying to write a script that executes a function every time I open the spreadsheet the script is linked to.
But now every time I run the function, a copy of the spreadsheet is created and that definitely shouldn't happen.
I'm not sure if it might have to do with the triggers or type of deployment I set. I put a screenshot of the trigger here.
As the type of deployment I put web app.
The code in the script is pretty simple because I didn't want to go forward yet when the error is still happening. It looks like this:
function mediaplan() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s_week = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Quick view - Week");
var s_month = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Quick view - Month");
var test = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test");
var currentWeek = Utilities.formatDate(new Date(), "GMT", "w");
console.log(currentWeek);
}
It would be great if someone could tell me what I did wrong or if it's an error by Google.
Thanks in advance!

TypeError: Cannot read property 'getSheetByName' of null

Looking for some help with a code in script app. I'm using the below code to get data from one sheet and then put it in the last row of another sheet. Both sheets are in the same workbook. I'm taking a monthly snap shot of a budget, so I have a historical view. The code runs when I manually 'run' it, however when I set up an automatic trigger I get the following error message TypeError: Cannot read property 'getSheetByName' of null at recordVariancesHistory(Variances script:3:19)
I have the same code set up in another spreadsheet and the trigger takes a snap shot each month without issue. I can't figure out what's different in this spreadsheet.
function recordVariancesHistory() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheetByName('ForMaster');
var sheet2 = ss.getSheetByName('Variances History');
var data = sheet1.getRange('z84:Af87').getValues();
var last_row = sheet2.getLastRow();
sheet2.getRange(last_row + 1,1,4,7 ).setValues(data);
}
Any help would be greatly appreciated.
Change getActiveSpreadsheet to openByUrl or openById. If you need dynamical search file, use DriveApp in order to find it.

Apps Script (Error Exception: The document is inaccessible. Please try again later. Creator # Code.gs:10)

I wrote a script to automatically create and fill in the required fields in the file, but an error
Error Exception: The document is inaccessible. Please try again later. Creator # Код.gs:10
Please look at the code, tell me where I was wrong.
function Creator() {
const docFile = DriveApp.getFileById("1DhHBAd3ssYMgbbxJatK6_URxBPdoPk2K");
const tempFolder = DriveApp.getFolderById("16keE-_Dm0gglO42Lw0IphiPHYK-_TFXH");
const pdfFolder = DriveApp.getFolderById("1ZsmW9UPNaqgjt8kFh3y9h8tdBLAtj7gC");
const tempFile = docFile.makeCopy(tempFolder);
const tempDocFile = DocumentApp.openById(tempFile.getId());
const body = tempDocFile.getBody();
var list = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var l=list.getLastRow();
for (var i=2; i <= l; i++) {
var a1 = list.getRange(i, 3).getValue();
var a2 = list.getRange(i, 4).getValue();
body.replaceText("{ПІБ}", a1);
body.replaceText("{Назва структури}", a2);
tempDocFile.saveAndClose();
const pdfFile = tempDocFile.getAs(MimeType.PDF);
pdfFolder.createFile(pdfFile).setName(a1);
tempFolder.removeFile(tempFile);
}
}
Assuming that the code line having the error is
var l=list.getLastRow();
It's very likely that you faced a Google environment glitch (I have faced the same error this weekend). In situations like this there is nothing else to do than to wait a bit and try again.
If you are developing a script / add-on / web-app to be used by others or you would like to handle this automatically you could use an algorithm like exponential backoff
If the error occurred on the previous code lines calling the Document Service, the problem might be caused for trying to open non Google Document file i.e. Microsoft Word file (.docx). In this case you should first convert the file to Google Document format and use the converted document instead of the original.
Related
Error message: "Cannot connect to Gmail" (Google services having glitches)
Google Script Document Inaccessible Error - creating and attempting to open document in code
Exception: The document is inaccessible. Please try again later. Google Scripts
Resources
Scripts implementing the exponential backoff algorithm in Google Apps Script
https://gist.github.com/peterherrmann/2700284
https://github.com/RomainVialard/ErrorHandler

Google sheets appscript to copy tabs to new sheets

I have a google sheet with around 190 tabs on that i need to split into 190 different files
The files need to be named the same as the tab, the contents of the tab need to be copied as values but i also need to bring the formatting accross (just not the formulas).
I have looked around, and through a combination of previous questions and answers plus using the function list help have formed the following code. It actually works for the first few tabs but then throws up an error about being unable to delete the only sheet.
function copySheetsToSS() {
var ss = SpreadsheetApp.getActive();
for(var n in ss.getSheets()){
var sheet = ss.getSheets()[n];// look at every sheet in spreadsheet
var name = sheet.getName();//get name
if(name != 'master' && name != 'test'){ // exclude some names
var alreadyExist = DriveApp.getFilesByName(name);// check if already there
while(alreadyExist.hasNext()){
alreadyExist.next().setTrashed(true);// delete all files with this name
}
var copy = SpreadsheetApp.create(name);// create the copy
sheet.copyTo(copy);
copy.deleteSheet(copy.getSheets()[0]);// remove original "Sheet1"
copy.getSheets()[0].setName(name);// rename first sheet to same name as SS
var target_sheet = copy.getSheetByName(name);
var source_range = sheet.getRange("A1:M50");
var target_range = target_sheet.getRange("A1:M50");
var values = source_range.getValues();
target_range.setValues(values);
}
}
}
I am hoping someone can tell me what i have done wrong as I cannot figure it out at this point. I am also open to better solutions though please be aware I am very much a beginner on google appscript, nothing too complex please.
thankyou
In principle your script correctly adds a new sheet to the new spreadsheet before removing the preexisting one
However, mind that calls to service such as SpreadsheetApp are asynchronous.
And this becomes the more noticeable, the longer your script runs.
In your case it apparently leads to behavior that the only sheet is being deleted before the new sheet is being created.
To avoid this, you can force the execution to be synchronous by implementing calls to SpreadsheetApp.flush().
This will ensure that the old sheet won't be deleted before the new one gets inserted.
Sample:
copy.deleteSheet(copy.getSheets()[0]);// remove original "Sheet1"
SpreadsheetApp.flush();
copy.getSheets()[0].setName(name);
You might want to introduce call toflush()` also at other positions where it is important for the code to run synchronously.

Changing the active range to a newly generated sheet causing error

Receiving the error,
ReferenceError: "setActiveSelection" is not defined.
Using Google Apps Script on Google Sheets. With this function, I'm wanting to create a new sheet tab on the same workbook using a template from another workbook. Once the new sheet is created, I'd like to change the actively selected cell to cell 'B1'. The template is copying fine, but the error is coming from the line changing the active selection. I've also tried setActiveRange and even just setActiveSheet but they return the same error.
function newReception() {
var templateSpreadsheet = SpreadsheetApp.openById("ID Redacted");
var template = templateSpreadsheet.getSheets()[1];
var currentSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var newSheet = template.copyTo(currentSpreadsheet).setName("Untitled
Reception");
setActiveSelection(currentSpreadsheet.getSheetbyName("Untitled
Reception").getRange('B1'));
}
Please advise on a solution. Thanks!
You're getting this issue because you're running .setActiveSelection() on its own. This method is bound to sheets, so you must run it for such. See Class Sheet documentation for more details on this method.
Try defining your sheet as a variable and then running it for your new sheet variable.
var sheet = currentSpreadsheet.getSheetbyName("Untitled Reception");
sheet.setActiveSelection('B1');