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

Google Sheets脚本:复制行时如何保留原受保护区域?

解决Google Sheets复制模板行时保留保护设置的问题

可以实现,只需在原脚本基础上添加同步保护规则的逻辑。下面是修改后的完整脚本:

function AddParticipant(){
  var spreadsheet = SpreadsheetApp.getActive();
  var thisSheet = spreadsheet.getActiveSheet();
  var sourceRow = 7; // 模板行的行号
  var sourceRange = thisSheet.getRange(sourceRow, 1, 1, thisSheet.getMaxColumns());

  // 找到插入位置(◇所在行之前)
  var testCol = thisSheet.getRange(1, 2, thisSheet.getMaxRows()).getValues();
  var pos = 0;
  for (var i = 0; i < testCol.length; i++){
    if (testCol[i] == "◇"){
      break;
    }
    pos = i + 2;
  }

  // 插入新行并复制内容
  thisSheet.insertRowsBefore(pos, 1);
  var destRange = thisSheet.getRange(pos, 1, 1, thisSheet.getMaxColumns());
  sourceRange.copyTo(destRange, SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);

  // 同步模板行的保护设置到新行
  var templateProtections = thisSheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  var newRow = pos;

  templateProtections.forEach(function(protection) {
    var protectedRange = protection.getRange();
    // 检查该保护是否属于模板行
    if (protectedRange.getRow() === sourceRow) {
      // 计算新行对应的保护范围
      var newProtectedRange = thisSheet.getRange(
        newRow,
        protectedRange.getColumn(),
        1,
        protectedRange.getNumColumns()
      );
      // 创建新保护
      var newProtection = newProtectedRange.protect();
      // 复制原保护的设置
      newProtection.setDescription(protection.getDescription());
      newProtection.setWarningOnly(protection.isWarningOnly());
      
      // 设置编辑权限(和原保护一致)
      var editors = protection.getEditors();
      var domainEditors = protection.getDomainEditors();
      if (protection.canDomainEdit()) {
        newProtection.setDomainEdit(true);
      } else {
        newProtection.setDomainEdit(false);
        newProtection.removeEditors(newProtection.getEditors());
        newProtection.addEditors(editors);
      }
      
      // 如果原保护是仅所有者可编辑,设置对应权限
      if (!protection.isWarningOnly() && editors.length === 0 && !protection.canDomainEdit()) {
        newProtection.setWarningOnly(false);
        newProtection.removeEditors(newProtection.getEditors());
        newProtection.addEditor(spreadsheet.getOwner());
      }
    }
  });
}

关键逻辑说明

  • 获取模板行保护: 通过getProtections(SpreadsheetApp.ProtectionType.RANGE)获取工作表中所有范围保护,筛选出属于模板行的规则。
  • 匹配新行范围: 根据原保护的列范围,在新行上创建对应的保护区域。
  • 同步权限设置: 复制原保护的描述、警告状态、编辑者列表,确保新行的保护规则和模板行完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 18:12:41