我只是想知道是否有办法使用下面提供的代码提取多个(最多只有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 :(得分: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;
}