使用batchUpdate使用Apps脚本onEdit设置表格过滤器

时间:2017-08-25 16:08:44

标签: google-apps-script google-sheets

以下示例在手动运行setFilter()函数时正常工作:

https://docs.google.com/spreadsheets/d/1vSDdXU8XSnfG5ixjaMtDys1ynwpbKTptPb_ZFjuMASg/edit#gid=0

function setFilter() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  var filterSettings = {};

  // The range of data on which you want to apply the filter.
  // optional arguments: startRowIndex, startColumnIndex, endRowIndex, endColumnIndex
  filterSettings.range = {
    sheetId: ss.getActiveSheet().getSheetId()
  };

  // Criteria for showing/hiding rows in a filter
  // https://developers.google.com/sheets/api/reference/rest/v4/FilterCriteria
  filterSettings.criteria = {};
  var columnIndex = 2;
  filterSettings['criteria'][columnIndex] = {
    'hiddenValues': ["England", "France"]
  };

  var request = {
    "setBasicFilter": {
      "filter": filterSettings
    }
  };
  Sheets.Spreadsheets.batchUpdate({'requests': [request]}, ss.getId());
}

但该功能在onEdit()

内不起作用
function onEdit(e){
  setFilter();
}

batchUpdate无法使用onEdit吗?

1 个答案:

答案 0 :(得分:1)

正如Sandy Good所说,onEdit之类的简单触发器无法执行任何需要授权的操作,例如修改电子表格。

相反,install a trigger会在每次编辑时运行:它将在您的授权下运行,并且可以通过手动运行该功能来执行任何操作。