使用VBA生成Excel目录列表

一、个人需求

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

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


二、功能实现


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




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





(3)收集各资料sheet信息,例下sheet列表:





(4) 生成后的索引如下图:





三、附代码

Sub create_Click()
    '获取所有sheet的名字
    For x = 2 To Sheets.Count
        'sheet名
        Sheets(1).Cells((x + 2), 3) = Sheets(x).Name
        '序号
        Sheets(1).Cells((x + 2), 2) = "=ROW()-3"
        '超链接
        Range("C" + CStr(x + 2)).Select
        ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:= _
                  Sheets(x).Name + "!A1"
    Next x
    
    '设置指定单元格边框
    Dim rng As Range
    Set rng = Range("B4:C" + CStr(Sheets.Count + 2))
    With rng.Borders
        .LineStyle = xlContinuous
        .ColorIndex = xlAutomatic
        .TintAndShade = 1
        .Weight = xlThin
    End With
    
    '设置指定单元格的字体样式
    Range("B4:C" + CStr(Sheets.Count + 2)).Select
    With Selection
        .Font.Name = "宋体"      '字体
        .Font.Size = 12          '字号
        .WrapText = True         '自动换行
        .Font.Color = FFFFFF     '颜色
    End With
    
    '删除指定范围的单元格内容
    Range("B" + CStr(Sheets.Count + 3) + ":C65530").ClearContents
    '删除指定范围的边框
    Range("B" + CStr(Sheets.Count + 3) + ":C65530").Borders.LineStyle = xlNone
End Sub


你可能感兴趣的:(Microsoft,Office)