首页 > 解决方案 > 我的 Google Apps 脚本保护整个工作表,而不是保护某些列并允许编辑者对其进行编辑

问题描述

我有这段代码,我希望某些列受到保护,并且只允许由某些编辑器进行编辑。但是,我的代码只制作了除我保护的列之外的整个工作表,而编辑器无法编辑任何其他列。我以为我剧本的这一部分

protection.removeEditors(protection.getEditors());

if (protection.canDomainEdit()) {
    protection.setDomainEdit(false);
}

导致整张纸受到保护,但是当我拿出它时,整张纸仍然受到保护。有人可以帮我找出我的脚本的哪一部分是错误的以及我该如何解决它?我在编码或编写脚本方面没有太多知识,希望能提供任何帮助。

编辑:显然编辑器可以编辑,但是当我在“数据”下检查“受保护的工作表和范围”时,部分代码也将受保护的范围设为“仅查看”。如果有人能帮助我摆脱这种看法,那我将不胜感激。”

function OnOpen(){
    // Protect the active sheet except colored cells, then remove all other users from the list of editors.
    var ss = SpreadsheetApp.getActiveSheet();
    var range = ss.getRange("A1:B10");
    var range1 = ss.getRange("D1:E10");
    var protection = range.protect().setDescription('Sample protected sheet');
    var protection1 = range1.protect().setDescription('Sample protected sheet');

    // Ensure the current user is an editor before removing others. Otherwise, if the user's edit
    // permission comes from a group, the script will throw an exception upon removing the group.
    var me = Session.getEffectiveUser();
    var editor = ["email@gmail.com"]
    var editor1 =["email2@gmail.com"]

    if (me.getEmail() == editor){
        protection.addEditor(editor);  
    }

    if (me.getEmail() == editor1){
        protection1.addEditor(editor1);
    }

    protection.removeEditors(protection.getEditors());

    if (protection.canDomainEdit()) {
        protection.setDomainEdit(false);
    }
}

标签: google-apps-scriptgoogle-sheets

解决方案


爱德华提供的答案。

function OnOpen(){
    // Protect the active sheet except colored cells, then remove all other users from the list of editors.
    var ss = SpreadsheetApp.getActiveSheet();
    var range = ss.getRange("A1:B10");
    var range1 = ss.getRange("D1:E10");
    var protection = range.protect().setDescription('Sample protected sheet');
    var protection1 = range1.protect().setDescription('Sample protected sheet');

    // Ensure the current user is an editor before removing others. Otherwise, if the user's edit
    // permission comes from a group, the script will throw an exception upon removing the group.
    var me = Session.getEffectiveUser(); 
    protection.addEditor(me); 
    protection1.addEditor(me); 
    protection.removeEditors(protection.getEditors()); 
      if (protection.canDomainEdit()) { 
        protection.setDomainEdit(false); 
      } 
      protection1.removeEditors(protection1.getEditors()); 
      if (protection1.canDomainEdit()) { 
        protection1.setDomainEdit(false); 
      } 
    }
      protection.addEditors(['user@gmail.com','user@gmail.com']); 
      protection1.addEditors(['user@gmail.com','user@gmail.com']); 
    }

推荐阅读