如何解决MS Word - 链接到当前部分的标题/相对引用
我正在处理一个带有多级标题的大型文档,用于一长串测试程序。在每个程序结束时,都有一个签收框。我想将部分编号和名称添加到每个签收框。
我研究了(当然是在这里!)并编写了一个宏来插入对当前部分标题的引用,它似乎工作正常:
Sub InsertCrossRefToSectionHeading()
Dim RefList As Variant
Dim LookUp As String
Dim Ref As String
Dim i As Integer
LookUp = ActiveDocument.Bookmarks("\HeadingLevel").Range.Paragraphs(1).Range.ListFormat.ListString
With ActiveDocument
RefList = .GetCrossReferenceItems(wdRefTypeHeading)
For i = UBound(RefList) To 1 Step -1
Ref = Trim(RefList(i))
If Left(Ref,Len(LookUp)) = LookUp Then Exit For
Next i
If i Then
Selection.InsertCrossReference ReferenceType:=wdRefTypeHeading,_
ReferenceKind:=wdNumberFullContext,_
ReferenceItem:=CStr(i),_
InsertAsHyperlink:=True,_
IncludePosition:=False,_
SeparateNumbers:=False,_
SeparatorString:=" "
Selection.TypeText Text:=vbTab
Selection.InsertCrossReference ReferenceType:=wdRefTypeHeading,_
ReferenceKind:=wdContentText,_
SeparatorString:=" "
'Copy the formatting from the previous cell in the template table and apply to refrence text.
Selection.MoveLeft Unit:=wdCell
Selection.CopyFormat
Selection.MoveRight Unit:=wdCell
Selection.PasteFormat
Else
MsgBox "A cross reference to """ & LookUp & """ couldn't be set" & vbCr & _
"because a paragraph with that number couldn't" & vbCr & _
"be found in the document.",_
vbInformation,"Invalid cross reference"
End If
End With
End Sub
但是,它是对标题的硬链接引用,该标题是运行宏时本节的标题。如果我添加一个部分,该部分后面的所有引用都指向前一个部分,这就违背了它的目的。
是的,我的宏会让修复速度更快,但每次我向这个不断发展的文档添加一个部分时都会有很多返工。是的,我什至可以以编程方式在文档中搜索顶行带有“测试记录”的表格,然后删除第 2 行单元格 2 并插入引用……但这是很多额外的编程!……我已经在 Excel 中完成了大量 VBA,但在 Word 中是新手。我想我可以将参考文献保留到本次编辑的最后......但如果文档在未来发展(这很有可能),我将不得不再做一遍。
有没有办法引用当前部分的标题?
感谢您的帮助!
解决方法
感谢@CharlesKenyon,这是解决方案(也比我的第一次尝试简单得多!)。
Sub InsertCrossRefToSectionHeading()
' Adds ref to the heading of the current section.
'https://stackoverflow.com/questions/67200486/ms-word-link-to-header-of-current-section-relative-referencing
'http://www.addbalance.com/usersguide/fields.htm#STYLEREF
CurrentHeadingLevel = ActiveDocument.Bookmarks("\HeadingLevel").Range.Paragraphs(1).Range.ListFormat.ListLevelNumber
Selection.Fields.Add Range:=Selection.Range,Type:=wdFieldEmpty,Text:= _
"STYLEREF ""Heading " & CurrentHeadingLevel & """ \w ",PreserveFormatting:=True
Selection.TypeText Text:=" "
Selection.Fields.Add Range:=Selection.Range,Text:= _
"STYLEREF ""Heading " & CurrentHeadingLevel & """ ",PreserveFormatting:=True
'Copy the formatting from the previous cell in the template table and apply to refrence text.
Selection.MoveLeft Unit:=wdCell
Selection.CopyFormat
Selection.MoveRight Unit:=wdCell
Selection.PasteFormat
End Sub
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。