【问题标题】:Find and replace based on criteria with Google Apps Scripts Code使用 Google Apps 脚本代码根据条件查找和替换
【发布时间】:2021-04-01 14:33:55
【问题描述】:

我有两个 Google 表格位于同一个电子表格对象中,作为参考,我将它们称为数据和变更日志。

Data Sheet

ID   Country   Attribute   Value
1    USA       X           100
2    RUS       X           77
3    MEX       Y           32
4    GER       Z           111
...
Change-Log Sheet

Country   Attribute   Value
USA       X           84
GER       Z           97
Updated Data Sheet

ID   Country   Attribute   Value
1    USA       X           84
2    RUS       X           77
3    MEX       Y           32
4    GER       Z           97
...

目前我正在通过 API 提取数据表,该 API 每月都会清除和更新。

理想情况下,我想编写某种辅助函数,可以查询数据表以获取两个表之间共享的条目,并用更改日志中的相应值覆盖数据表中的值。

在上面的示例中,我想查询 Country 和 Indicator 变量在哪里相同,然后比较 Value 变量并通过在适当的数据表中覆盖该值来优先选择 Change-Log.Value 条目。

【问题讨论】:

  • 您能否展示您已经尝试过的任何工作以及任何记录的错误或问题?
  • 很遗憾,我无法理解Ideally I would like to write some sort of helper function that can parse through the Data sheet and update the value based upon shared criteria from both sheets. I would like to make this exclusively with JS code, and trigger the function after the monthly updating of data from the API I am using.。我为此道歉。我可以问一下您当前问题的详细信息和您的目标吗?

标签: javascript google-apps-script google-sheets google-sheets-api


【解决方案1】:

关于您的床单的外观和您想要做什么,我们掌握的信息非常少。 你可以这样做:

function test() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();

  const dataSheet = ss.getSheetByName("Data");
  const dataRange = dataSheet.getRange(2, 1, dataSheet.getLastRow() - 1, 4);
  const dataValues = dataRange.getValues(); // Get at once, faster execution

  const changeLogSheet = ss.getSheetByName("Change-Log");
  const replacements = changeLogSheet.getRange(2, 1, changeLogSheet.getLastRow() - 1, 3).getValues(); // Faster

  const newValues = [];
  dataValues.forEach(row => {
    const replacementValue = getReplacementValue_(row[1], row[2], replacements);
    newValues.push([row[0], row[1], row[2], (replacementValue ? replacementValue : row[3])]);
  });

  dataRange.setValues(newValues); // Faster
}

function getReplacementValue_(country, attribute, replacements) {
  const matchingRows = replacements.filter(row => row[0] == country && row[1] == attribute);
  return matchingRows.length > 0 ? matchingRows[0][2] : null;
}

我不确定您是要每次都覆盖所有数据,还是从某行开始。

注意 1:如果您的问题是“这是我的目标和代码到目前为止,这些是错误和问题”,Stack Overflow 社区将能够为您提供更多帮助。如果您问“如何做某事”,我们将无法为您提供太多帮助。

注意 2:如果某些答案对您有帮助,请点赞/接受。如果没有,请编辑您的问题以提供更多信息。在这种情况下,如果您可以制作一份工作表副本(如果数据敏感,则用模拟数据替换)并与互联网上的任何人共享并在您的问题中发布链接,那将是一件好事。类似于“数据”表、“更改日志”表和“所需数据”表。

【讨论】:

    猜你喜欢
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多