Google Sheets script, copyto and replace existing sheet - google-apps-script

I've been searching for the past few weeks and haven't been able to figure out this script. What I'm trying to do is figure out a way for me to duplicate a pictorial calendar on a master Google Sheets file to another Google Sheets file that I manage. Every time there's an update on the master calendar, I'd love for it to automatically update in the other Google Sheets file that I manage. Right now I have to copy paste everything, reformat, and reimport images. I did find a script that somewhat works, but it has some issues that cause it to be just as much work.
The script is a copyTo script, it allows me to copy a sheet titled "Pictorial Calendar" from the master Google Sheets file (called "Master Calendar") to a different Google Sheets file (called "My Calendar"). I even set up a trigger that allows the script to run whenever I make an edit.
However, it keeps creating new sheets titled "Copy of Pictorial Calendar 1" "Copy of Pictorial Calendar 2" etc.) and I can't figure out how to make the script replace the existing sheet instead of creating new sheets.
I also would love to be able to change the duplicated sheet to just be called "Pictorial Calendar" in the "My Calendar" file. The script I'm using is:
function copyMasterCalendar() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[2];
var destination = SpreadsheetApp.openById("1exiUWVypFpYeHMkXHO3sMUTGupiC2gQjZIF0Ss44-pU");
sheet.copyTo(destination);
}
Any and all help would be much appreciated! Thank you!

If I understood you correctly try this...
function copyMasterCalendar() {
var source = SpreadsheetApp.getActiveSpreadsheet(),
sheet = source.getSheetByName('Pictorial Calendar'),
destination = SpreadsheetApp.openById("1exiUWVypFpYeHMkXHO3sMUTGupiC2gQjZIF0Ss44-pU"),
destSheet = destination.getSheetByName('Pictorial Calendar'),
copydSheet = sheet.copyTo(destination);
copydSheet.getDataRange().copyTo(destSheet.getDataRange());
destination.deleteSheet(copydSheet);
}

Related

Cannot read property 'getSheetByName' of null

function sortResponses() {
var Sheets = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Fall 01")
sheet.sort(3, false);
}
I have a Sheet called Fall 01 in my google Sheets, where I explicítly had to give the script access to, but it won't open, what am I missing?
Explanation/Issue:
The issue is that you have a standalone script which therefore is not bound to a google spreadsheet and as a result SpreadsheetApp.getActiveSpreadsheet() returns null.
Solutions:
There are two ways you can follow:
Solution 1:
Use SpreadsheetApp.openById(id) or SpreadsheetApp.openByUrl(url):
var Sheets = SpreadsheetApp.openById("Put your Spreadsheet ID").getSheetByName("Fall 01");
or
var Sheets = SpreadsheetApp.openByUrl("Put your Spreadsheet URL").getSheetByName("Fall 01");
Solution 2:
Go to the spreadsheet file that you want to work with and click on Tools => Script editor on the top menu of the spreadsheet file and put your current code there.
Please Note
If this is your only code, sheet is not defined, therefore you will get another error down the road. You most likely want to replace sheet with Sheets or the other way around. Be careful with this.

Google sheets make a copy of a worksheet to drive folder

I Am wondering if anyone can help.
I have been making a collection log sheet in google sheets and i want to only make a copy of 1 of the work sheets at the end of each month.
for exaple i want this worksheet tab in google sheets called collected orders to be copyed and then the sheet to be cleared of data arfter it had been copyed to the google drive
https://i.imgur.com/m5GueWv.png
The Apps Script reference documentation is your friend https://developers.google.com/apps-script/reference/spreadsheet.
The following code may or may not answer your question as it isn't completely clear what your actual workflow is.
What the code below will do is;
Get the active spreadsheet
Get the sheet called Completed Orders
Copy that sheet to the active spreadsheet
Get the range of data on that newly copied sheet
Delete the cells specified by that range of data
function copySheetDeleteData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mySheet = ss.getSheetByName("Completed Orders");
var myNewSheet = mySheet.copyTo(ss);
var copiedData = myNewSheet.getDataRange()
copiedData.deleteCells(SpreadsheetApp.Dimension.ROWS)
}
When I read your question I think;
Does he want to schedule this script to run at the end of the month?
Does the spreadsheet need to be open at the time?
When he says worksheet, does he mean the spreadsheet or the sheet within a spreadsheet?
Why bother copying the sheet and the data and then delete the data?
Why not just create a new sheet and call it what you want?

Google Sheets - Replace sheet without breaking references to that sheet

We are building a google sheets database where each user has their own spreadsheet that accesses a central sheet for information using apps script.
This means that with 50 employees, we have 50 spreadsheets to maintain. I am trying to find a way to push updates to all 50 spreadsheets without having to update each one manually. I have all the apps script code in a library that each user's sheet references, so I have the coding maintenance figured out. But keeping each users actual spreadsheet up to date with the latest features is proving difficult.
One way I'm figuring to do that is have a "Template" user sheet that gets updated with the changes/new features. Then when each user opens their spreadsheet, it cross references all of its sheets to the template sheet, and checks if it needs to replace it's sheet with the latest sheet based on time that it was updated in the template sheet. For example, when the sheet "Project Report" in the template is newer than the "Project Report" sheet in the user's spreadsheet, the user SS deletes it's current "Project Report" and copies the template "Project Report" sheet to it's own via the copyTo() method.
I have this all working with apps script, but the issue now is that when the user's local sheet is deleted and replaced with the new updated seet, all formula references to that sheet in other sheets break and replace the reference with #REF. I had planned on overcoming this by using only Named Ranges, but even the named ranges break when the sheet is replaced to the point where even the apps script can no longer find the named range because the named range it is looking for was automatically renamed when the new version of the sheet was imported (aka, "CustomNamedRange" in the template SS was renamed to "'SheetName'!CustomNamedRange" in the user SS).
The only way I know to overcome this issue at this point is to create a centralized "Range Index" spreadsheet that has all the named ranges with their destination sheet and range. I would have to create a custom function that filters through the range index and finds the address it needs based on the name given. For example, instead of calling "CustomNamedRange" in a sheet formula, I would call custom function: getNamedRange("CustomNamedRange"), and apps script would return the range found in the range index. And when a sheet is replaced with the newer version, no references would break because all references go through the apps script filter function.
The only problem with this is that I can foresee this method (calling every range needed in the script through a custom function) slowing down my spreadsheet A LOT because every time a range is called for, it will have to go search through the range index to find it and return it.
Does anyone have any other ideas on how to accomplish what I'm looking for? As in keeping 50+ individual spreadsheets updated with new features without having to do it manually and without breaking all the references?
Sorry for the long post, but I appreciate any ideas!
I had a similar problem and was able to resolve it by using SheetAPI to replace text. I have a template called Sheet1_Template and its hidden. I delete Sheet1, copy Sheet1_Template, show it and then replace all occurances of "Sheet1" in formulas to "Sheet1". Sheet API has to be enabled in the Resources and Google API Console.
function copyTemplate() {
try {
var spread = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spread.getSheetByName("Sheet1");
if( sheet !== null ) spread.deleteSheet(sheet);
sheet = spread.getSheetByName("Sheet1_Template");
sheet = sheet.copyTo(spread);
sheet.setName("Sheet1");
sheet.showSheet();
sheet.activate();
spread.moveActiveSheet(0);
var requests = {"requests":[{"findReplace":{"allSheets":true,"find":"Sheet1","replacement":"Sheet1","includeFormulas":true}}]};
Sheets.Spreadsheets.batchUpdate(requests, spread.getId());
}
catch(err) {
Logger.log("error in copyTemplate: "+err);
}
}
I haven't been able to test implementation of it yet, but I believe the answer above is what I was originally looking for.
I haven't spent any time messing with the API yet, so in the meantime I have found another solution:
Google Sheets recently added macros to it's feature set. The beauty of this is that You can see and edit the macro code after you've recorded your actions in the sheet. For now, I plan on recording a macro when I make updates to the template sheet, then copying the script for that macro into a custom function in my library that will run every time a user opens their spreadsheet. When they open their SS, apps script will check to see if the library's macro function has a later date than the last time the sheet was opened. If it does have a new date, then it will run the macro script, and that user's SS should get updated to the same state as the template.
Also if you are seeing that you cannot run the query from #TheWizEd
It may be due to "Sheets API" not being enabled at Advanced Google services. Please enable>
In the script editor, select Resources > Advanced Google services In the dialog that appears, click the on/off switch for Google Sheets API v4. Please turn on. Click OK button.
Thank you so much to TheWizEd for getting me started (please vote for that post too).
This is what I needed:
function replaceFormulasInSheet(sheet, searchFor, replaceWith) {
// https://stackoverflow.com/a/67151030/470749
// First you need to do this to enable the feature: https://developers.google.com/apps-script/guides/services/advanced#enabling_advanced_services
// https://developers.google.com/sheets/api/quickstart/apps-script
// https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#findreplacerequest
// https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate
const spread = SpreadsheetApp.getActiveSpreadsheet();
const requests = {
"requests": [
{
"findReplace": {
// "allSheets": true, Omitting this property and instead setting the sheetId property is the only way to effectively set allSheets as false.
"sheetId": sheet.getSheetId(),
"find": searchFor,
"replacement": replaceWith,
"includeFormulas": true
}
}
]
};
return Sheets.Spreadsheets.batchUpdate(requests, spread.getId());
}
Also note that it does not work for sheets with hyphens in their names. If you need hyphens in their names, remove the hyphens beforehand and re-add them after.

Wishing to run calendar import script on specific sheet not on active sheet

I would like the Google Calendar import script run on a specific sheet. Lets Say "Sheet4" The script works well on any current active sheet but I seem to be unable to modify all the proper lines in the script to make it work properly to be directed to a specified sheet.
Here is a link to the sheet
https://docs.google.com/spreadsheets/d/1DI_gnXyeKrR_t_6u0-EKzfUjeMmXj8GC6HlU-3uGmkc/edit#gid=2105065853
I tried to paste the code but kept getting formatting error. Apologies in advance. I am very new to this
You haven't shared the Google Spreadsheet but you can use the below code snippet to perform task on a particular sheet.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet4");
For sheet of different spreadsheet.
var sheet = SpreadsheetApp.openById("<<ENTER SPREADSHEET ID>>").getSheetByName("Sheet4")

Unable to access (an save) my SpreadSheet Google App Script

I have a Google SpreadSheet (filled through a form) associated to a Google Apps Script.
Now, the spreadsheet contains too many cells and I'm not able to load it anymore (server timeout).
I'm not interested in the data, but I really want to retrieve the script (the source code).
Unfortunately, the only way I know is to load the SpreadSheet first :-(
(Copying the Document ends in a timeout and the script is not copied.)
Any suggestion?
Regards,
Rémi.
Create another script which makes a copy of original spreadsheet to backup the data and then clear the original spreadsheet through the script.
However this seems an issue which should be reported to Google Spreadsheet Forum
Here is an example code which will backup the spreadsheet as a copy and clear the original spreadsheet
function backupDataAndClear(){
var sourceSS = SpreadsheetApp.openById('ID_OF_ORIGINAL_SS');
var newSS = sourceSS.copy('Backup SS');
var sourceSheets = sourceSS.getSheets();
for(var i in sourceSheets){
sourceSheets[i].clear();
}
}