根据ID匹配将单元格数据更新/复制到另一个工作表
我正在根据唯一 ID 匹配将数据从工作表 1更新到工作表 2
例如,如我的工作表 1 的屏幕截图所示,其中包含唯一 ID。我想要做的是,当我更新工作表 1 中的已售状态时,我希望将工作表 2 更新为与 ID 匹配的已售出(在编辑时)。
在我的搜索中,我发现了这个答案Click Here接近我的期望,但由于某种原因它不起作用,
在这方面你能帮我吗?提前致谢。
回答
我相信你的目标如下。
- 您有 2 个 Google 电子表格,例如“WorkSheet 1”和“WorkSheet 2”。
- 您希望
Sold在单元格中编辑“WorkSheet 1”中特定工作表的“D”列时运行脚本。 - 运行脚本时,您要检查编辑行的“A”列的 ID,并将其值放入
Sold“WorkSheet 2”中特定工作表的“D”列。在这种情况下,您希望将该值与“WorkSheet 2”中特定工作表的“A”列中的 ID 放在同一行。 - 您想使用 Google Apps 脚本来实现这一点。
在这种情况下,需要使用 2 个 Google 电子表格。由此,SpreadsheetApp.openById使用。所以需要使用OnEdit的可安装触发器。示例脚本如下。为了在“WorkSheet 2”中搜索 ID,使用了 TextFinder。
不幸的是,从On my search, I found out this answer Click Here was close to my expectation but It's not working for some reason,,我无法理解您的测试脚本。所以在这个答案中,我提出了一个示例脚本。
示例脚本:
请将以下脚本复制并粘贴到“WorkSheet 1”的脚本编辑器中,并将 OnEdit的可安装触发器安装到installedOnEdit(). 然后,请设置变量spreadsheetIdOfWorksheet2,以及“WorkSheet 1”和“WorkSheet 2”的每个工作表名称。
function installedOnEdit(e) {
const range = e.range;
const sheet = range.getSheet();
if (!(sheet.getSheetName() == "Sheet1" && range.getRow() > 1 && range.getColumn() == 4 && range.getValue() == "Sold")) return;
const srcId = range.offset(0, -3).getValue();
const spreadsheetIdOfWorksheet2 = "###"; // Please set the Spreadsheet ID of "WorkSheet 2" here.
const worksheet2 = SpreadsheetApp.openById(spreadsheetIdOfWorksheet2).getSheetByName("Sheet1");
const dstValues = worksheet2.getRange("A1:A" + worksheet2.getLastRow()).createTextFinder(srcId).findAll();
if (dstValues.length > 0) {
worksheet2.getRangeList(dstValues.map(r => r.offset(0, 3).getA1Notation())).setValue("Sold");
}
}
- 使用此脚本时,请将“WorkSheet 1”中特定工作表的“D”列编辑为
Sold. 通过这种方式,运行脚本并将 的值Sold放入“WorkSheet 2”中特定工作表中具有相同 ID 的同一行。 - 在此示例脚本中,两个 Google 电子表格中特定工作表的工作表名称都是
Sheet1. 所以请根据您的实际情况修改它。
笔记:
- 此示例脚本适用于您提供的示例图像的电子表格。因此,当每个工作表的结构与您的实际情况不同时,脚本可能无法正常工作。所以请注意这一点。
参考:
- 可安装的触发器
- 类文本查找器
- @Miyer Thank you for replying. I apologize for the inconvenience and my poor English skill. From your error message of `TypeError: Cannot read property 'range' of undefined`, I thought that you might directly be running the script with the script editor. In that case, such error occurs because the event object is used in the script.