You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Sheets脚本优化需求:规范日期命名复制工作表并调整位置

Google Sheets 脚本优化实现

需求说明

  • 将复制生成的工作表名称改为带前导零的当前日期格式(日/月,如01/01)
  • 调整新工作表位置,使其位于MASTER工作表右侧,而非工作表列表最右侧

修改后的完整脚本

function duplicateSheetWithProtections() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('MASTER');
  // 生成带前导零的日/月格式日期作为新表名称
  var formattedDate = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd/MM");
  var sheet2 = sheet.copyTo(ss).setName(formattedDate);
  
  // 将新表移动到MASTER工作表右侧
  var masterIndex = sheet.getIndex();
  sheet2.setIndex(masterIndex + 1);
  
  // 复制区域保护规则
  var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  for (var i = 0; i < protections.length; i++) {
    var p = protections[i];
    var rangeNotation = p.getRange().getA1Notation();
    var p2 = sheet2.getRange(rangeNotation).protect();
    p2.setDescription(p.getDescription());
    p2.setWarningOnly(p.isWarningOnly());
    if (!p.isWarningOnly()) {
      p2.removeEditors(p2.getEditors());
      p2.addEditors(p.getEditors());
      // p2.setDomainEdit(p.canDomainEdit()); // 仅在使用Google Workspace域名时启用
    }
  }
}

关键修改点

  1. 带前导零的日期命名
    使用Utilities.formatDate()方法,指定格式字符串"dd/MM",自动为日、月小于10的数值添加前导零,确保格式统一。同时通过Session.getScriptTimeZone()获取脚本运行时区,避免日期显示偏差。

  2. 调整工作表位置
    通过sheet.getIndex()获取MASTER工作表的索引位置,再调用sheet2.setIndex(masterIndex + 1)将新表移到MASTER右侧,每次生成的最新日期表都会紧邻MASTER,方便快速查看。

  3. 变量作用域优化
    为sheet和sheet2添加var声明,避免全局变量污染,提升代码规范性。

内容的提问来源于stack exchange,提问作者dek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:55:11