0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Google Apps Scriptでスプレッドシートの表にフィルターを表示させる

Last updated at Posted at 2021-10-20

Google Apps Script(GAS)でスプレッドシートにフィルターを表示させるためのコード。

const sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1, 1, 5, 5).setValues("データがある配列など").createFilter()

.createFilter()がポイント。

このコードだと確かにフィルターは設定されるものの、2回目以降の実行で「すでにフィルターが設定されているから処理できません」とエラーになる。

そのため「すでにフィルターが設定されている場合は、フィルターを削除した後新しく設定し直す」という処理を書く必要がある。

const sheet = SpreadsheetApp.getActiveSheet();
if(sheet.getFilter() != null) {
  sheet.getFilter().remove();
}
sheet.getDataRange().createFilter()

if文でフィルターがあるかどうかを判別し、「nullじゃない=設定されている」場合にremoveで削除し、新たにフィルターを設定する際にエラーが起きないようにしている。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?