我试图从多个文档中拉出一个段落,通过让sub解析每个文档来查找总是在两个术语之间的段落。但是我不能让"activedocument“或打开的文档工作吗?以前我可以很好地使用open函数,但现在每次都会收到对象错误。文件夹目录和文件名由用户输入到单独的单元格中,因此单元格中的文本必须组合在一起才能形成完整的文档地址。以下是代码
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发布于 2016-02-09 02:55:31
不要依赖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做什么,这可能是你的问题的一部分?
https://stackoverflow.com/questions/35268425
复制相似问题