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;
}
4

1 回答 1

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;
}
于 2013-08-01T17:51:41.747 回答