2016-02-04 39 views
1

我有一些代碼在表中運行並在項目到期時發送電子郵件。如何在不同的選項卡上運行相同的代碼?

function expiryAlert() { 
    // get the spreadsheet object 
    var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); 
    // set the first sheet as active 
    SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]); 
    // fetch this sheet 
    var sheet = spreadsheet.getActiveSheet(); 

    // figure out what the last row is 
    var lastRow = sheet.getLastRow(); 

    // the rows are indexed starting at 1, and the first row 
    // is the headers, so start with row 4 
    var startRow = 3; 

    // days left column 
    var range = sheet.getRange(7,4,lastRow-startRow+1,1); 
    var numRows = range.getNumRows(); 
    var days_open_values = range.getValues(); 

    // item number column 
    range = sheet.getRange(7, 1, lastRow-startRow+1, 1); 
    var item_number_values = range.getValues(); 

    //Now grab the description number 
    range = sheet.getRange(7, 2, lastRow-startRow+1, 1); 
    var description_values = range.getValues(); 

    //Now grab the email addresses 
    range = sheet.getRange(7, 7, lastRow-startRow+1, 1); 
    var emailAddress_values = range.getValues(); 

    //Now grab the alert days value 
    range = sheet.getRange(2, 2); 
    var alert_days_values = range.getValues(); 

    //Grab the sheet title 
    range = sheet.getRange(1,1); 
    var title_values = range.getValues(); 

    //Grab the extra alert message 
    range = sheet.getRange(3,2); 
    var alert_message_values = range.getValues(); 

    var msg = ""; 

    // Loop over the days left values 
    for (var i = 0; i <= numRows - 1; i++) { 
    var days_open = days_open_values[i][0]; 
    var alert_days = alert_days_values; 
    if(days_open == alert_days) { 

     var item_number = item_number_values[i][0]; 
     var description = description_values[i][0]; 
     var emailAddress = emailAddress_values[i][0]; 
     var title = title_values; 
     var alert_message = alert_message_values; 

     msg = msg + "This is an automated alert for "+title+"\n\nItem number "+item_number+", "+description+", is due to expire in "+days_open+" days. Please ensure it is updated or reviewed.\n\n"+alert_message+"\n\n"; 

    MailApp.sendEmail(emailAddress,title, msg); 
    } 
    } 

}; 

我想爲不同班次添加另一個選項卡並在該表上運行相同的代碼。

我該怎麼做?我搜索了Google搜索,找不到任何幫助。

非常感謝!如果你想要的代碼對當前活動工作表運行

// set the first sheet as active 
SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]); 

回答

0

您需要刪除此代碼。該行代碼總是獲得電子表格中的第一個工作表選項卡。索引零[0]是數組中的第一個表。

如果您希望代碼影響當前活動的工作表選項卡,則需要手動選擇希望代碼工作的工作表選項卡,或者需要有兩個不同的菜單項每個將表單名稱傳遞給代碼。

您可以通過名字來取得各表:

.getSheetByName(theSheetName) 

如果你這樣做,你需要工作表名稱傳遞給函數。

function expiryAlert(theSheetName) { 

你可以有一個看起來像每個表中的按鈕,和連接將有表名稱腳本的圖像。你可以有一個側邊欄和兩個不同的按鈕。你可以有一個帶有表格名稱下拉列表的側邊欄。

相關問題