I'm working with Google App Script. I am trying to:
It seems to me that the code below should work, but it doesn't. It does accomplish tasks 1 and 3 - that is, it makes a copy and saves the copy to my desired folder. However, it does not save the file with the file name I specify. Instead, it saves it as "Copy of [original spreadsheet filename]." To do this, I am using File#makeCopy
(Note: I know this question has been answered before, but I believe it has not been answered since Google sunset the DocList service.)
When I made this simplified MCVE, I found that it works as expected:
function saveAsSpreadsheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var destFolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxx");
DriveApp.getFileById(sheet.getId()).makeCopy("desired file name", destFolder);
} //END function saveAsSpreadsheet
However, my original code does not - the copy's name is wrong:
function saveAsSpreadsheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var buildingNameAddress = sheet.getRangeByName('buildingNameAddress').getValue();
Logger.log(buildingNameAddress); //Logs correct string
var destFolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxxxx");
DriveApp.getFileById(sheet.getId()).makeCopy(buildingNameAddress, destFolder);
}
To copy a sheet to another spreadsheet in Google Drive, click the tab of the sheet you want to copy, then select Copy to... from the menu that appears. Select the spreadsheet where you want to place the copy from the list that appears. A duplicate of the sheet will appear in the other spreadsheet.
Here is the corrected code for your function that worked for me. You were not setting the named range for which I used the method setNamedRange
and gave it a name. That and changing the variable name to which you were getting the range values to TestRange
. Also, getValue()
would only get you one value whereas you needed a range of values hence, used getValues()
instead. But the rest of the code was fine and worked perfectly.
function saveAsSpreadsheet(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var range = sheet.getRange('Sheet1!A1:B3');
sheet.setNamedRange('buildingNameAddress', range);
var TestRange = sheet.getRangeByName('buildingNameAddress').getValues();
Logger.log(TestRange);
var destFolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxxx");
DriveApp.getFileById(sheet.getId()).makeCopy("Test File", destFolder);
}
This code works good for me.
function cloneGoogleSheet() {
var destFolder = DriveApp.getFolderById("your_drive_folder_id");
DriveApp.getFileById("your_drive_source_file_id").makeCopy("particular_file_name", destFolder);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With