簡體   English   中英

Google腳本可將電子表格中的工作表復制到新電子表格,並以特定單元格命名新電子表格

[英]Google script to copy sheet in spreadsheet to new spreadsheet and name new spreadsheet after specific cell

我有一個包含多個工作表的google電子表格,我想將每個工作表復制到一個新的電子表格中,並讓新的電子表格以特定單元格中的文本命名。 我很高興多次運行該腳本,因此我想讓它復制活動工作表。

即我所擁有的=電子表格稱為“顏色”-表格1 =“紅色”,表格2 =“藍色”,表格3 =“黃色”,依此類推。

我想要的=

電子表格稱為“紅色”。 電子表格稱為“藍色”,電子表格稱為“黃色”

到目前為止,我有這個腳本,但是它告訴我“找不到腳本功能:saveAsSpreadsheet有關更多信息”

function copyDocument() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Get current active spreadsheet.
var sstocopy = ss.getActiveSheet(); // Get spreadsheet with DriveApp.
var sheet = ss.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.
sstocopy.makeCopy(sheet_name,folder); // Make a copy of the spreadsheet in the destination folder.

任何幫助將不勝感激。

您需要將電子表格作為文件而不是電子表格打開才能使用makeCopy函數。

因此,您代碼中的這一行是不正確的:

var sstocopy = ss.getActiveSheet(); // Get spreadsheet with DriveApp.

它應該是:

var sstocopy = DriveApp.getFileById(ss.getId()); // Get spreadsheet with DriveApp.

因此,正確的代碼如下:

function copyDocument() {
    var ss = SpreadsheetApp.getActiveSpreadsheet(); // Get current active spreadsheet.
    var sstocopy = DriveApp.getFileById(ss.getId()); // Get spreadsheet with DriveApp.
    var sheet = ss.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.
    sstocopy.makeCopy(sheet_name,folder); // Make a copy of the spreadsheet in the destination folder.

回答您的評論:

為了您的目的,應按以下方式修改代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM