【问题标题】:Google Sheets - Update Sheet 1 with data from Sheet 2 if a value on both sheets matchGoogle 表格 - 如果两张表格上的值匹配,则使用表格 2 中的数据更新表格 1
【发布时间】:2017-12-14 02:36:27
【问题描述】:

我在一个电子表格上有两张工作表:

https://docs.google.com/spreadsheets/d/1ahtB9M6rl6aHmj51ZlP_qDqyUwhpsSVg1r16BafcKIo/edit?usp=sharing

使用 Google Apps 脚本,如果每个工作表上 ID 列中的值匹配,我想使用“新数据”工作表上 E 列中的值更新“报告”工作表上 C 列中的值。

在生产中,我预计会有多个独特的匹配。我该怎么做才最好?

作为一个简单的例子,在下面的模拟表中,我希望行 ID 为 12 的报告表的“STATE”列中的值从“Queued”更新为“Won”。

  • 报告表

    ID |状态

    12 |排队

    34 |迷路了

  • 新数据表

    ID |状态

    56 |迷路了

    12 |赢了

【问题讨论】:

  • 很酷的项目。如果您对某事有任何疑问,请告诉我们。
  • 嗨安托万,谢谢!我意识到我没有明确提出问题(只是编辑过)。我希望找出最好的方法?我尝试了几种方法,但都无济于事。
  • 嘿,我看到你投了反对票,这里是a guide to asking better questions。适用于 Stack Overflow 等地方。
  • 谢谢安托万!我猜我的第一个问题几乎可以预料...感谢您的链接,我会检查一下!

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


【解决方案1】:

本周有人问过similar question

这是我的建议,不过您需要调整工作表和标题的名称!

function setCommon() {

  var ss = SpreadsheetApp.getActive(),
      compare1 = "", compare2 = "",

      outputSheet = ss.getSheetByName("Sheet1"),
      sourceSheet = ss.getSheetByName("Sheet2"),

      range1 = outputSheet.getDataRange(),
      range2 = sourceSheet.getDataRange(),

      lastCol1 = range1.getNumColumns(),
      lastCol2 = range2.getNumColumns(),

      values1 = range1.getValues(),
      values2 = range2.getValues(),

      // get the range of the titles
      titleSection1 = outputSheet.getRange(1,1,1, lastCol1),
      titleSection2 = sourceSheet.getRange(1,1,1, lastCol2),

      // get the values from the titles
      titles1 = titleSection1.getValues(),
      titles2 = titleSection2.getValues(),

      // get the column # for "ID" and "comment"
      idCol1 = titles1[0].indexOf("ID"),
      idCol2 = titles2[0].indexOf("ID"),
      commentsCol1 = titles1[0].indexOf("comment"),
      commentsCol2 = titles2[0].indexOf("comment");

  // get the IDs from range1
  for (i = 1; i < values1.length; i++) { 
    compare1 = values1[i][idCol1];

    // get the IDs from range2
    for (j = 1; j< values2.length; j++){
      compare2 = values2[j][idCol2];

      // if same ID, change the values array
      if (compare1 == compare2) {
        values1[i][commentsCol1] = values2[j][commentsCol2];
      }
    }
  }
  // set values based on the values array
  range1.setValues(values1);
}

【讨论】:

  • 感谢安托万!非常感谢您的帮助。我试试看!
猜你喜欢
  • 1970-01-01
  • 2019-07-07
  • 2019-01-03
  • 1970-01-01
  • 2023-02-03
  • 1970-01-01
  • 2021-10-26
  • 1970-01-01
  • 2019-11-30
相关资源
最近更新 更多