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

标签 google-apps-script google-sheets

我正在 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/

相关文章:

javascript - 从 gmail 线程中的 ZIP 文件中提取 CSV 并将数据写入 Google 表格

google-apps-script - Google Apps Script - 将数据复制到不同的工作表并附加

javascript - 客户端 successHandler 为空,但服务器日志显示结果

multithreading - 如何并行执行自定义函数公式,同时保持Google表格的可共享性和非许可性?

excel - 如何在表格上搜索已编辑的行以比较值并相应地更改不同列上的时间戳?

google-apps-script - 如何让用户登录 Google 以访问已部署的 GAS Web 应用程序?

google-apps-script - 将谷歌应用程序脚本移动到 v8 文件上传停止从侧边栏工作

javascript - 对所选文本使用 replaceText(),而不是 Google 文档的整个元素

python - 根据多个标准查找重复项

google-apps-script - 将 setFormula 方法与 appendRow 一起使用