Log in

View Full Version : How to search current section header for text?



SamMurr
07-21-2018, 04:54 PM
I would like to know if there is a way to search the text of the current section header in Word. Only want to search one section header. What would that code look like? I am new to VBA programming.

Thanks in Advance
Sam Murr

gmayor
07-21-2018, 08:05 PM
That's not as straightforward as you might imagine as there are potentially three headers in each section, and those headers may be linked to the preceding or following sections, in which case the header would relate to more than one section. However the following will loop through the headers of the current section, search for the indicated string and if found perform some actions on it.


Sub Macro1()
Dim oRng As Range
Dim oHeader As HeaderFooter
Dim strFind As String
strFind = "Text to find"
For Each oHeader In Selection.Sections(1).Headers
If oHeader.Exists Then
Set oRng = oHeader.Range
With oRng.Find
Do While .Execute(FindText:=strFind)
'do something with orng (the found text) e.g.
oRng.Text = "Replacement Text"
oRng.Font.ColorIndex = wdRed
oRng.Font.Bold = True
oRng.Collapse 0
Loop
End With
End If
Next oHeader
lbl_Exit:
Set oHeader = Nothing
Set oRng = Nothing
Exit Sub
End Sub

SamMurr
07-23-2018, 09:09 AM
gmayor.....Thanks a bunch! I think this will help me solve my issue! Thanks again!