View Single Post
 
Old 07-14-2015, 09:42 PM
gmayor's Avatar
gmayor gmayor is offline Windows 7 64bit Office 2010 32bit
Expert
 
Join Date: Aug 2014
Posts: 4,137
gmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud of
Default

There are potentially many headers in a document. You need to identify which section and which header in that section. The following example examines the primary header in the section where the cursor is when you run the macro. If necessary you can loop through all sections and the headers in those sections.

There is no need to 'select' the found word/string in order to read it and the word that comes before.

Another issue not mentioned by Paul is what Word considers is a 'word', so when looking to add a word to a string, it helps to know what that 'word' might be. However the following should be easy enough to adapt. The string variable to which the search string and previous 'word' are added is sText

Code:
Sub FindInHeader()
Dim oRng As Range
Dim sText As String
Dim sWord As String
Dim numWords As Integer
Dim i As Integer
Dim j As Integer
    numWords = 1
    'In the following line set the section and the particular header
    Set oRng = Selection.Sections(1).Headers(wdHeaderFooterPrimary).Range
    sWord = InputBox("Enter the text to find")
    i = Len(sWord)
    For j = 1 To i
        If (Mid(sWord, j, 1)) = " " Then
            numWords = numWords + 1
        End If
    Next j
    With oRng.Find
        Do While .Execute(FindText:=sWord, MatchWholeWord:=True)
            oRng.MoveStart wdWord, -1
            Exit Do
        Loop
    End With
    If Not oRng.Words.Count = numWords + 1 Then
        sText = ""
    Else
        sText = oRng.Text
    End If
    If sText = "" Then
        MsgBox "Not found"
    Else
        MsgBox sText
    End If
lbl_Exit:
    Set oRng = Nothing
    Exit Sub
End Sub
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com

Last edited by macropod; 07-15-2015 at 05:39 PM. Reason: Merging of multiple threads & overlapping posts deleted
Reply With Quote