问题与this answer有关。
我正在过滤具有特定单元格值的一些行:
.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
});
}
如何更新每个过滤行的单元格?
答案 0 :(得分:2)
我会使用带有条件的 .map() 函数在箭头函数内部,而不是由于电子表格的性质,关于 Apps 脚本需要二维值数组来设置值。这是我的方法:
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 = dataValues.map(row => {
if(row[position_1] !== 'value') return row
// Update the value and return row
row[position_2] = 'new_value'
return row
});
dataRange
.offset(headers, 0, dataRange.getNumRows() - headers)
.setValues(dataValues);
}
答案 1 :(得分:2)
在其他方法中,我想建议使用 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);
}
答案 2 :(得分:1)
假设我们要查找第一个单元格中包含“a1”的所有行,并将这些行的第二个单元格更改为“zzz”:
var dataValues = [
["a1", "b1", "c1"],
["a2", "b2", "c2"],
["a3", "b3", "c3"],
["a1", "b1", "c1"],
["a2", "b2", "c2"],
["a3", "b3", "c3"]
];
var value = "a1";
var position_1 = 0;
var new_value = "zzz";
var position_2 = 1;
var filtered_dataValues = dataValues.filter(row => {
if (row[position_1] == value) { row[position_2] = new_value; return row; }
else { return false; }
});
console.log(filtered_dataValues); // [ [ 'a1', 'zzz', 'c1' ], [ 'a1', 'zzz', 'c1' ] ]