背景
我正在尝试在Excel中构建一个Word文档浏览器,以筛选大量文档(约1000个)。
打开Word文档的过程证明相当缓慢(每个文档约4秒钟,因此在这种情况下需要2个小时才能查看所有项目,这对于单个查询来说太慢了),即使禁用了可能会减慢打开速度的所有内容。因此,我采取以下步骤来打开:
- 只读方式打开
- 不使用打开和修复模式(在某些文档上可能会发生)
- 禁用文档的显示
我的研究所 far
这些文档很难搜索,因为有些关键字每次都出现,但上下文不同(当加载到数组时,这不是核心问题)。因此,经常使用的Windows资源管理器
解决方案(如此链接)在我的情况下无法使用。
目前,我已经成功编写了一个宏,通过打开文档来分析Word文档的内容。
代码
以下是代码示例。
注意,我使用了Microsoft Word 14.0 Object Library
引用。
' Analyzing all the word document within the same folder '
Sub extractFile()
Dim i As Long, j As Long
Dim sAnalyzedDoc As String, sLibName As String
Dim aOut()
Dim oWordApp As Word.Application
Dim oDoc As Word.Document
Set oWordApp = CreateObject("Word.Application")
sLibName = ThisWorkbook.Path & "\"
sAnalyzedDoc = Dir(sLibName)
sKeyword = "example of a word"
With Application
.DisplayAlerts = False
.ScreenUpdating = False
End With
ReDim aOut(2, 2)
aOut(1, 1) = "Document name"
aOut(2, 1) = "Text"
While (sAnalyzedDoc <> "")
' Analyzing documents only with the .doc and .docx extension '
If Not InStr(sAnalyzedDoc, ".doc") = 0 Then
' Opening the document as mentionned above, in read only mode, without repair and invisible '
Set oDoc = Word.Documents.Open(sLibName & "\" & sAnalyzedDoc, ReadOnly:=True, OpenAndRepair:=False, Visible:=False)
With oDoc
For i = 1 To .Sentences.Count
' Searching for the keyword within the document '
If Not InStr(LCase(.Sentences.Item(i)), LCase(sKeyword)) = 0 Then
If Not IsEmpty(aOut(1, 2)) Then
ReDim Preserve aOut(2, UBound(aOut, 2) + 1)
End If
aOut(1, UBound(aOut, 2)) = sAnalyzedDoc
aOut(2, UBound(aOut, 2)) = .Sentences.Item(i)
GoTo closingDoc ' A dubious programming choice but that works for the moment '
End If
Next i
closingDoc:
' Intending to make the closing faster by not saving the document '
.Close SaveChanges:=False
End With
End If
'Moving on to the next document '
sAnalyzedDoc = Dir
Wend
exitSub:
With Output
.Range(.Cells(1, 1), .Cells(UBound(aOut, 1), UBound(aOut, 2))) = aOut
End With
With Application
.DisplayAlerts = True
.ScreenUpdating = True
End With
End Sub
我的问题
我想到的想法是通过文档中的XML内容直接访问其内容(您可以在新版本的Word中重命名任何文档时访问它,使用.zip
扩展名并转至nameOfDocument.zip\word\document.xml
)。
这比加载文档中所有无用的图像、图表和表格要快得多,在文本搜索中也没有用处。
因此,我想问一下,在VBA中是否有一种打开Word文档并像打开zip文件一样访问该XML文档,然后在VBA中处理它像普通字符字符串一样的方法,因为我已经拥有了给定上述代码的路径和文件名称。