【发布时间】: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