2013-08-01 55 views
0

我只是想知道是否有辦法用下面提供的代碼提取多個(最多隻有2個)結果。所有代碼都在搜索電子表格中的用戶名,然後在該用戶名旁邊的單元格中顯示值。我現在遇到的一個小問題是,他們的名字可能在給定的列中出現兩次,我希望顯示兩個結果。任何幫助,將不勝感激。什麼這個代碼是用於完整的解釋,如果需要,可以在這裏找到:VLOOKUP style app script using UiApp and textBox form to reference a spreadsheet電子表格中單個列搜索的多個結果

// function called when submit button is clicked 
function submit(e) { 
    var app = UiApp.getActiveApplication(); 

    Logger.log(Utilities.jsonStringify(e)); // Log the input parameter (temporary) 

    // Write the data in the text boxes back to the Spreadsheet 
    var cell = e.parameter.userName; 

    var doc = SpreadsheetApp.openById('SPREADSHEET-ID'); 
    var ss = doc.getSheets()[0]; 
    var lastRow = doc.getLastRow(); 
    var data = ss.getRange(2, 1, 2, 4).getValues(); 

    var result = "User not found"; 
    for (nn = 0; nn < data.length; ++nn) { 
    if (data[nn][1] == cell) { 
     result = data[nn][1]; 
     break 
    }; // if a match in column B is found, break the loop 
    } 

    // Make the status line visible and tell the user the possible actions 
    app.getElementById('status').setVisible(true).setText(result); 
    return app; 
} 

回答

0

所有你需要做的是修改搜索環路的行爲。執行搜索,將查找添加到數組中,並在找到一個項目後襬脫正在終止搜索的break。在搜索結束時,將發現數組加入到一個字符串中,然後就完成了。

// function called when submit button is clicked 
function submit(e) { 
    var app = UiApp.getActiveApplication(); 

    Logger.log(Utilities.jsonStringify(e)); // Log the input parameter (temporary) 

    // Write the data in the text boxes back to the Spreadsheet 
    var cell = e.parameter.userName; 

    var doc = SpreadsheetApp.openById('SPREADSHEET-ID'); 
    var ss = doc.getSheets()[0]; 
    var lastRow = doc.getLastRow(); 
    var data = ss.getRange(2, 1, 2, 4).getValues(); 

    var result = "User not found"; 
    var result_array = []; 
    for (nn = 0; nn < data.length; ++nn) { 
    if (data[nn][1] == cell) { 
     result_array.push(data[nn][1]); 
    }; // if a match in column B is found, keep going, there may be more! 
    } 
    if (result_array.length > 0) 
    result = result_array.join(", "); // concatenate multiple results 

    // Make the status line visible and tell the user the possible actions 
    app.getElementById('status').setVisible(true).setText(result); 
    return app; 
} 
相關問題