之前积累的代码,现在分享一下
Sub 建立目录()
Dim sht As Worksheet
Dim i As Integer
For Each sht In Sheets
If sht.Name = "目录" Then
Exit Sub
End If
Next
Sheets.Add before:=Sheets(1)
Sheets(1).Name = "目录"
Sheets(1).Cells(1, 1) = "序号"
Sheets(1).Cells(1, 2) = "工作表目录"
i = 1
For Each sht In Worksheets
If sht.Visible <> 0 And sht.Name <> "目录" Then
i = i + 1
ActiveSheet.Cells(i, 1) = i - 1
ActiveSheet.Hyperlinks.Add anchor:=Cells(i, 2), Address:="", SubAddress:="'" & sht.Name & "'!a1", TextToDisplay:=sht.Name
End If
Next
End Sub
代码的主要逻辑:首先遍历工作簿下所有的工作表,确定是否存在名为“目录”的工作表。
(1)如果不存在“目录”的工作表,则在第一个工作表前插入一个新的工作表,并命名为“目录”,在A列填充序号,在B列填充工作表目录;
(2)如果已存在“目录”的工作表,则结束程序的执行。
注:代码设置对于隐藏的工作表,不在生成的工作表目录中