Google Apps Script copies spreadsheet every time I run the script - google-apps-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!

Related

Scripts Running Slowly

My scripts each take over a minute to run. They accept triggers from spreadsheet, so the longer they take to run, the more executions build up, and I've started getting failures due to "simultaneous invocations."
I'm running two AutoFill functions (see sample) OnChange, and one script that populates drop-down data validations OnEdit.
function accountCreationAutoFill(e){
Logger.log(e.changeType);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Account Creation Sheet")
if(e.changeType=='INSERT_ROW'){
var rules = sheet.getConditionalFormatRules();
var needsSourceRange = sheet.getRange("AccountCreationNeedsFormula")
var needsDestination = sheet.getRange("AccountCreationNeedsAutoFill")
var contactSourceRange = sheet.getRange("AccountCreationContactFormula")
var contactDestination = sheet.getRange("AccountCreationContactAutoFill")
needsSourceRange.autoFill(needsDestination, SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES)
contactSourceRange.autoFill(contactDestination,SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES)
sheet.clearConditionalFormatRules();
sheet.setConditionalFormatRules(rules);}
}
I haven't tried anything. I'm new to coding, and it took everything I have just to write the scripts and get them to work in the first place. I don't know how to troubleshoot this issue.
Combining all functions I wanted to run On Change into one script, so I'm only running one OnChange trigger, shortened average run time by 75%.

DriveApp.getFileById() throwing a server error [duplicate]

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.

Writing into another Spreadsheet with SetValue fails without errors/exceptions

I'm trying to update a spreadsheet from a script running on another spreadsheet.
Nothing seems to have any effect on the table (SetValue(), SetBackgroundRGB(), etc.).
I've checked the scope, it includes "https://www.googleapis.com/auth/spreadsheets" permission; besides, this same script has no problem writing to another spreadsheet that it creates in runtime.
function updateAnotheSpreadsheet() {
var targetSpreadsheet = SpreadsheetApp.openById('<target spreadsheet id>');
var sheet = targetSpreadsheet.getSheetByName('<sheet name>');
Browser.msgBox(sheet.getRange("A1").getValue()); // Here I see that my getSheetByName worked
sheet.getRange("A1").setValue('Test value'); // But this does nothing
}
There are no errors but also no effect: nothing changes in the target spreadsheet.
Hi I was testing and was able to do what you are trying to do. You can try to declare a variable for the message, here is what I was able to do, I hope this resolves your inquiry.
function updateAnotherSpreadsheet() {
//Opening the second Spreadsheet by ID
var targetSpreadSheet = SpreadsheetApp.openById("<SpreadSheetId>");
var sheet = targetSpreadSheet.getSheetByName("<SheetName>");
//Getting the range to show on msgBox.
var msg = sheet.getRange("A1:A1").getValue();
//Displaying old data on A1:A1 from the secondary Spreadsheet.
Browser.msgBox("Old data on secondary spreadsheet: " + msg);
//Getting the range and setting new values
sheet.getRange("A1:A1").setValue('Test value').setBackground("teal").setFontColor("white");
}
I would suggest to check for more information here https://developers.google.com/apps-script/guides/sheets.
I hope this helps, greetings.
I found the problem.
A function called from OnEdit() can't ask for permissions. I needed to first update that other spreadsheet from any function called by something "active", like a button; then, after the script asks for permission once, it can do its thing from OnEdit() the next time it runs.

Convert onEdit script to manually running script

The script has the purpose of writing the datetimestamp to a specific cell the moment when a cell in column 4 has the text Assign.
I have a script that theoretical works but I'm getting my data from Appsheet. The problem with this is that Appsheet writes data into my sheet but the script wont see it as edited cells, so it wont write the time stamp.
But my knowledge about Apps Scripts is pretty bad. And I am getting errors with the source line and the col, val lines.
function onEdit(e) {
var sh = e.source.getActiveSheet();
var row = e.range.getRow();
var col = e.range.getColumn();
var val = sh.getRange(row, 4).getValue();
//check if sheet is 'Blad1' & value is 'Assign'
if (sh.getSheetName() === 'Blad1' && val == 'Assign') {
var tz = e.source.getSpreadsheetTimeZone();
var date = Utilities.formatDate(new Date(), tz, 'dd-MM-yyyy hhmmss');
//set date in column 14 for same row
sh.getRange(row, 14).setValue(date);
}
}
I want to convert my script to a manually run script with a time-based trigger of 1 min. That way I hope the script will see the changed cell to Assign.
The problem is rooted in apps script triggers restrictions, specifically in their inability to listen to script-based events. I would suggest deploying your script as a WebApp with doGet() / doPost() functions to listen to API requests and, if I am correct in assuming that AppSheet works similarly to Zapier, etc., add a step that calls your WebApp after making changes to your Spreadsheet.
Please, see this guide on WebApps, its pretty straightforward to follow.
P.s. Btw, refrain from creating triggers acting as event listeners, you will easily cap your quotas!

How to set daily google app script to output fixed value

Am quite new with Google Scripts and wondering if anyone can help with this.
I've connected Google Analytics to Google Sheets (via add-on) and made settings so that conversion numbers are generated daily into a new google sheet tab (sheetB).
I'd like to match dates then copy the conversion data from sheetB to sheetA (master sheet which has acts like a dashboard).
The above can be done using this formula:
=IF(DA2=JuicerSessTime!$A$16,JuicerSessTime!$B$16)
The problem I'm facing is that since the above is a formula, I can't save the conversion data as a fixed value. So yesterday's value would show as FALSE from the formula above.
I'd like to be able to keep and save all daily generated values.
I've tried to create a google script below but it doesn't seem to work, hope someone can help.
function moveOneValuesOnlyToday() {
var mydate = new Date();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sdate = ss.getRange('sheetB!B2');
var sdate2 = ss.getRange('sheetA!DA2');
var source = ss.getRange('sheetA!DA5');
if (sdate == sdate2){
source.copyTo(ss.getRange('sheetA!DA6'), {contentsOnly: true});
}
}
Thanks in advance!