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.

googlespreadsheetのシートを並べなおすGASを書いた

Posted at

google spreadsheetは実に至らないアプリでいろいろ腹が立つことがあるのだけど、中でも仕様書として使わざるを得なくなった時、どうしてもシートが増えていくのだけど、シートの並べ替えが苦痛でしょうがなかった。
で、あまりに腹が立ったので仕様書用のGASで目次を作ると同時にシートを目次の順に従って並べ直すスクリプトを書いたのだけど、それを単純化して切り出したのがこのGAS。
前に公開した目次と組み合わせるのはコード屋なら簡単だと思うのでバラしたままにしておく。
機能的には実行すると
gas_sample1.jpg

gas_sample3.jpg
のように並べ直される。
以下、コード。

sortsheet.gs
function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet(); // ともかくspreadsheetを取得する。
  const contSheet = ss.getActiveSheet();
  const sheets = ss.getSheets();

  let narray=[];
  sheets.forEach(item=>{
    narray.push(item.getSheetName());
  });

  console.log(narray);
  narray.sort();   // sortはお好みで。
  console.log(narray);

  let i=1;
  narray.forEach(item=>{
    ss.getSheetByName(item).activate();  // アクティブにしないと動かせない。
    ss.moveActiveSheet(i);
    i++;
  });
  contSheet.activate(); // 最後にactiveだったシートに戻る。
}

なお、ちょっとだけ書いておくとmoveActiveSheetを実行するためにはシートをアクティブにしなければならない制約があるので、ボタンなどでシート側から起動すると、バタバタシートが切り替わって、実にキモい挙動をするので注意。

前の目次生成用と組み合わせると結構幸せになれるかも知れない。

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?