使用VBA生成Excel目录列表

本文介绍如何使用VBA自动生成Excel文档的目录列表。通过编写VBA代码,创建一个‘索引’工作表,并在其中添加按钮,点击即可更新链接到所有其他工作表的索引。
摘要由CSDN通过智能技术生成
一、个人需求

最近使用Excel整理一些术语解释的文档,每个术语都对应一个sheet,最后有个索引页,可以快速链接到指定的sheet。

由于sheet会不断增加,做索引页时需要自动生成。考虑使用VBA实现,由于初次接触VBA,在此留个备份。


二、功能实现


(1)新建“索引”sheet,在此工作表中插入一个“生成索引”的按钮,如下图:




 (2)为此按钮添加事件处理代码,如下&#x

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
您可以使用以下VBA代码在Excel生成目录: ``` Sub GenerateTableOfContents() Dim sh As Worksheet Dim tocSheet As Worksheet Dim i As Long Dim j As Long Dim tocRow As Long Set tocSheet = Worksheets.Add(after:=Worksheets(Worksheets.Count)) tocSheet.Name = "Table of Contents" tocSheet.Range("A1").Value = "Table of Contents" tocRow = 3 For Each sh In ThisWorkbook.Worksheets If sh.Name <> tocSheet.Name Then tocSheet.Hyperlinks.Add Anchor:=tocSheet.Cells(tocRow, 1), _ Address:="", _ SubAddress:="'" & sh.Name & "'!A1", _ TextToDisplay:=sh.Name tocRow = tocRow + 1 For i = 1 To sh.OutlineLevels.Count If sh.OutlineLevels(i) = 1 Then tocSheet.Cells(tocRow, 2).Value = sh.Cells(i, 1).Value tocSheet.Cells(tocRow, 2).IndentLevel = 1 tocSheet.Hyperlinks.Add Anchor:=tocSheet.Cells(tocRow, 1), _ Address:="", _ SubAddress:="'" & sh.Name & "'!" & sh.Cells(i, 1).Address, _ TextToDisplay:=sh.Cells(i, 1).Value tocRow = tocRow + 1 End If If sh.OutlineLevels(i) = 2 Then tocSheet.Cells(tocRow, 2).Value = sh.Cells(i, 1).Value tocSheet.Cells(tocRow, 2).IndentLevel = 2 tocSheet.Hyperlinks.Add Anchor:=tocSheet.Cells(tocRow, 1), _ Address:="", _ SubAddress:="'" & sh.Name & "'!" & sh.Cells(i, 1).Address, _ TextToDisplay:=sh.Cells(i, 1).Value tocRow = tocRow + 1 End If Next i tocSheet.Cells(tocRow, 1).Value = "" tocRow = tocRow + 1 End If Next sh tocSheet.Columns("A:B").AutoFit tocSheet.Activate End Sub ``` 此代码会创建一个名为“Table of Contents”的新工作表,并将所有现有工作表的名称和其大纲级别1和2的单元格添加到该表中,同时在目录中创建超链接,以便单击目录中的条目后可以快速跳转到相应的工作表和单元格。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

八零后琐话

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值