【问题标题】:Google Apps Script - Better way to do a VlookupGoogle Apps 脚本 - 进行 Vlookup 的更好方法
【发布时间】:2022-11-15 22:47:53
【问题描述】:

我正在一个包含大约 3K 个单元格的列中执行一种 VLOOKUP 操作。我正在使用以下功能来做到这一点。我评论了代码在函数中的作用,但总结一下:

  • 它从值创建映射以从具有元数据的表中搜索
  • 它迭代给定范围的每个值,并在上一个地图中搜索巧合
  • 如果发现重合,则使用索引捕获元数据表的第二列
  • 最后,设置在另一个单元格中捕获的值

这是代码:

function questions_categories() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("data_processed");

  // get metadata. This will work as the table to look into
  // Column B contains the matching element
  // Column C contains the string to return
  var metadata = ss.getSheetByName("metadata").getRange('B2:C').getValues()

  // Just get the different values from the column B
  var dataList = metadata.map(x => x[0])

  // Used to define the last cell where to apply the vlookup
  var Avals = sheet.getRange("A1:A").getValues();
  var Alast = Avals.filter(String).length;

  // define the range to apply the "vlookup"
  const questions_range = sheet.getRange("Q2:Q" + Alast);
  
  forEachRangeCell(questions_range, (cell) => {
  
    var searchValue = cell.getValue();
    // is the value to search in the dataList we defined previously?
    var index = dataList.indexOf(searchValue);

    if (index === -1) {
      // if not, throw an error
      throw new Error('Value not found')
    } else {
      // if the value is there, use the index in which that appears to get the value of column C
      var foundValue = metadata[index][1]
      // set the value in two columns to the right
      cell.offset(0, 2).setValue(`${foundValue}`);
    }
  })
}

forEachRangeCell() 是一个遍历范围的辅助函数。

这工作得很好,但它每秒解析 3-4 个单元格,如果我需要检查数千个数据,这不是很有效。我想知道是否有更高效的方法来实现相同的结果。

【问题讨论】:

    标签: google-apps-script google-sheets


    【解决方案1】:

    要提高性能,请使用 Range.setValues() 而不是 Range.setValue(),如下所示:

    function questions_categories() {
      const ss = SpreadsheetApp.getActive();
      const source = { values: ss.getRange('metadata!B2:C').getValues() };
      const target = { range: ss.getRange('data_processed!Q2:Q') };
      source.keys = source.values.map(row => row[0]);
      target.keys = target.range.getValues().flat();
      const result = target.keys.map(key => [sourceValues[source.keys.indexOf(key)]?.[1]]);
      target.range.offset(0, 2).setValues(result);
    }
    

    Apps Script best practices

    【讨论】:

      猜你喜欢
      • 2023-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 2023-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多