【发布时间】:2016-08-24 14:07:01
【问题描述】:
上下文
我正在尝试在 Excel 中构建一个 Word 文档浏览器来筛选大量文档(大约 1000 个)。
事实证明,打开一个 word 文档的过程相当缓慢(每个文档大约需要 4 秒,因此在这种情况下需要 2 小时来查看所有项目,这对于单个查询来说太慢了),即使是禁用所有可能减慢打开速度的东西,因此我打开:
- 只读
- 没有打开和修复模式(某些文档可能会出现这种情况)
- 禁用文档的显示
我目前的尝试
这些文档很难浏览,因为有些关键字确实每次都出现但不在同一个上下文中(不是问题的核心,因为当文本加载到数组中时我可以处理这个问题)。因此,在我的情况下,不能使用经常使用的 Windows explorer 解决方案(如 link )。
目前,我设法拥有一个工作宏,通过打开它们来分析 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)。
这将比加载所有在文本搜索中没有用的word文档的图像、图表和表格要快得多。
因此,我想问一下 VBA 中是否有一种方法可以打开像 zip 文件这样的 word 文档并访问该 XML 文档,然后像 VBA 中的普通字符串一样处理它,因为我已经有了上面代码给出的文件的路径和名称。
【问题讨论】:
-
您可以通过 Shell 对象 (rondebruin.nl/win/s7/win002.htm) 直接访问压缩文件,但是您将无法解析 XML (stackoverflow.com/questions/11305/how-to-parse-xml-using-vba) 并且 Word 有一个可怕的底层 xml 可以使用.祝你好运。
-
看看VBA macro to search a folder for a keyword。通过使用所描述的
FindFiles函数(使用第二个版本),您将利用文档中所有单词的 Windows 索引。 -
谢谢你们,我会看看链接并尝试做点什么。
-
好的,到目前为止,我已经得出结论,我想做的事情(即在不更改扩展名的情况下编辑 .docx)无法在 VBA 中完成。我目前正在用 C# 编写一个 DLL,它可能会解决类似于 code found on the MSDN 的问题,我希望尽快发布一些关于它的内容。