以下代码来自“Word Hacks: Tips & Tools for Taming Your Text”,自动将所选文本交叉引用到任何具有相同内容的标题。我一直在尝试调整它以自动交叉引用具有相同内容的图形标题,但没有成功。这个想法是,如果用户在任何文本行中选择“图 3-5”(例如在显示“更多信息,请参阅图 3-5”的段落中),代码应该查找相应的图标题和自动插入对它的交叉引用。
Sub MakeAutoXRef()
Dim sel As Selection
Dim rng As range
Dim para As Paragraph
Dim doc As Document
Dim sBookmarkName As String
Dim sSelectionText As String
Dim lSelectedParaIndex As Long
Set sel = Selection
Set doc = sel.Document
If sel.range.Paragraphs.Count <> 1 Then Exit Sub
lSelectedParaIndex = GetParagraphIndex(sel.range.Paragraphs.First)
sel.MoveStartWhile cset:=(Chr$(32) & Chr$(13)), Count:=sel.Characters.Count
sel.MoveEndWhile cset:=(Chr$(32) & Chr$(13)), Count:=-sel.Characters.Count
sSelectionText = sel.text
For Each para In doc.Paragraphs
Set rng = para.range
rng.MoveStartWhile cset:=(Chr$(32) & Chr$(13)), _
Count:=rng.Characters.Count
rng.MoveEndWhile cset:=(Chr$(32) & Chr$(13)), _
Count:=-rng.Characters.Count
If rng.text = sSelectionText Then
If Not GetParagraphIndex(para) = lSelectedParaIndex Then
sBookmarkName = GetOrSetXRefBookmark(para)
If Len(sBookmarkName) = 0 Then
MsgBox "Couldn't get or set bookmark"
Exit Sub
End If
sel.InsertCrossReference _
referencekind:=wdContentText, _
referenceItem:=doc.Bookmarks(sBookmarkName), _
referencetype:=wdRefTypeBookmark, _
insertashyperlink:=True
Exit Sub
Else
MsgBox "Can't self reference!"
End If
End If
Next para
End Sub
Function RemoveInvalidBookmarkCharsFromString(ByVal str As String) As String
Dim i As Integer
For i = 33 To 255
Select Case i
Case 33 To 47, 58 To 64, 91 To 96, 123 To 255
str = Replace(str, Chr(i), vbNullString)
End Select
Next i
RemoveInvalidBookmarkCharsFromString = str
End Function
Function ConvertStringRefBookmarkName(ByVal str As String) As String
str = RemoveInvalidBookmarkCharsFromString(str)
str = Replace(str, Chr$(32), "_")
str = "_" & str
str = "XREF" & CStr(Int(90000 * Rnd + 10000)) & str
ConvertStringRefBookmarkName = str
End Function
Function GetParagraphIndex(para As Paragraph) As Long
GetParagraphIndex = _
para.range.Document.range(0, para.range.End).Paragraphs.Count
End Function
Function GetOrSetXRefBookmark(para As Paragraph) As String
Dim i As Integer
Dim rng As range
Dim sBookmarkName As String
If para.range.Bookmarks.Count <> 0 Then
For i = 1 To para.range.Bookmarks.Count
If InStr(1, para.range.Bookmarks(i).name, "XREF") Then
GetOrSetXRefBookmark = para.range.Bookmarks(i).name
Exit Function
End If
Next i
End If
Set rng = para.range
rng.MoveEnd unit:=wdCharacter, Count:=-1
sBookmarkName = ConvertStringRefBookmarkName(rng.text)
para.range.Document.Bookmarks.Add _
name:=sBookmarkName, _
range:=rng
GetOrSetXRefBookmark = sBookmarkName
End Function