gpt4 book ai didi

google-apps-script - 用于复制和重命名电子表格的 Google Sheets 脚本

转载 作者:行者123 更新时间:2023-12-02 19:56:23 24 4
gpt4 key购买 nike

我正在 Google 表格中创建一个脚本,该脚本将复制事件工作表并在同一工作簿中创建 30 个重复工作表。每个复制的工作表将根据事件工作表上单元格内的值具有不同的名称。该单元格将包含一个日期;重复的工作表将具有单元格中列出的日期之后的日期名称。例如,单元格 B3 是“7/5/2019”。复制的表格应命名为“2019年7月6日”(B3+1)、“2019年7月7日”(B3+2)、“2019年7月8日”(B3+3)等。

我使用的代码已嵌入 Google 表格中。其中一些是通过录制宏创建的,其他部分是通过我对编码和在线研究的了解而创建的。

function duplicatesheet(){

//copy active sheet
var as = SpreadsheetApp.getActiveSpreadsheet()
SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet();

//rename sheet
var myValue =
SpreadsheetApp.getActiveSpreadsheet().getRange('B3').getValue();
SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet(myValue);

}

该代码可以将事件工作表复制一次,但不能复制 30 次。它也没有根据单元格 B3 中列出的日期如上所述正确地重命名工作表。我需要帮助创建可以完成这两项任务的代码。

最佳答案

这是经过编辑的。评论。您还可以看到 Tedinoz 的精彩回答。

试试这个代码:

function duplicatesheet() {
var as = SpreadsheetApp.getActiveSpreadsheet(); // active spreadsheet
var s = as.getActiveSheet(); // first sheet object
var dateCell = "B3"; // cell containing first date
var N = 30; // number of copies to make

var startDate = new Date(s.getRange(dateCell).getValue()); // get the date stored in dateCell
var day = startDate.getDate(); // extract the day
var month = startDate.getMonth(); // extract the month
var year = startDate.getFullYear(); // extract the year

// loop over N times
for (var i = 0; i < N; i++) {
var asn = s.copyTo(as); // make a duplicate of the first sheet
var thisSheetDate = new Date(year, month, day+(i+1)); // store the new date as a variable temporarily

asn.getRange(dateCell).setValue(thisSheetDate); // writes the date in cell "B3"
asn.setName(Utilities.formatDate(thisSheetDate, undefined, "MMMMM d, yyyy")); // sets the name of the new sheet
}
}

我建议将 N=30 放在那里一些小的东西,比如 N=2 来看看它是否适合您的格式。

这里的格式由Utilities.formatDate()方法使用,我假设它是MMMMM d, yyyy,它将以此格式打印选项卡名称:

July 6, 2019

您可以根据引用[ 3 随意更改它] 下面。


您可以查看此处使用的所有函数的引用:

关于google-apps-script - 用于复制和重命名电子表格的 Google Sheets 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56910886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com