javascript - 编辑谷歌表格应用脚本中过滤行中的单元格值
问题描述
这个问题与这个答案有关。
我正在过滤一些具有特定单元格值的行:
.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
});
}
如何更新每个过滤行的单元格?
解决方案
在其他方法中,我想建议使用 TextFinder 和 RangeList 来实现您的目标。示例脚本如下。
示例脚本:
position_1
请设置、position_2
和searchText
的变量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);
}
- 该脚本的流程如下。
- 检索搜索范围。
- 搜索 searchText 并检索范围列表。
- 使用范围列表替换单元格值。
- 在这种情况下,只有要替换的单元格值才会被替换。因此,即使被替换的单元格以外的单元格具有公式,也可以使用此脚本。
参考:
推荐阅读
- reactjs - redux 自定义 reducer 如何与 Thunk 配合使用
- xml - 使用 Xpath 搜索网站以查找文本部分
- php - 将 Ajax JQuery 选择器保存在数组中
- java - 如何避免java安全信息弹出?
- java - Java Websocket 客户端作为 Servlet (App Engine)
- java - 给定根节点和目标节点的二叉树的总和是多少?
- typescript - 可以弄清楚如何让 TypeScript 对返回的 Promise 感到满意
- haskell - 在 Haskell Stack+Nix 项目中设置 XDG_RUNTIME_DIR
- google-apps-script - Google Script 中的排序规则与 Google Sheets 不同——怎么办?
- react-spring - 使用 react-spring 进行 onclicks 翻译的正确方法是什么