I'm trying to have a macro read all the sheet names in a workbook and produce a Table of Contents (TOC) in which the sheet names are also hyperlinks to the sheet.
I ran into a problem with a notebook in which sheet names were 13E1, 22E2, etc. because the hyperlink subaddress gets interpreted as a scientific number and therefore the link tries to point to sheet names like 130 or 2200 (using the above 13E1 & 22E2).
As you can see in my code below, I tried declaring the variable as type string and tried using Cstr; neither works.
Any ideas or solutions?
Sub TOC()
Dim i As Integer
Dim bTocExist As Boolean
Dim txtNewLink As String
bTocExist = False
For i = 1 To Worksheets.Count
If Worksheets(i).Name = ("-TOC-"
Then bTocExist = True: Exit For
Next
If bTocExist = False Then
Worksheets.Add.Move Before:=Sheets(1)
ActiveSheet.Name = ("-TOC-"
End If
Worksheets("-TOC-"
.Select
Worksheets("-TOC-"
.Cells(1, 1) = "Page"
Worksheets("-TOC-"
.Cells(1, 1).Font.Bold = True
Worksheets("-TOC-"
.Cells(1, 2) = "SheetName"
Worksheets("-TOC-"
.Cells(1, 2).Font.Bold = True
Sheets(2).Activate
For i = 2 To Worksheets.Count
Worksheets("-TOC-"
.Cells(i, 1) = i - 1
Worksheets("-TOC-"
.Cells(i, 2) = ActiveSheet.Name
txtNewLink = CStr("'" & Format(ActiveSheet.Name) & "'" & "!A1"
Worksheets("-TOC-"
.Cells(i, 2).Hyperlinks.Add _
Anchor:=Worksheets("-TOC-"
.Cells(i, 2), _
Address:="", _
SubAddress:=CStr(txtNewLink), _
TextToDisplay:=CStr(ActiveSheet.Name)
If i < Worksheets.Count Then ActiveSheet.Next.Select
Next
Worksheets("-TOC-"
.Activate
Cells(1, 1).Select
End Sub
I ran into a problem with a notebook in which sheet names were 13E1, 22E2, etc. because the hyperlink subaddress gets interpreted as a scientific number and therefore the link tries to point to sheet names like 130 or 2200 (using the above 13E1 & 22E2).
As you can see in my code below, I tried declaring the variable as type string and tried using Cstr; neither works.
Any ideas or solutions?
Sub TOC()
Dim i As Integer
Dim bTocExist As Boolean
Dim txtNewLink As String
bTocExist = False
For i = 1 To Worksheets.Count
If Worksheets(i).Name = ("-TOC-"
Next
If bTocExist = False Then
Worksheets.Add.Move Before:=Sheets(1)
ActiveSheet.Name = ("-TOC-"
End If
Worksheets("-TOC-"
Worksheets("-TOC-"
Worksheets("-TOC-"
Worksheets("-TOC-"
Worksheets("-TOC-"
Sheets(2).Activate
For i = 2 To Worksheets.Count
Worksheets("-TOC-"
Worksheets("-TOC-"
txtNewLink = CStr("'" & Format(ActiveSheet.Name) & "'" & "!A1"
Worksheets("-TOC-"
Anchor:=Worksheets("-TOC-"
Address:="", _
SubAddress:=CStr(txtNewLink), _
TextToDisplay:=CStr(ActiveSheet.Name)
If i < Worksheets.Count Then ActiveSheet.Next.Select
Next
Worksheets("-TOC-"
Cells(1, 1).Select
End Sub