gpt4 book ai didi

vba - 使用 VBA 获取 word 中的所有交叉引用

转载 作者:行者123 更新时间:2023-12-02 08:32:54 25 4
gpt4 key购买 nike

我有一个相当大的 word 文档(> 400 页),其中有很多标题的交叉引用。到目前为止,我一直引用标题的标题,但现在我想更改它并引用标题所在的页面。

我没有通过 GUI 找到解决此问题的方法(当然,手动处理除外),所以我正在考虑编写一些 VBA。不幸的是,我只找到了一种方法来列出所有可以交叉引用的目标(通过 GetCrossReferenceItems),但我需要一种方法来访问实际的交叉引用字段。

你能帮我吗?交叉引用字段与超链接相同吗?

最佳答案

交叉引用是 Word 文档中的字段,可以通过字段集合 (ActiveDocument.Fields) 访问。您可以像任何其他集合一样遍历它们并检查它们的类型以查看它是否是您想要处理的类型。看起来对文本的交叉引用是类型 3 (wdFieldRef),对页码的交叉引用是类型 37 (wdFieldPageRef)。更改字段可能有点棘手;以下应该让你开始:

Sub ChangeFields()
Dim objDoc As Document
Dim objFld As Field
Dim sFldStr As String
Dim i As Long, lFldStart As Long

Set objDoc = ActiveDocument
' Loop through fields in the ActiveDocument
For Each objFld In objDoc.Fields
' If the field is a cross-ref, do something to it.
If objFld.Type = wdFieldRef Then
'Make sure the code of the field is visible. You could also just toggle this manually before running the macro.
objFld.ShowCodes = True
'I hate using Selection here, but it's probably the most straightforward way to do this. Select the field, find its start, and then move the cursor over so that it sits right before the 'R' in REF.
objFld.Select
Selection.Collapse wdCollapseStart
Selection.MoveStartUntil "R"
'Type 'PAGE' to turn 'REF' into 'PAGEREF'. This turns a text reference into a page number reference.
Selection.TypeText "PAGE"
'Update the field so the change is reflected in the document.
objFld.Update
objFld.ShowCodes = True
End If
Next objFld
End Sub

关于vba - 使用 VBA 获取 word 中的所有交叉引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24951526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com