首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Google脚本-做Vlookup的更好方法

Google脚本-做Vlookup的更好方法
EN

Stack Overflow用户
提问于 2022-11-15 12:13:29
回答 1查看 31关注 0票数 0

我正在做一种VLOOKUP操作,在一个列约3K细胞。我正在使用下面的函数来完成它。我评论了代码在函数中所做的工作,但概括地说:

  • 它从包含元数据的表中创建要搜索的值的映射。
  • 它迭代给定范围的每个值,并在前面的映射中搜索巧合。
  • 如果发现巧合,则使用索引捕获元数据表的第二列。
  • 最后,设置在另一个单元格中捕获的值。

这是代码:

代码语言:javascript
复制
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个单元每秒,这不是很有效,如果我需要检查数千个数据。我想知道是否有一种更好的方式来达到同样的效果。

EN

Stack Overflow用户

回答已采纳

发布于 2022-11-15 14:26:38

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

代码语言:javascript
复制
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 => [source.values[source.keys.indexOf(key)]?.[1]]);
  target.range.offset(0, 2).setValues(result);
}

应用程序脚本最佳实践

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74445425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档