可以使用setValues方法和filter方法来复制筛选过的行,并避免重复复制。
示例代码:
function copyFilteredRows() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
// 获取筛选条件
var filter = sheet.getFilter();
var range = filter.getRange();
var values = range.getValues();
var criteria = filter.getColumnFilterCriteria(1);
// 应用筛选条件并复制行
var filteredRange = range.offset(1, 0, range.getNumRows() - 1).getFilteredRanges()[0];
var filteredValues = filteredRange.getValues();
var numRows = filteredValues.length;
var numCols = filteredValues[0].length;
// 复制筛选后的行,并避免重复
var targetSheet = ss.getSheetByName("Sheet2");
var targetRange = targetSheet.getRange(2, 1, numRows, numCols);
targetRange.clearContent();
var targetValues = [];
for (var i = 0; i < numRows; i++) {
var row = filteredValues[i];
var shouldCopy = true;
for (var j = 0; j < numCols; j++) {
var criterion = criteria[j];
if (criterion && !criterion.isValidValue(row[j])) {
shouldCopy = false;
break;
}
}
if (shouldCopy) {
targetValues.push(row);
}
}
targetRange.setValues(targetValues);
}