0

I am trying to run a Google Script to delete unused filter views. I found the script on Stackoverflow

function delUnusedFilterViews() {

  var ssId = SpreadsheetApp.getActive().getId();
  var sheetName = SpreadsheetApp.getActiveSheet().getName();
  SpreadsheetApp.getActiveSpreadsheet().toast('Removing unnamed Filters from sheet: ' + sheetName);
  var allFilters = Sheets.Spreadsheets.get(ssId).sheets[0].filterViews;
  var filterArr =[];
  for (var i in allFilters) {
    var currFilter = allFilters[i];
    var filterName = currFilter.title;
    var currFilterId = currFilter.filterViewId;
    if (/Filter [0-9]/.test(filterName)) filterArr.push({ deleteFilterView: { filterId: currFilterId } })
  }
   Sheets.Spreadsheets.batchUpdate({
      requests: filterArr
    },
      ssId
    )
  Browser.msgBox("All Done. You need to reload the sheet to see the filters have been deleted");
}

I've never run a Google Script before, so I went through the process of adding in the "Sheets" services. However, I'm getting this error when I run it and I don't know what's going wrong:

GoogleJsonResponseException: API call to sheets.spreadsheets.batchUpdate failed with error: Must specify at least one request.

Rubén
  • 34,714
  • 9
  • 70
  • 166
dataviolet
  • 33
  • 3
  • The problem is that you are calling batchUpdate before you are creating any request. That's what batchUpdate needs because it's job is to process [requests](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request) – Cooper Aug 31 '22 at 18:48
  • how would I go about fixing this? – dataviolet Aug 31 '22 at 20:35
  • 1
    https://stackoverflow.com/questions/54632698/mass-delete-filter-views-in-google-sheets – Cooper Aug 31 '22 at 22:12

1 Answers1

0

I'm writing this answer as a community wiki, since the issue was resolved in a different post, but I will explain what the script does.

I tested the script and it works. There are a couple of things that you need to keep in mind when running the script.

  1. This script will delete the unnamed filters. For example, from the list below, it will delete "Filter 1" and "Filter 2" because that's the default name it assigns when you don't specify a name for a new Filter view.

enter image description here

  1. In this line var allFilters = Sheets.Spreadsheets.get(ssId).sheets[0].filterViews; you need to specify the sheet where you want to get the unnamed filters, count starts from 0, so let's say for example you have unnamed filters in Sheet2, you have to changesheets[0] to sheets[1].

enter image description here

  1. If you don't have unnamed filters in the sheet that you specified in the line above, then it will fail and return the error that you're getting.
Lorena Gomez
  • 1,946
  • 2
  • 4
  • 11