2016-12-12 60 views
0

我有一個小的Google Apps腳本,在編輯電子表格中的某些單元格後運行幾秒鐘。Google Apps腳本 - 禁止在腳本運行時編輯單元格

我的問題是,如果可以阻止當前用戶在腳本運行時對電子表格進行進一步更改。

因此,它應該是這樣的: 1.細胞被編輯 2.腳本運行時,用戶交互/當前用戶的變化被阻止 3.腳本完成 4.用戶交互/改變用於當前用戶未被封鎖

任何幫助將不勝感激。

非常感謝, 馬丁

+1

我會建議使用一個不可忽視的UI對話框,它解釋發生了什麼,然後在腳本完成運行時以編程方式關閉。 –

回答

1

您可以使用等級防護:https://developers.google.com/apps-script/reference/spreadsheet/protection

從上面的鏈接,其適於你可以試試:

function pro(){ 
    var sheet = SpreadsheetApp.getActiveSheet(); 
    var protection = sheet.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); 
    protection.removeEditors(protection.getEditors()); 
    if (protection.canDomainEdit()) { 
    protection.setDomainEdit(false); 
    } 

    //YOUR CODE TO RUN 

    SpreadsheetApp.flush(); 
    protection.remove(); 
} 

編輯

這爲我工作:

function onEdit(){ 
    //Adapted from: https://developers.google.com/apps-script/reference/spreadsheet/protection 
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; 
    var me = Session.getActiveUser().getEmail(); 

    if (me != 'owner email'){ 
    var protection = sheet.protect().setDescription('Sample protected sheet'); 
    protection.removeEditors(protection.getEditors()); 
    if (protection.canDomainEdit()) { 
     protection.setDomainEdit(false); 
    } 

    //YOUR CODE TO RUN 
    SpreadsheetApp.flush(); 
    protection.remove(); 
    } 
} 
+0

這對於有效的用戶不起作用。它會鎖定所有其他編輯器(不是所有者),但不會阻止用戶在腳本運行時進行編輯。 –

+0

@SpencerEaston我相信它確實有效,可能不是最好的解決方案,但它的工作原理。你可以在這裏試試:https://docs.google.com/spreadsheets/d/1cxiG2olk8FxZV30lCxv7aNnwoqC1c6NWICTq4UMaHzI/edit#gid=0 – utphx

+0

是的,如果用戶編輯速度慢,他們不擔心錯誤框就可以。同樣想到代碼刪除所有編輯器以阻止UI,然後在刪除更新的權限之前失敗/超時/配額的場景。真正正確的解決方案是「不要將用戶鎖定在用戶界面之外」,但是如果您必須使用更優雅的解決方案(如模態對話框)。 –