在循环中创build活动文档?

我试图从多个文档中获取一个段落,通过获得一个子文件来parsing每个文档,寻找这个始终在两个词之间的段落。 但是我不能得到“活动文档”或打开文档工作? 以前我已经可以使用open函数了,但是现在每次都得到Object Errors。 文件夹目录和文件名由用户input到单独的单元中,因此单元中的文本必须被组合以形成完整的文档地址。 这是代码

Sub findTest() Dim firstTerm As String, filename As Variant Dim secondTerm As String, J As Integer Dim myRange As Range Dim documentText As String Dim mydoc As String Dim file As Variant Dim startPos As Long 'Stores the starting position of firstTerm Dim stopPos As Long 'Stores the starting position of secondTerm based on first term's location Dim nextPosition As Long 'The next position to search for the firstTerm J = 2 nextPosition = 1 Do Until J > 600 Documents.Open filename:="Worksheets(1).Cells(5, 5) & Worksheets(2).Cells(J, 1)", ReadOnly:=True ' I get an error here every single time. 'First and Second terms as defined by your example. Obviously, this will have to be more dynamic firstTerm = "<firstword>" secondTerm = "<secondname>" 'Get all the document text and store it in a variable. Set myRange = ActiveDocument.Range 'Maximum limit of a string is 2 billion characters. 'So, hopefully your document is not bigger than that. However, expect declining performance based on how big doucment is documentText = myRange.Text 'Loop documentText till you can't find any more matching "terms" Do Until nextPosition = 0 startPos = InStr(nextPosition, documentText, firstTerm, vbTextCompare) stopPos = InStr(startPos, documentText, secondTerm, vbTextCompare) Debug.Print Mid$(documentText, startPos + Len(firstTerm), stopPos - startPos - Len(secondTerm)) nextPosition = InStr(stopPos, documentText, firstTerm, vbTextCompare) Loop J = J + 1 file = Dir Close Document Loop End Sub 

不要依赖于ActiveDocument。 声明一个Word.Document对象并将打开的文档分配给该文档。 然后使用该对象而不是ActiveDocument – 更可靠!

 Dim oDoc as Word.Document Set oDoc = Documents.Open(filename) Dim oRng as Word.Range Set oRng = oDoc.Content 'Preferred over oDoc.Range for getting content of entire document oDoc.Close 

注意:我不知道你要用Close Document来做什么,这可能是你的问题的一部分?