Reputation: 159
I am using the following Google Script code to generate a backup every time I open the file.
function copySheet() {
var formattedDate = Utilities.formatDate(new Date(), "GMT-6", "yyyy-MM-dd' 'HH:mm:ss");
var name = SpreadsheetApp.getActiveSpreadsheet().getName() + " Copy " + formattedDate;
var destination = DriveApp.getFolderById("18aW0o_L1jngSjZ56aKGjt29JwTE1OQZf");
var file = DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId())
var sh = SpreadsheetApp.openById(file.makeCopy(name, destination));
var ss = sh.getSheets()[0];
ss.getRange(1,1,ss.getLastRow(),ss.getLastColumn()).setValues(ss.getRange(1,1,ss.getLastRow(),ss.getLastColumn()).getValues());
}
There is a form linked to this sheet and that too gets duplicated every time the form. How do I stop this from happening? I want every backup copy to be linked with the same form. How can I do it using Google Script?
If it is not possible, is there any other way to generate backup such that the form doesn't get duplicated?
Upvotes: 1
Views: 613
Reputation: 50416
The previous answer is correct. It is however possible to delink the form and use onFormSubmit
of form to post form data to various spreadsheets without relying on the inbuilt form-spreadsheet link. See sample here
Upvotes: 0
Reputation: 2072
I want every backup copy to be linked with the same form. How can I do it using Google Script?
Unfortunately, this is not possible. A form can only be linked to one spreadsheet at a time.
One way to prevent duplicate forms: instead of creating a copy of the spreadsheet, create a new blank spreadsheet, and copy the individual sheet (or sheets) to that spreadsheet.
/**
* Create a new spreadsheet in the folder, and copy the sheet to it.
*/
function duplicateSpreadsheetF(filename, sourceSpreadsheet, folder) {
// Create a new blank file
var spreadsheet = SpreadsheetApp.create(filename)
// Move to the folder
var file = DriveApp.getFileById(spreadsheet.getId())
file.moveTo(folder)
// Copy the sheets from the source
sourceSpreadsheet.getSheets().forEach(function(sheet){
sheet.copyTo(spreadsheet).setName(sheet.getName())
})
// Remove the default blank Sheet1
var blankSheet = spreadsheet.getSheetByName('Sheet1')
if (blankSheet) spreadsheet.deleteSheet(blankSheet)
return spreadsheet
}
When you just copy the individual sheet, the copy won't be linked to any form--it will just be a copy of the data on the sheet.
You can append this to your existing code. It will iterate over all sheets on the backup copy, and unlink--then delete--any form linked to each sheet.
// Unlink and delete all forms that are linked to spreadsheet sh
sh.getSheets().forEach(function(sheet){
// Get form attached to sheet
var formUrl = sheet.getFormUrl(); // returns null if there is no linked form
if (formUrl) {
var form = FormApp.openByUrl(formUrl);
// Unlink the form
form.removeDestination();
// Delete the form
DriveApp.getFileById(form.getId()).setTrashed(true);
}
})
Upvotes: 3