在你的情况下,以下修改怎么样?
修改要点:
-
在你的剧本中
const matchRow = targetMatch.find(r => r[0] == searchRow([0]))
,
searchRow([0])
应该是
searchRow[0]
这就是你目前发行《
searchRow is not a function.
.
-
此外,at
return matchRow ? [matchRow([2])] : [null];
,
matchRow([2])
应该是
matchRow[2]
但是
targetMatch
有2列
const targetMatch = tab.getRange("G1:H").getValues();
。因此,在这种情况下,返回undefined。
-
我想,在您的情况下,当在循环外创建用于搜索值的对象时,流程成本可能会降低。
当这些点反映在脚本中时,以下修改如何?
修改的脚本:
function myFunction() {
const sheetName1 = "Tab";
const sheetName2 = "Data";
// Retrieve sheets.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const [sheet1, sheet2] = [sheetName1, sheetName2].map(s => ss.getSheetByName(s));
// Retrieve values from both sheets.
const lastRow1 = sheet1.getLastRow();
const values1 = sheet1.getRange("G1:H" + lastRow1).getValues();
const values2 = sheet2.getRange("G1:I" + sheet2.getLastRow()).getValues();
// Create an object for searching.
const obj2 = new Map(values2.map(([g, h, i]) => [`${g}${h}`, i]));
// Create the result array.
const res = values1.map(([g, h]) => [obj2.get(`${g}${h}`) || null]);
// Put the result array to column "O" of "Tab" sheet as a sample.
sheet1.getRange(`O1:O${lastRow1}`).setValues(res);
}
运行此脚本时,结果值将放入“O”列。因为您的电子表格在“N”列中有值。当您想将值放入“N”列时,请修改
sheet1.getRange(`O1:O${lastRow1}`).setValues(res);
到
sheet1.getRange(`N1:N${lastRow1}`).setValues(res);
.
参考文献: