007 February 2016

Creating active document in loop?

I am trying to pull a paragraph from multiple documents, by getting a sub to parse through each document looking for this paragraph that is always between two terms. However I cannot get the "activedocument" or open document to work? Previously I have been able to use the open function fine, but now I get Object Errors each time. The folder directory and filename are inputted by the user into separate cells, so the text in the cells has to be combined to form the full document address. Here is the code

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 - st        

Answers


Cindy Meister February 2016

Don't rely on ActiveDocument. Declare a Word.Document object and assign the document you open to that. Then work with that object rather than ActiveDocument - much more reliable!

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

Note: I don't know what you're trying to do with Close Document, that could be part of your problem?

Post Status

Asked in February 2016
Viewed 3,219 times
Voted 5
Answered 1 times

Search




Leave an answer