Simmons
Simmons

Reputation: 139

Loop through Word document, starting from beginning of file at start of each loop

I'm looping through a Word Document in VBA. Through each pass I'd like to search for a different word, so each pass needs to start at the beginning of the file. The current method I'm using is this, but it appears to search for the first word, and when it gets to the end of the file, moves to the second word, and searches only at the end of the file and so on with the rest of the words.

'my array of words is called myKeywords
For x = LBound(myKeywords) To UBound(myKeywords)
    PageNumbers(x) = ""
    'start from start of file here somehow.
    With oWord.Selection.Find
        .ClearFormatting()
        .Text = myKeywords(x)
        .Wrap = False
        .Forward = True
        Do While .Execute = True
            If PageNumbers(x) = "" Then
                PageNumbers(x) = oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
            Else
                PageNumbers(x) = PageNumbers(x) & ", " & oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
            End If
        Loop
    End With
Next

Any insight is appreciated.

Edit 1

I have read through this, and I don't see anything that could help me. Wrap looks like it would help, but if I set wrap = True, I get the error "Value out of range", and I don't see how .wrap could set anything out of range.

Edit 2

I tried setting a range and resetting it at the end of the loop, but no success so far.

'my array of words is called myKeywords
Range = oWord.Selection
For x = LBound(myKeywords) To UBound(myKeywords)
    PageNumbers(x) = ""
    'start from start of file here somehow.
    With Range.Find
        .ClearFormatting()
        .Text = myKeywords(x)
        .Wrap = False
        .Forward = True
        Do While .Execute = True
            If PageNumbers(x) = "" Then
                PageNumbers(x) = oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
            Else
                PageNumbers(x) = PageNumbers(x) & ", " & oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
            End If
        Loop
        'I've also tried several other variations of Range = other things to get this to work.
        Range = Range.Select

    End With
Next

Edit 3

'my array of words is called myKeywords
Range = oWord.ActiveDocument.Range(Start:=oWord.Selection.Start, [End]:=oWord.Selection.End)
For x = LBound(myKeywords) To UBound(myKeywords)

    'start from start of file here somehow.
    With oWord.Selection.Find
        PageNumbers(x) = ""
        .ClearFormatting()
        .Text = myKeywords(x)
        .Wrap = False
        .Forward = True
        Do While .Execute = True
            If PageNumbers(x) = "" Then
                PageNumbers(x) = oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
            Else
                PageNumbers(x) = PageNumbers(x) & ", " & oWord.Selection.Information(Word.WdInformation.wdActiveEndAdjustedPageNumber)
            End If
        Loop
        Range.Select()

    End With
Next

Upvotes: 2

Views: 2228

Answers (4)

rpmathur 12
rpmathur 12

Reputation: 55

Loop through single word file and save individual pages as pdf in a particular folder

Sub print_pdf()

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False

Dim file As String
Dim fname As String
Dim lngth As Integer
Dim wrd As New Word.Application
Dim wb As Word.Document
Dim pagecount As Integer
Dim pge As Word.Page

file = Environ("UserProfile") & "\Desktop\Write-wordfile-name-on-desktop.docx"
fname = VBA.Dir(file)
lngth = VBA.Len(fname)
Debug.Print lngth

If lngth > 0 Then

    wrd.Visible = True
    Set wb = wrd.Documents.Open(file)
    pagecount = wb.ComputeStatistics(wdStatisticPages)
    Debug.Print pagecount
    
    If pagecount > 0 Then
    
         For i = 1 To pagecount
                
                
               wb.ExportAsFixedFormat OutputFileName:=Environ("userprofile") & "\Desktop\write-folder-name-on-desktop\letter-" & i & ".pdf", Range:=wdExportCurrentPage, ExportFormat:=wdExportFormatPDF
               wb.Application.Browser.Next
               Application.Wait (Now + TimeValue("00:00:02"))
                
         Next i
    
                wb.Close SaveChanges:=wdDoNotSaveChanges
    End If
    

End If


                wrd.Quit
                Application.ScreenUpdating = True
                Application.Calculation = xlCalculationAutomatic
                Application.DisplayAlerts = True

End Sub

Upvotes: 0

J. Chomel
J. Chomel

Reputation: 8393

To go to the beginning of a Word document with vba, you can use:

Selection.HomeKey Unit:=wdStory

Then you have to do it at the start of the loop. I found this simply by using Word's macro recorder.

Upvotes: 0

Fratyx
Fratyx

Reputation: 5797

You apply the Find to the current selection. But the selection moves by calling the Execute on the Find object. The consequence is that after the first run of the loop the selection is on the last occurence of the first verb. This will be the starting point for the next Find.Execute. One possible solution is to store the current selection at the start of the loop in a Range variable (range=oWord.Selection) and set the selection back to this stored range at the end of the loop (range.Select). (For sure there are more elegant solutions for your general problem but it could be a solution to your concrete problem.)

Upvotes: 2

user3685427
user3685427

Reputation: 219

I'm not familiar with VBA so I can't give exact code, but you'll be able to implement the following strategy: If you are searching for individual words, you can just collect words one word at a time (or build them with one letter at a time, delimited by spaces and punctuation), and compare that word to a list of the keywords you want to find. So, rather than looping through the document many times and going through your list once, you can instead go through the document once while looping through your list many times.

Upvotes: 0

Related Questions