Every end of the month I duplicate a tab with multiple hidden rows, then delete all those hidden rows from the duplicate tab. For that purpose I modified the following code of Tanaike, the code running without any error, but all hidden rows still there.
Please advice what correction should be made for the code.
Here is the modified code:
function deleteHiddenRows() {
const spreadsheetId = SpreadsheetApp.openById(gid);
const sheetName = spreadsheetId.getSheetByName(tab);
const lastRow = sheetName.getLastRow();
const sheetId = sheetName.getSheetId();
const fields = "sheets(data(rowMetadata(hiddenByUser)),properties/sheetId)";
const rowMetadata = SheetsV4.Spreadsheets.get(gid, { fields: fields }).sheets[0].data[0].rowMetadata;
const requests = rowMetadata.reduce((ar, { hiddenByUser }, i) => {
if (hiddenByUser && i > 0 && i + 1 < lastRow) ar.push({ deleteDimension: { range: { sheetId, startIndex: i, endIndex: i + 1, dimension: "ROWS" } } });
return ar;
}, []);
SheetsV4.Spreadsheets.batchUpdate({requests}, gid);
}
@Alma_Matters provided a code that solved my problem, if my file only had 1 tab. Since my file had more than 1 tab (my fault for not providing the exact condition at the first place), the code won't work as what I want.
Then I did some troubleshooting to the original code, and finally found a workaround. Following is the code that solved my real case.
const gid = '###'; //spreadsheet id
const tab = 'tab name'; //tab name
function deleteHiddenRows() {
const spreadsheetId = SpreadsheetApp.openById(gid);
const sheetName = spreadsheetId.getSheetByName(tab);
const lastRow = sheetName.getLastRow();
const sheetId = sheetName.getSheetId();
const idx = sheetName.getIndex()-1; //get the index of the tab
const fields = "sheets(data(rowMetadata(hiddenByUser)),properties/sheetId)";
const rowMetadata = Sheets.Spreadsheets.get(gid, { fields: fields}).sheets[idx].data[0].rowMetadata;
const requests = rowMetadata.reduceRight((ar, { hiddenByUser }, i) => {
if (hiddenByUser && i > 0 && i + 1 < lastRow) {
ar.push({
deleteDimension: {
range: {
sheetId, startIndex: i, endIndex: i + 1, dimension: "ROWS"
}
}
});
}
return ar;
}, []);
if(requests.length > 0){
Sheets.Spreadsheets.batchUpdate({requests}, gid);
}
}