---
title: "Excel自动生成目录"
author: "zhyt710"
date: "2010-03-30T16:05:17Z"
tags: []
categories: ["编程语言"]
slug: "excel"
draft: false
lastmod: "2010-04-23T15:27:31Z"
id: 628316
url: "https://zhyt710.iteye.com/blog/628316"
---

内容取自http://zhangpeeta.blog.sohu.com/128784050.html

 

具体方法如下

 

1，首先在excel文件的最前面追加一个sheet，命名为“目录”

2，按Alt+F11在弹出的对话框中点插入选择模块然后把下面的代码复制到模块中

Sub mulu()  
    On Error GoTo Tuichu  
    Dim i As Integer  
    Dim ShtCount As Integer  
    Dim SelectionCell As Range

    ShtCount = Worksheets.Count  
    If ShtCount = 0 Or ShtCount = 1 Then Exit Sub  
    Application.ScreenUpdating = False  
    For i = 1 To ShtCount  
        If Sheets(i).Name = "目录" Then  
            Sheets("目录").Move Before:=Sheets(1)  
        End If  
    Next i  
    If Sheets(1).Name &lt;&gt; "目录" Then  
        ShtCount = ShtCount + 1  
        Sheets(1).Select  
        Sheets.Add  
        Sheets(1).Name = "目录"  
    End If  
    Sheets("目录").Select  
    Columns("B:B").Delete Shift:=xlToLeft  
    Application.StatusBar = "正在生成目录…………请等待！"  
    For i = 2 To ShtCount  
        ActiveSheet.Hyperlinks.Add Anchor:=Worksheets("目录").Cells(i, 2), Address:="", SubAddress:= _  
                                   "'" & Sheets(i).Name & "'!R1C1", TextToDisplay:=Sheets(i).Name  
    Next  
    Sheets("目录").Select  
    Columns("B:B").AutoFit  
    Cells(1, 2) = "目录"  
    Set SelectionCell = Worksheets("目录").Range("B1")  
    With SelectionCell  
        .HorizontalAlignment = xlDistributed  
        .VerticalAlignment = xlCenter  
        .AddIndent = True  
        .Font.Bold = True  
        .Interior.ColorIndex = 34  
    End With  
    Application.StatusBar = False  
    Application.ScreenUpdating = True  
Tuichu:  
End Sub

3，复制完成后按F5运行即可，如果后期对表名做了修改，只需要重新F5运行刷新下目录即可。