I believe your goal as follows.
- You want to retrieve the rows which have
fruit
and red
in the columns "B" and "C", respectively.
- You want to put the retrieved rows to the destination sheet.
- You want to achieve above using Google Apps Script.
Flow:
The flow of this sample script is as follows.
- Retrieve all sheets.
- From each sheet, retrieve the rows which have
fruit
and red
in the columns "B" and "C", respectively.
- At this time,
destinationSheetName
sheet is excluded.
- Put the retrieved rows to the destination sheet.
Sample script:
Before you use this script, please set destinationSheetName
. And in this sample script, destinationSheetName
and "MERGED RED FRUITS" sheet in your shared Spreadsheet are excluded for retrieving rows.
function myFunction() {
const destinationSheetName = "MERGED RED FRUITS (DESIRED RESULT)";
const excludeSheetNames = [destinationSheetName, "MERGED RED FRUITS"];
// 1. Retrieve all sheets.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheets = ss.getSheets();
// 2. From each sheet, retrieve the rows which have `fruit` and `red` in the columns "B" and "C", respectively.
const values = sheets.reduce((ar, s, i) => {
if (!excludeSheetNames.includes(s.getSheetName())) {
const [,...v] = s.getDataRange().getValues();
const temp = v.filter(([,b,c]) => b == "fruit" && c == "red");
if (temp.length > 0) ar = ar.concat(temp);
}
return ar;
}, []);
// 3. Put the retrieved rows to the destination sheet.
const dest = ss.getSheetByName(destinationSheetName);
dest.getRange(2, 1, values.length, values[0].length).setValues(values);
}
Note:
- In this sample script, the duplication of the values is not checked. Please be careful this.
- When I saw your current script in your shared Spreadsheet, it seems that
getValue()
is used in the loop. In this case, the process cost will be high. So I proposed above flow.
References: