简体   繁体   中英

Copy and Paste Values of Cells to another Spreadsheet, creating a new sheet and pasting values

I have searched all of the web and cannot find a script that does the following.

Copy Active Sheet Cells: A1:AX55

Paste in another spreadsheet, creating a new sheet (name new sheet - value of Active Sheet C1)

I would link the script to an image in the active spreadsheet and click it to run script

The closest I have found is the following:

var sheet = SpreadsheetApp.getActiveSheet(); // Get current active sheet.
var sheet_name = sheet.getRange("i2").getValue(); // Get the value of cell B1, used to name the new spreadsheet.

var folder = DriveApp.getFolderById("xxxxxxxxxxxxx"); // Get the ID of the folder where you will place a copy of the spreadsheet.

var newSS = SpreadsheetApp.create(sheet_name); // create new blank spreadsheet in a root folder
var asFile = DriveApp.getFileById(newSS.getId()); // get new spreadsheet as a file

folder.addFile(asFile); // add this file to destination folder
DriveApp.getRootFolder().removeFile(asFile); // remove a file from root folder

var copiedSheet = sheet.copyTo(newSS); // copy active sheet to new spreadsheet
copiedSheet.setName(sheet_name); // rename copied sheet
newSS.deleteSheet(newSS.getSheetByName('Sheet1')); // remove "Sheet1" sheet which was created by default in new spreadsheet

reworked your example to suit your case:

var sheet = SpreadsheetApp.getActiveSheet(); // Get current active sheet.
var dataToCopy = sheet.getRange("A1:AX55").getValues(); //data to copy
var sheet_name = dataToCopy[0][2]; // Get the value of cell C1, used to name the new spreadsheet.
var folder = DriveApp.getFolderById("xxxxxxxx"); // Get the ID of the folder where you will place a copy of the spreadsheet.
        
var newSS = SpreadsheetApp.create(sheet_name); // create new blank spreadsheet in a root folder
var newSheetFile = DriveApp.getFileById(newSS.getId());
newSheetFile.moveTo(folder); //move new spreadsheet to destination folder  
var renamedSheet = newSS.getSheetByName('Sheet1').setName(sheet_name); // rename sheet
renamedSheet.getRange("A1:AX55").setValues(dataToCopy); //sets old data into new sheet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM