我正在一個包含大約 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 個單元格,如果我需要檢查數千個資料,這不是很有效。我想知道是否有更高效的方法來實作相同的結果。
uj5u.com熱心網友回復:
要提高性能,請使用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 => [source.values[source.keys.indexOf(key)]?.[1]]);
target.range.offset(0, 2).setValues(result);
}
請參閱Apps 腳本最佳實踐。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/534780.html
標籤:谷歌应用脚本谷歌表格
上一篇:有沒有辦法更新Docs中的鏈接物件值?基本上從Docs->Sheets更新而不是僅從Sheets->Docs更新?
下一篇:谷歌表格-查詢以過濾行和列