首页 > 解决方案 > 编辑谷歌表格应用脚本中过滤行中的单元格值

问题描述

这个问题与这个答案有关。

我正在过滤一些具有特定单元格值的行:

.filter(row => row[position_1] == 'value')

我想从选定的行更新另一个单元格:

row[position_2] = 'new_value'

我试图包含类似上一行代码的内容,但它不起作用。

所以,如果我们有这样的代码:

function selectRecords() {
  const ss = SpreadsheetApp.getActiveSheet();
  const dataRange = ss.getDataRange();
  const headers = 2;
  const dataValues = dataRange
    .offset(headers, 0, dataRange.getNumRows() - headers)//offsetting the headers from the whole range
    .getValues();

  dataValues
    .filter(row => row[position_1] == 'value') 
    .forEach(row => {
           //update the value of a specific cell within the row.
           //extract some cell's values: row[pos_x], row[pos_y], row[pos_z],.. to use it inside the loop
    });
}

如何更新每个过滤行的单元格?

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


在其他方法中,我想建议使用 TextFinder 和 RangeList 来实现您的目标。示例脚本如下。

示例脚本:

position_1请设置、position_2searchText的变量replaceText

function selectRecords() {
  const position_1 = 1; // From your script, 1st index is 0. So, 1 is the column "B".
  const position_2 = 2; // From your script, 1st index is 0. So, 2 is the column "C".
  const searchText = "value"; // Please set the search text.
  const replaceText = "new_value"; // Please set the replace text.

  // 1. Retrieve the search range.
  const ss = SpreadsheetApp.getActiveSheet();
  const headers = 2;
  const range = ss.getRange(3, position_1 + 1, ss.getLastRow() - headers);

  // 2. Search the searchText and retrieve the range list.
  const rangeList = range.createTextFinder(searchText).matchEntireCell(true).findAll().map(r => ss.getRange(r.getRow(), position_2 + 1).getA1Notation());

  // 3. Replace the cell values using the range list.
  if (rangeList.length > 0) ss.getRangeList(rangeList).setValue(replaceText);
}
  • 该脚本的流程如下。
    1. 检索搜索范围。
    2. 搜索 searchText 并检索范围列表。
    3. 使用范围列表替换单元格值。
  • 在这种情况下,只有要替换的单元格值才会被替换。因此,即使被替换的单元格以外的单元格具有公式,也可以使用此脚本。

参考:


推荐阅读