簡體   English   中英

在Google表格中輸入數據后,自動保護單元格/范圍

[英]Automatically protect a cell / range after inputting data in Google Sheets

我有一個公開的電子表格,人們可以在其中在“名稱”列下輸入其名稱。 除“名稱”列中的單元格外,此工作表中的所有內容均受保護。 由於電子表格是公開的,因此我想避免有人可以拖曳並刪除所有輸入的姓名的情況。 因此,在任何人在單元格中輸入了他們的名字之后,我試圖使用on編輯觸發器來設置腳本以保護該范圍內的單元格。 到目前為止,輸入名稱后,我一直在手動保護單元格。

我發現最好的方法是使用on edit觸發器。 我以前使用過JavaScript,但是由於我是Google電子表格腳本的新手,所以我無法讓腳本像預期的那樣運行。 當前腳本應該在編輯時自動保護范圍,並添加有關保護時間的描述。 包含腳本的電子表格示例: https : //docs.google.com/spreadsheets/d/18NlVKcaeyOkgqIa6WAuDsu5TSYK37m_vXLmp7p7Q8kc/edit?usp=sharing

function protectOnEdit(event) {
  var ss = SpreadsheetApp.getActive();
  var range = ss.getRange('Sheet1!A2:A1000');
  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

  var me = Session.getEffectiveUser();

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

參考: https : //developers.google.com/apps-script/reference/spreadsheet/range#protect()

有問題的數據范圍是A2:A1000,目前似乎可以部分使用,但是,它在編輯單個單元格后保護了整個范圍,而不是像原來那樣保護已編輯的單元格。

為了使腳本分別鎖定單元格而不是整個范圍,我是否缺少任何步驟? 任何見解都非常感謝!

我做了一些更正:

function protectOnEdit(e) {
  var range = e.range;
  // Be sure to have edited the sheet "Sheet1"
  if (range.getSheet().getName() != "Sheet1") return;
  // Be sure to have a single cell as edited range
  if (range.getWidth() != 1 || range.getHeight() != 1) return;
  // Be sure to have edited cell inside A2:A1000
  if (range.getColumn() != 1 || range.getRow() < 2) return;
  // Be sure to have non-blank new value
  if (!e.value) return;

  // Protect this 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);
  protection.removeEditors(protection.getEditors());
  if (protection.canDomainEdit()) protection.setDomainEdit(false);
}

首先,腳本會檢查幾種條件以獲得所需的保護。 在我看來,它們對於這項任務很重要。 如果它們都為TRUE,則保護單個單元格。 電子表格所有者對編輯受保護的單元格沒有任何限制,但其他編輯器則有限制。

當然,所有者應為此功能正確安裝觸發器,以使過程自動化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM