2013-02-01 33 views
0

我在Google Docs中有一個腳本,用於在Status列包含特定值時設置行的背景顏色。問題在於工作表具有某些受保護的列,因此當受限用戶觸發其部分上的腳本時,它會運行,但會得到令人討厭的權限錯誤消息(因爲腳本會對受保護列的部分進行着色)。因此,我需要創建2個腳本,以塊的形式對行進行着色,以便當受限用戶觸發個性化狀態消息時,只有他們未受保護的列顏色。下面的代碼是顏色的整行(由安裝onedit觸發器觸發):在Google電子表格中設置背景顏色時的權限問題

function setBackLogColor() { 

var range = SpreadsheetApp.getActiveSheet().getDataRange(); 
var statusColumnOffset = getStatusColumnOffset(); 

for (var i = range.getRow(); i < range.getLastRow(); i++) { 
rowRange = range.offset(i, 0, 1); 
status = rowRange.offset(0, statusColumnOffset).getValue(); 

if (status == 'TO LD') 
{ 
    rowRange.setBackgroundColor("#cfe2f3"); 
} 
else if (status == 'TO GB') 
{ 
    rowRange.setBackgroundColor("#d9ead3"); 
} 
else if (status == 'TO OUTSIDE PARTY - WILL COME BACK') 
{ 
    rowRange.setBackgroundColor("#f4cccc"); 
} 
else if (status == 'Hand Delivery 2') 
{ 
    rowRange.setBackgroundColor("#d9ead3"); 
} 
else if (status == 'Hand Delivery') 
{ 
    rowRange.setBackgroundColor("#cfe2f3"); 
} 
else 
{ 
    rowRange.setBackgroundColor("#FFFFFF"); 
} 
} 
} 

//Returns the offset value of the column titled "Status" 
//(eg, if the 7th column is labeled "Status", this function returns 6) 
function getStatusColumnOffset() { 
lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn(); 
var range = SpreadsheetApp.getActiveSheet().getRange(1,1,1,lastColumn); 

for (var i = 0; i < range.getLastColumn(); i++) { 
if (range.offset(0, i, 1, 1).getValue() == "Status") { 
    return i; 
} 
} 
} 

任何幫助將不勝感激!謝謝!

回答

0

這將是一個很好的應用Try..Catch block

var statusColor = "#FFFFFF"; // default value 
switch (status) { 
    case 'TO LD': 
    case 'Hand Delivery': 
    statusColor = "#cfe2f3"; 
    break; 
    case 'TO GB': 
    case 'Hand Delivery 2': 
    statusColor = "#d9ead3"; 
    break; 
    case 'TO OUTSIDE PARTY - WILL COME BACK': 
    statusColor = "#f4cccc"; 
    break; 
    default: 
    // do nothing, default already set 
    break; 
} 

try { 
    // try coloring whole range 
    // If non-privileged user, this will throw an exception. 
    rowRange.setBackgroundColor(statusColor); 
} 
catch (err) { 
    // You could validate that the error is indeed a permission error. 
    // Let's assume that's the case, and color only the unprotected columns. 
    var unprotRowRange = someSubsetOf(rowRange); // <<<<< Adjust as needed. 
    unprotRowRange.setBackgroundColor(statusColor); 
}