Advertisement
gn4711

Excel create TOC sheet

Jul 28th, 2015
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Option Explicit
  2. Sub Create_TOC()
  3.     Dim wbBook As Workbook
  4.     Dim wsActive As Worksheet
  5.     Dim wsSheet As Worksheet
  6.    
  7.     Dim lnRow As Long
  8.     Dim lnPages As Long
  9.     Dim lnCount As Long
  10.    
  11.     Set wbBook = ActiveWorkbook
  12.    
  13.     With Application
  14.         .DisplayAlerts = False
  15.         .ScreenUpdating = False
  16.     End With
  17.    
  18.    
  19.     On Error Resume Next
  20.     With wbBook
  21.         .Worksheets("TOC").Delete
  22.         .Worksheets.Add Before:=.Worksheets(1)
  23.     End With
  24.     On Error GoTo 0
  25.    
  26.     Set wsActive = wbBook.ActiveSheet
  27.     With wsActive
  28.         .Name = "TOC"
  29.         With .Range("A1:B1")
  30.             .Value = VBA.Array("Table of Contents", "Sheet # – # of Pages")
  31.             .Font.Bold = True
  32.         End With
  33.     End With
  34.    
  35.     lnRow = 2
  36.     lnCount = 1
  37.    
  38.    
  39.     For Each wsSheet In wbBook.Worksheets
  40.         If wsSheet.Name <> wsActive.Name Then
  41.             wsSheet.Activate
  42.             With wsActive
  43.                 .Hyperlinks.Add .Cells(lnRow, 1), "", _
  44.                 SubAddress:="'" & wsSheet.Name & "'!A1", _
  45.                 TextToDisplay:=wsSheet.Name
  46.                 lnPages = wsSheet.PageSetup.Pages().Count
  47.                 .Cells(lnRow, 2).Value = "‘" & lnCount & " - " & lnPages
  48.             End With
  49.             lnRow = lnRow + 1
  50.             lnCount = lnCount + 1
  51.         End If
  52.     Next wsSheet
  53.    
  54.     wsActive.Activate
  55.     wsActive.Columns("A:B").EntireColumn.AutoFit
  56.    
  57.     With Application
  58.         .DisplayAlerts = True
  59.         .ScreenUpdating = True
  60.     End With
  61. End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement