第一次輸入資料后,我使用以下 OnEdit() 觸發代碼鎖定單元格:
function LockCells(event){
var range = event.range;
var description = 'Protected'; // stringDate;
var protection = range.protect().setDescription(description);
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
}
當我作為用戶(不是作業表管理員)在單元格中輸入一個值時,它會立即阻止單元格重新輸入值。我們可以推遲這個程序嗎?我的意思是,如果我們現在輸入值,但對該單元格的保護在 10 分鐘或一小時后應用,而不是立即應用?
uj5u.com熱心網友回復:
我相信你的目標如下。
- 您的功能
LockCells由 OnEdit 可安裝觸發器執行。 - 您希望
LockCells在 OnEdit 觸發器運行后運行函式中的腳本。
在這種情況下,以下修改后的腳本如何?
修改后的腳本 1:
例如,當OnEdit觸發器運行時,當你想LockCells在大約6分鐘后運行函式中的腳本時,修改后的腳本可以簡單一點,如下所示。
function LockCells(event) {
Utilities.sleep(5 * 60 * 1000); // For example, after 5 minutes, the script is run.
var range = event.range;
var description = 'Protected'; // stringDate;
var protection = range.protect().setDescription(description);
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
}
修改后的腳本 2:
當你想在LockCells超過6分鐘后運行函式中的腳本時,修改后的腳本如下。請將以下腳本復制并粘貼到電子表格的腳本編輯器中。并且,請重新安裝 OnEdit 可安裝觸發器到函式中LockCells。這樣,當您編輯單元格時,在此示例腳本中編輯的單元格會在 10 分鐘后受到保護。
var time = 10 * 60 * 1000; // 10 minutes
function LockCells(event) {
var date = new Date().getTime();
var range = event.range;
var a1Notation = `'${range.getSheet().getSheetName()}'!${range.getA1Notation()}`;
var p = PropertiesService.getScriptProperties();
var ranges = p.getProperty("ranges");
ranges = ranges ? JSON.parse(ranges).concat({ date, a1Notation }) : [{ date, a1Notation }];
p.setProperty("ranges", JSON.stringify(ranges));
ScriptApp.newTrigger("lockCellsByTrigger").timeBased().after(time).create();
}
function lockCellsByTrigger(e) {
ScriptApp.getScriptTriggers().forEach(t => {
if (t.getUniqueId() == e.triggerUid) ScriptApp.deleteTrigger(t);
});
var limit = time;
var now = new Date().getTime();
var p = PropertiesService.getScriptProperties();
var ranges = p.getProperty("ranges");
if (!ranges) return;
ranges = JSON.parse(ranges);
var {rranges, r} = ranges.reduce((o, e) => {
o[e.date limit < now ? "rranges" : "r"].push(e);
return o;
}, {rranges: [], r: []});
if (rranges.length == 0) return;
p.setProperty("ranges", JSON.stringify(r));
var description = 'Protected';
var me = Session.getEffectiveUser();
rranges.forEach(({a1Notation}) => {
var protection = SpreadsheetApp.getActiveSpreadsheet().getRange(a1Notation).protect().setDescription(description);
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
});
}
- 當您要更改時間時,請修改
time。在當前階段,10 分鐘后,編輯的單元格被保護。 - 該腳本的流程如下。
- 編輯單元格時,
LockCells由可安裝的 OnEdit 觸發器運行。 - 將編輯過的單元格的a1Notation和日期放到屬性服務中,10分鐘后安裝時間驅動觸發器。
- 當時間驅動觸發器運行該功能時
lockCellsByTrigger,10 分鐘后編輯的單元格受到保護。
- 編輯單元格時,
參考:
- 物業服務
- 新觸發器(功能名稱)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/365622.html
