学习并仿制守柔老师的代码:
Sub InsertBookmarkHyperlinker() '以下代码完成的功能是在表格将自动插入书签和将指定单元格 '链接到TOP文本所在位置,并将TOP所在位置链接到表格指定单元格 '起始位置 Dim myTable As Table, oCell As Cell Dim cellRange As Range Dim myRange As Range, TopCount As Integer, strFind As String Dim TopRange As Range, BkName As String, HyBkName As String Dim i As Integer strFind = "SGM News Clipping from China Top^p" '定义一个查找的字符串,为精确起见,加上段落标记 With ActiveDocument If .Tables.Count < 1 Then Exit Sub '如果没有表格(目录),则退出运行 .Fields.Unlink '去除超链接,这是为确保查找的准确性 Set myTable = .Tables(1) '定义一个表格对象 For i = 2 To myTable.Rows.Count Set cellRange = myTable.Cell(i, 1).Range BkName = VBA.Format(i - 1, "000") .Bookmarks.Add Name:="A" & BkName, Range:=cellRange Set cellRange = myTable.Cell(i, 5).Range.Paragraphs(1).Range Set cellRange = .Range(cellRange.Start, cellRange.End - 1) .Hyperlinks.Add Anchor:=cellRange, SubAddress:="B" & BkName, ScreenTip:="转到详细内容" Next Set myRange = .Content '定义一个RANGE对象,为主文档文字部分 With myRange.Find '查找 .ClearFormatting '清除格式 .Text = strFind Do While .Execute And myRange.Hyperlinks.Count = 0 '如果找到没有超级链接的这个段落文本 TopCount = TopCount + 1 '计数 Set TopRange = myRange.Words(6) 'TOP词组所在的RANGE位置 BkName = "B" & VBA.Format(TopCount, "000") '定义一个书签名 HyBkName = "A" & VBA.Format(TopCount, "000") '定义一个超级链接的名称(位置) '添加一个书签 ActiveDocument.Bookmarks.Add Name:=BkName, Range:=TopRange '添加一个超级链接 ActiveDocument.Hyperlinks.Add Anchor:=TopRange, Address:="", SubAddress:=HyBkName _ , ScreenTip:="返回目录" Loop End With End With End Sub |