我在各个子文件夹中收集了 Word docx 文件。我需要创建一个索引文件,其中包含指向原始文件的链接。我认为 VBA 可能是执行此操作的最简单方法。我可以找到打印子文件夹中每个文件的列表,但我无法访问索引条目字段。
我的第一个目标是获取我需要检查的每个文件的列表。我改编了以下代码:http://word.mvps.org/faqs/macrosvba/ReadFoldersIntoArray.htm获取文件路径。
我的第二个目标是检查每个文件并获取索引条目字段(我的文档中的 { XE“scissors:running with”} 内容。
这就是我被困住的地方。我可以为每个文件的完整路径名构造一个字符串。我如何读取文件并获取这些索引条目?
答案1
您可以使用以下方式执行此操作(我尚未测试过此确切的代码,因此可能会出现错误)
Sub openAndProcess1Document( FullName As String, target As Word.Document )
' FullName is the full path+file name of the .docx
' target is a reference to the document that was the
' ActiveDcoument before you call this routine
' Or you could set up a Range variable and pass that
' So loop through your list of fullnames, calling this Sub
Dim doc as Word.Document
Dim fld as Word.Field
Dim r as Word.Range
Dim strCode as String
Set doc = Documents.Open(FullName)
For each fld in doc.Fields
if fld.Type = wdFieldIndexEntry then ' It's an XE field
strCode = fld.Code ' this will look something like 'XE "scissors:running with"'
' do whatever you want with strCode here,
' e.g.
' Set r = target.Content
' r.Collapse wdCollapseEnd
' r.InsertParagraph
' r.InsertAfter strCode
' Set r = Nothing
end if
Next
doc.Close Savechanges:=wdDoNotSaveChanges
Set doc = Nothing
End Sub
然后你需要类似
Dim target as Word.Document ' doesn't have to be called "target"!
Set target = ActiveDocument
For i = 1 to intDocumentCount ' or some such
Call openAndProcessDocument(strArrayOfDocumentFullNames(i), target)
Next ' i
' optionally...
target.Activate