首页 > 解决方案 > 当我(工作簿的所有者)清除其内容时,如何自动删除 Google 表格中单元格上存在的所有保护?

问题描述

我目前正在使用 Google 表格作为人们注册某些时间班次的一种方式。我正在使用以下脚本在数据输入后自动保护单元格,这样人们就无法在不通知我的情况下随意删除他们的注册:

function onEdit(e) {

  var range = e.range;

  var timeZone = Session.getScriptTimeZone();
  var stringDate = Utilities.formatDate(new Date(), timeZone, 'dd/MM/yy HH:mm');
  var description = 'Protected on ' + stringDate;
  var protection = range.protect().setDescription(description);

  // below code taken directly from Google's documentation (second comment is my own):

  // Ensure the current user is an editor before removing others. Otherwise, if the user's edit
  // permission comes from a group, the script throws an exception upon removing the group.

  var me = Session.getEffectiveUser();
  //user who installed trigger

  protection.addEditor(me);
  protection.removeEditors(protection.getEditors());
  if (protection.canDomainEdit()) {
    protection.setDomainEdit(false);
  }      
}

手头的问题是我正在与许多班次和人员一起工作,这使得如果有人出于正当理由需要取消任何保护措施(谷歌表格不提供搜索您的保护范围)。我了解编写脚本的逻辑,但在使用它们时非常缺乏经验。我真的可以使用一些帮助来创建一些可以删除我从中清除数据的任何单元格上的所有保护的东西。

标签: google-apps-scriptgoogle-sheetsscripting

解决方案


一种方法是打开保护范围菜单并单击角落。然后手动删除它们

0

脚本将是:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0]; // assuming you want the first sheet
var protections = sheet.getProtections();
for (var i = 0; i < protections.length; i++) {
  if (protections[i].getDescription() == 'Protect column A') { //name of protected range
    protections[i].remove();
  }
}  

对于大规模取消保护,请参阅:https ://webapps.stackexchange.com/a/99304/186471


推荐阅读