Hide or Show multiple columns in one command
Solution 1:
I believe your goal as follows.
-
You want to reduce the process cost of the following script.
resultsSheet.hideColumns(11); resultsSheet.hideColumns(18); resultsSheet.hideColumns(19); resultsSheet.showColumns(26); resultsSheet.showColumns(27); resultsSheet.showColumns(28); resultsSheet.showColumns(29);
Modification points:
- When
hideColumns
andshowColumns
are used, the arguments arecolumnIndex, numColumns
. In this case, when the columns you want to hide and show are continuously existing like the column "A", "B" and "C", you can achieve this using onehideColumns
andshowColumns
. But when the columns you want to hide and show are scattered, multiplehideColumns
andshowColumns
are required to be used. - In this case, in order to achieve your goal using one call, I would like to propose to use the method of batchUpdate in Sheets API. When Sheets API is used, both
hideColumns
andshowColumns
can be used by one API call.
The sample script is as follows.
Sample script:
Please copy and paste the following script to the script editor of Spreadsheet you want to use. Before you use this script, please enable Sheets API at Advanced Google services. And, please set the sheet name.
function myFunction() {
const hideColumns = [11, 18, 19];
const showColumns = [26, 27, 28, 29];
const sheetName = "Sheet1";
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheetId = ss.getSheetByName(sheetName).getSheetId();
const requests = [];
// Create requests for the hide columns.
if (hideColumns.length > 0) {
hideColumns.forEach(c =>
requests.push({ updateDimensionProperties: { properties: { hiddenByUser: true }, range: { sheetId: sheetId, dimension: "COLUMNS", startIndex: c - 1, endIndex: c }, fields: "hiddenByUser" } })
);
}
// Create requests for the show columns.
if (showColumns.length > 0) {
showColumns.forEach(c =>
requests.push({ updateDimensionProperties: { properties: { hiddenByUser: false }, range: { sheetId: sheetId, dimension: "COLUMNS", startIndex: c - 1, endIndex: c }, fields: "hiddenByUser" } })
);
}
// Request to Sheets API using the created requests.
if (requests.length > 0) Sheets.Spreadsheets.batchUpdate({requests: requests}, ss.getId());
}
- In above sample script, when only
hideColumns
is declared, the columns are hidden usinghideColumns
. when onlyshowColumns
is declared, the columns are shown usingshowColumns
. When bothhideColumns
andshowColumns
are declared, the columns are hidden and shown usinghideColumns
andshowColumns
.- Above process is done by one API call.
- The values of
hideColumns
andshowColumns
are from your script
References:
- hideColumns(columnIndex, numColumns)
- showColumns(columnIndex, numColumns)
- Method: spreadsheets.batchUpdate
- UpdateDimensionPropertiesRequest