2012-11-12 100 views
0

我們使用谷歌電子表格進行報告,用戶數量衆多。 我寫了一個基本的腳本,這將打開取決於當前用戶的特定表:獲取和使用Google文檔中其他工作表的用戶數據

var CurrentUser = Session.getUser().getEmail() 
var ss = SpreadsheetApp.getActive(); 
    switch(CurrentUser){ 
    case "[email protected]": 
     SpreadsheetApp.setActiveSheet(ss.getSheetByName("sheet1")); 
     break; 
    case "[email protected]": 
     SpreadsheetApp.setActiveSheet(ss.getSheetByName("sheet2")); 
     break; 
    case "[email protected]": 
     SpreadsheetApp.setActiveSheet(ss.getSheetByName("sheet3")); 
     break; 
    etc... 

我願把用戶數據和sheetnames到外部表,並把這些數據根據該表,所以它更容易維護電子郵件和用戶列表。 如何從特定的Google電子表格中獲取數據並讓腳本按照這種方式工作?

回答

0

你可以試試這個。它在不同的工作表上模擬VLOOKUP,並切換到當前工作簿中的「匹配」工作表。這不處理不匹配,但這應該相對簡單,以適應您的情況。

function switchSheets() { 
    // Current sheet 
    var ss = SpreadsheetApp.getActive(); 
    // Target sheet (using the key found in the URL) 
    var target = SpreadsheetApp.openById("my_other_sheet_id"); 
    var rows = target.getDataRange(); 
    var values = rows.getValues(); 

    // Get the current user 
    var CurrentUser = Session.getUser().getEmail(); 

    // Now iterate through all of the rows in your target sheet, 
    // looking for a row that matches your current user (this assumes that 
    // it will find a match - you'll want to handle non-matches as well) 
    for (var i = 1; i <= rows.getNumRows() - 1; i++) { 
    // Match the leftmost column 
    var row = values[i][0]; 
    if (row == CurrentUser) { 
     // If we match, grab the corresponding sheet (one column to the right) 
     target_sheet = values[i][1]; 
     break; 
    } 
    } 
    // Now switch to the matched sheet (rememeber to handle non-matches) 
    ss.setActiveSheet(ss.getSheetByName(target_sheet)); 
}; 
相關問題