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.

EXCELのシートを目次順に並べる

Posted at

あまり使う機会はないのだけど、EXCELで設計書などを記述する場合、シート順が決められているケースがあって、結構手間がかかるのでVBAにしました。
実はネットに色々サンプルあるんですが、ダミーのシートを作成して最後に消す、みたいなサンプルばかりで、シートを並べ替えるのに大げさ感あるのと、エラーが起きたらダミーシート残っちゃうので、もっと単純なロジックを書きました。

ロジックは、なんのことはない、シート名を書いた目次セルをう読み込んで一番最後に移動します。

Public Sub 目次頁にいたら順にシートを並べる()
    Const LIST_SHEET_NAME = "目次"  'シート一覧の物理的なシート名
    
    '目次にいななら処理中断
    If ActiveSheet.Name <> LIST_SHEET_NAME Then
        MsgBox "シート並べ替えは目次ページで実行してください"
        Exit Sub
    End If
    Dim ListSheet
    Set ListSheet = ActiveSheet
    '
    '目次を最後に
    Worksheets(LIST_SHEET_NAME).Move After:=Worksheets(Worksheets.Count)
     
    Dim i As Long
    For i = 1 To Worksheets.Count
        If Trim(ListSheet.Cells(i, 2).Value) = "" Then
            Exit For
        End If
        Worksheets(ListSheet.Cells(i, 2).Value).Move After:=Worksheets(Worksheets.Count)
    Next i
    Worksheets(LIST_SHEET_NAME).Select
    MsgBox "シートの並べ替えが終わりました。"
End Sub

ついでに一覧も(汚いソースで恥ずかしいけど)

Public Sub シート一覧作成()
    Const LIST_SHEET_NAME = "目次"
    Const LIST_NO_COLIDX = 1
    Const LIST_NAME_COLIDX = 2
    Dim intIdx As Integer
    Dim intWksCnt As Integer
    Dim objWks As Object
    Dim strWks() As String
    Dim intLstShtIdx As Integer
    Dim intLstIdx As Integer
    Dim strSubAdr As String
    intLstShtIdx = -1
    intWksCnt = Excel.ActiveWorkbook.Worksheets.Count
    ReDim strWks(intWksCnt)
    For intIdx = 1 To intWksCnt
        strWks(intIdx) = Worksheets(intIdx).Name
        If strWks(intIdx) = LIST_SHEET_NAME Then
            intLstShtIdx = intIdx
        End If
    Next
    If intLstShtIdx < 0 Then
        Set objWks = ActiveWorkbook.Worksheets.Add(Before:=Worksheets(1))
        objWks.Name = LIST_SHEET_NAME
    Else
        Set objWks = Worksheets(LIST_SHEET_NAME)
    End If
    objWks.Select
    Range("A1:B999").ClearContents
    intLstIdx = 0
    For intIdx = 1 To intWksCnt
        If intLstShtIdx <> intIdx Then
            intLstIdx = intLstIdx + 1
            Cells(intLstIdx, LIST_NO_COLIDX) = intLstIdx
            Cells(intLstIdx, LIST_NAME_COLIDX) = "
            strSubAdr = "
            ActiveSheet.Hyperlinks.Add _
                Anchor:=Cells(intLstIdx, LIST_NAME_COLIDX), _
                Address:="", SubAddress:=strSubAdr, TextToDisplay:=strWks(intIdx)
        End If
    Next
End Sub

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?