问题
I have the following code to clear all filters in every sheet:
function clearAllFilter() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssId = ss.getId();
var sheetIds = ss.getSheets();
for (var i in sheetIds) {
var requests = [{
"clearBasicFilter": {
"sheetId": sheetIds[i].getSheetId()
}
}];
Sheets.Spreadsheets.batchUpdate({'requests': requests}, ssId);
}
}
The code is working well, but I'm getting the following error:

How do I get rid of this error message or better yet, optimize the code to complete its job as quickly as possible?...
EDIT: to add more information, my spreadsheet has a 119 sheets.
回答1:
You might have hit your current quota limit. Be noted for the Usage Limits of the Sheets API.
This version of the Google Sheets API has a limit of 500 requests per 100 seconds per project, and 100 requests per 100 seconds per user. Limits for reads and writes are tracked separately. There is no daily usage limit.
To view or change usage limits for your project, or to request an increase to your quota, do the following:
- If you don't already have a billing account for your project, then create one.
- Visit the Enabled APIs page of the API library in the API Console, and select an API from the list.
- To view and change quota-related settings, select Quotas. To view usage statistics, select Usage.
Hope this helps!
回答2:
@tehhowch comment was all I needed, he gave me a clue and I found a fix to the code.
The error lies in the for loop:
for (var i in sheetIds) {
var requests = [{
"clearBasicFilter": {
"sheetId": sheetIds[i].getSheetId()
}
}];
Sheets.Spreadsheets.batchUpdate({'requests': requests}, ssId);
}
Here I am looping through every sheet in the spreadsheet, obtaining the sheet ID and then calling .batchUpdate()
. The problem here, is that I'm calling the sheets API for every sheet, meaning I'm calling it 119 times for all my 119 sheets.
The above code is inefficient and beyond my quota limit.
FIX:
- Place all the sheets IDs into an array.
- Move the
.batchUpdate()
outside of the for loop - Then do
.batchUpdate({'requests': array}
instead of.batchUpdate({'requests': requests}
So now the code is efficient, instead of calling the sheets API 119 times, now I'm only calling it once, fixing my quota issue and successfully run the script without any error messages.
The complete code:
function clearAllFilter() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssId = ss.getId();
var sheetIds = ss.getSheets();
var idArray = [];
//loop through all the sheets, get the sheet ID, then push into the array
for (var i in sheetIds) {
var requests = [{
"clearBasicFilter": {
"sheetId": sheetIds[i].getSheetId()
}
}];
idArray.push(requests); //now the array stores all the sheet IDs
//Logger.log(idArray);
}
Sheets.Spreadsheets.batchUpdate({'requests': idArray}, ssId); //do .batchUpdate only once by passing in the array
}
来源:https://stackoverflow.com/questions/49375108/im-running-into-some-quota-issue