【问题标题】:Google Apps Script - Insert values to column B based on values on column A, when there is thousands of rowsGoogle Apps 脚本 - 当有数千行时,根据 A 列上的值向 B 列插入值
【发布时间】:2021-08-20 08:59:53
【问题描述】:

我有一个脚本需要改进。该脚本遍历列 A 上的所有行。然后,它根据值在下一个单元格中插入一个值。例如:如果单元格 A2 上的值为 4,9,那么它将在单元格 B2 中插入 UNDER10。有用。但是,它的工作速度很慢。如果我在 A 列上有数千行,有时脚本会超时。有谁知道让这个脚本更快的方法吗?

下面是我的脚本:

function myFunction() {
  const ss = SpreadsheetApp.getActive().getActiveSheet()
  const lastRow = ss.getLastRow();

  for (var i = 1; i < lastRow +1; i++) {
    var value = ss.getRange(i,1).getValue();
    var newValue = ss.getRange(i,2);
    if (value < 10) {
      newValue.setValue("UNDER10");
    } else if (value < 20) {
      newValue.setValue("UNDER20");
    } else if (value > 20) {
      newValue.setValue("OVER20");
    }
  }  
}

【问题讨论】:

  • 避免在循环内的单个单元格中设置值。相反,写入一个数组,然后在一次调用中将该数组写回电子表格。 Also see this link。不确定为什么要使用脚本执行此操作?似乎这应该很容易用公式来实现......
  • 谢谢我去看看。这是我需要定期运行的功能,这就是我需要脚本的原因。
  • 您是否在此工作表中的其他内容中使用脚本?否则我使用 JPV,在工作表中使用带有嵌套 IF() 公式的 ArrayFormula 将完成同样的事情,并且需要更少的维护。应用脚本的缺点之一 - 除非您非常小心地设置命名范围和工作表,否则对工作表的任何更改都可能破坏您的功能。
  • 是的,这必须通过脚本来完成,因为它会不断运行

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


【解决方案1】:

这种改进应该有效。请注意,我假设 A 列包含数字(谷歌表将 4,9 称为字符串。因此,声明 if(value &lt; 10) 不是真正有效的)。

为了测试我的代码,我使用了 4.9、14.9 等。

function myFunction() {
  const ss = SpreadsheetApp.getActive().getActiveSheet()
  const lastRow = ss.getLastRow();

  // get all the range at once
  let range = ss.getRange(2, 1, lastRow -1, 2);

  // get all the values in 2D array
  let values = range.getValues();

  // for each pair of values [price, custom value], calculate the custom value
  values.forEach((value)=> {

    // NOTE that i parse float out of price.
    // Google sheet refer 4,9 as string (i assume you ment 4.9)
    value[0] = parseFloat(value[0])
    if (value[0] < 10) {
      value[1] = "UNDER10"
    } else if (value[0] < 20) {
      value[1] = "UNDER20";
    } else if (value[0] > 20) {
      value[1] = "OVER20";
    }
  })

  // set the new values into the spreadsheet
  range.setValues(values)
}

如果您要比较每一行中的每个数字(例如,在“A2”单元格中:if(4 &lt; 10 &amp;&amp; 9 &lt; 10)),请发表评论,我会相应地修复。

【讨论】:

  • 谢谢!这工作得非常好而且很快!
猜你喜欢
  • 2021-11-17
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
  • 2018-08-06
  • 2022-07-04
  • 1970-01-01
相关资源
最近更新 更多