Reputation: 9194
I have a file that needs to get copied about 125 times: one copy for each user. There are about 1,000 rows in the sheet. I elected to just copy this file so that protected ranges, formatting, filters, etc. follow it without having to recreate them.
The Apps Script I have thus far:
!documentObject.isRowHiddenByFilter(row)
and deletes the row if true
.For removing the visible rows, I'm doing the following:
deleteVisibleRows(documentObject, lastRow) {
for (let r = lastRow; r > 1; r--) {
if(!documentObject.isRowHiddenByFilter(r)) {
documentObject.deleteRow(r);
}
}
}
This is really slow: 125 iterations * 1000 rows = 125,000 rows
.
I'd much prefer to be able to just selectRange
and deleteVisibleRows
without iteration to speed this up.
From what I can tell, there isn't a method for just deleting visible rows. It is very likely visible and not visible rows will not be consecutive either.
Any suggestions?
Upvotes: 0
Views: 153
Reputation: 201398
I believe your goal is as follows.
In this case, I thought that when Sheets API is used, the process cost can be reduced. So in this answer, I would like to propose using Sheets API.
From your script, I understood that your values of documentObject
and lastRow
are the object of the Class Sheet and the integer number, respectively. In this answer, these values are used in the request for Sheets API. When your script of deleteVisibleRows
is modified, it becomes as follows.
Before you use this script, please enable Sheets API at Advanced Google services.
function deleteVisibleRows(documentObject, lastRow) {
const spreadsheetId = documentObject.getParent().getId();
const sheetName = documentObject.getSheetName();
const sheetId = documentObject.getSheetId();
const rowMetadata = Sheets.Spreadsheets.get(spreadsheetId, { ranges: [sheetName], fields: "sheets(data(rowMetadata(hiddenByFilter)))" }).sheets[0].data[0].rowMetadata;
const requests = rowMetadata.reduceRight((ar, { hiddenByFilter }, i) => {
if (!hiddenByFilter && i > 0 && i + 1 < lastRow) ar.push({ deleteDimension: { range: { sheetId, startIndex: i, endIndex: i + 1, dimension: "ROWS" } } });
return ar;
}, []);
Sheets.Spreadsheets.batchUpdate({requests}, spreadsheetId);
}
Upvotes: 1