[英]Lock Google Sheets cells/range after condition is met
我們在內部使用 Google 表格進行財務核對,但其中存在一些錯誤。 有一個包含所有數據的電子表格,幾乎公司中的每個人都可以訪問並進行編輯。 我想做的是在滿足簡單條件(例如,單元格填充顏色更改為紅色)時,為除少數人之外的所有用戶鎖定某些單元格。 所以功能描述看起來像:
如果有人可以幫助應用確切的功能,我們將不勝感激。 提前謝謝了!
我唯一找到的是接近我的問題的文檔: https ://developers.google.com/apps-script/reference/spreadsheet/range https://developers.google.com/apps-script/reference /spreadsheet/protection但我在 Google 表格使用的 Apps 腳本中為零(
這讓你接近但不幸的是我遇到了 onEdit 事件的問題顯然不考慮背景顏色變化......所以最終這只會在單元格值改變后觸發。
如果單元格為紅色且范圍尚未受到保護,那么它將受到保護,因為您是唯一的編輯者。 如果背景不是紅色,它將取消保護或不改變。
/**
* Protects and unprotects ranges;
* @param {Object} e event object;
*/
function onEdit(e) {
//access cell formats;
var bgColor = e.range.getBackground();
var bold = e.range.getFontWeight();
//access edited range, value and sheet;
var rng = e.range;
var val = e.value;
var sh = rng.getSheet();
//access edited range row and column;
var row = rng.getRow();
var col = rng.getColumn();
//access protections;
var ps = sh.getProtections(SpreadsheetApp.ProtectionType.RANGE);
//filter out other cells protections;
ps = ps.filter(function(p){
var ptd = p.getRange();
if(row===ptd.getRow()&&col===ptd.getColumn()) {
return p;
}
})[0];
//SpreadsheetApp.getActive().toast(bgColor); //Uncomment to get a toast displaying background color of edited cell.
//if protection not set -> protect;
if(!ps) {
if (bgColor === '#ff0000' && bold === 'bold') {
SpreadsheetApp.getActive().toast("Cell Locked");
var protection = rng.protect(); //protect Range;
var users = protection.getEditors(); //get current editors;
var emails = [Session.getEffectiveUser(),'email1@email.com','email2@email.com']; //declare list of users (emails)
protection.addEditor(Session.getEffectiveUser());
protection.addEditors(emails);
protection.removeEditors(users); //remove other editors' access;
}}else {
if(!val || bgColor != '#ff0000' || bold != 'bold') { ps.remove(); } //if cell is empty -> remove protection;
}
}
也許有人可以對此進行改進並僅針對背景事件進行調整。 另外,如果工作速度很快,這就跟不上了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.