问题
I have a spreadsheet with various filter views set in place. Normally this works great but occasionally new rows are added and I have to manually update the range in each filter view. I've tried searching for solutions online and came up with the following code that might update the range:
function UpdateFilterView() {
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data');
//for each (var dataSheet in sheets){
var lastRow = dataSheet.getLastRow();
var lastColumn = dataSheet.getLastColumn();
var sheetId = dataSheet.getSheetId();
var filterSettings = {
"filterViewId": "319575141",
"range":{
"sheetId": sheetId,
"startRowIndex": 1,
"endRowIndex": lastRow,
"startColumnIndex": 1,
"endColumnIndex": lastColumn
}
//}
};
var requests = [{
"fields": "*",
"updateFilterView":{
"filter": filterSettings
}
}];
Sheets.Spreadsheets.batchUpdate({"requests":requests},sheetId);
}
I took most of the code from a post I found (here) but for some reason it won't update the specified filter. Am I missing something? Also, I get the following error when I run the code "ReferenceError: Sheets is not defined (line 32, file "Code")" of which is referencing the line "Sheets.Spreadsheets.....".
Any thoughts on if this is even possible?
回答1:
From your replying, I could confirm that in your current situation, Sheets API was enabled at Advanced Google services. By this, I could confirm your error message was changed. In order to resolve the new issue, how about this modification?
Modification points:
- Please modify
sheetId
ofSheets.Spreadsheets.batchUpdate({"requests":requests},sheetId);
to the spreadsheet ID. - Please include
"fields": "*"
in the object ofupdateFilterView
.
When your script is modified, please modify as follows.
Modified script:
function UpdateFilterView() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Added
var dataSheet = ss.getSheetByName('Data'); // Modified
var lastRow = dataSheet.getLastRow();
var lastColumn = dataSheet.getLastColumn();
var sheetId = dataSheet.getSheetId();
var filterSettings = {
"filterViewId": "319575141",
"range":{
"sheetId": sheetId,
"startRowIndex": 1,
"endRowIndex": lastRow,
"startColumnIndex": 1,
"endColumnIndex": lastColumn
}
};
var requests = [{
"updateFilterView":{
"filter": filterSettings,
"fields": "*", // Modified
}
}];
Sheets.Spreadsheets.batchUpdate({"requests":requests}, ss.getId()); // Modified
}
Note:
- When
filterViewId
of319575141
is not correct, an error likeInvalid value at 'requests[0].update_filter_view.filter.filter_view_id
occurs. Please be careful this.
References:
- Method: spreadsheets.batchUpdate
- UpdateFilterViewRequest
来源:https://stackoverflow.com/questions/62569534/update-google-sheet-filter-view-w-new-range