Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vba - Searching for Text in Header Section of A Word Document

I am trying to confirm if a document contains some text, the only problem is this text is in the Header. This is the code I am using which constantly returns false even though the text exists:

Set CurrentDoc = Documents.Open("a.doc")

With CurrentDoc.Sections(1).Headers(wdHeaderFooterFirstPage).Range.Find
    .Text = "This is the text to find"
    .Forward = True
    .Execute
    If (.Found = True) Then Debug.Print "Match"
End With

The following also doesn't seem to work (I assume .Content doesn't include header/footers):

With CurrentDoc.Content.Find
    .Text = "This is the text to find"
    .Forward = True
    .Execute
    If (.Found = True) Then Debug.Print "Match"
End With

Any help would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're probably trying to search in the wrong section/headertype. You could try this code:

Dim rng As Range
Dim intSecCount As Integer
Dim intHFType As Integer
intSecCount = ActiveDocument.Sections.Count
For intSection = 1 To intSecCount
    With ActiveDocument.Sections(intSection)
        For intHFType = 1 To 3 
            Set rng = ActiveDocument.Sections(intSection).Headers(intHFType).Range
            rng.Find.Execute findtext:="This is the text to find", Forward:=True
            If rng.Find.Found = True Then
                Debug.Print "Match" 
            End If
        Next intHFType
    End With
Next intSection

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...