officeba > 单独文章


添加目录到您的excel编程工作簿


下面的代码示例验证工作表命名为“目录”已经存在。如果它存在,例如更新目录。否则,该示例创建的工作簿在开始一个新的目录表。每个工作表的名称,与相应的打印页码一直以来,被列入目录。要检索的例子页码打开打印预览对话框。您必须关闭该对话框,然后在创建表的内容。
Sub CreateTableOfContents()
    ' Determine if there is already a Table of Contents
    ' Assume it is there, and if it is not, it will raise an error
    ' if the Err system variable is > 0, you know the sheet is not there
    Dim WST As Worksheet
    On Error Resume Next
    Set WST = Worksheets("TOC")
    If Not Err = 0 Then
        ' The Table of contents doesn't exist. Add it
        Set WST = Worksheets.Add(Before:=Worksheets(1))
        WST.Name = "TOC"
    End If
    On Error GoTo 0
    
    ' Set up the table of contents page
    WST.[A2] = "Table of Contents"
    With WST.[A6]
        .CurrentRegion.Clear
        .Value = "Subject"
    End With
    WST.[B6] = "Page(s)"
    WST.Range("A1:B1").ColumnWidth = Array(36, 12)
    TOCRow = 7
    PageCount = 0

    ' Do a print preview on all sheets so Excel calcs page breaks
    ' The user must manually close the PrintPreview window
    Msg = "Excel needs to do a print preview to calculate the number of pages. "
    Msg = Msg & "Please dismiss the print preview by clicking close."
    MsgBox Msg
    ActiveWindow.SelectedSheets.PrintPreview

    ' Loop through each sheet, collecting TOC information
    For Each S In Worksheets
        If S.Visible = -1 Then
            S.Select
            ThisName = ActiveSheet.Name
            HPages = ActiveSheet.HPageBreaks.Count + 1
            VPages = ActiveSheet.VPageBreaks.Count + 1
            ThisPages = HPages * VPages

            ' Enter info about this sheet on TOC
            Sheets("TOC").Select
            Range("A" & TOCRow).Value = ThisName
            Range("B" & TOCRow).NumberFormat = "@"
            If ThisPages = 1 Then
                Range("B" & TOCRow).Value = PageCount + 1 & " "
            Else
                Range("B" & TOCRow).Value = PageCount + 1 & " - " & PageCount + ThisPages
            End If
        PageCount = PageCount + ThisPages
        TOCRow = TOCRow + 1
        End If
    Next S
End Sub

声明:欢迎各大网站转载本站文章,还请保留一条能直接指向本站的超级链接,谢谢!

时间:2010-04-15 12:33:46,点击:65824


【OfficeBa论坛】:阅读本文时遇到了什么问题,可以到论坛进行交流!Excel专家邮件:342327115@qq.com(大家在Excel使用中遇到什么问题,可以咨询此邮箱)。

【声明】:以上文章或资料除注明为Office自创或编辑整理外,均为各方收集或网友推荐所得。其中摘录的内容以共享、研究为目的,不存在任何商业考虑。如有任何异议,请与本站联系,本站确认后将立即撤下。谢谢您的支持与理解!


相关评论

我要评论

评论内容