Headings with Macro

D

Designingsally

i m attempting to write macro where it checks for "A" in the style (heading
2). This style can be found in the Home table under Styles group. The macros
I have got searches for the word "A" in the entire document, which is wrong.
Is there a same way to arrive at the solution.

The macros I have attempted is shown below:
Sub FindHeading()


Dim oRng As Range
Dim sRep As String
Dim sFindText As String
Dim sRepText As String
Selection.Style = ActiveDocument.Styles("Heading 2")
If Not Selection.Style = ActiveDocument.Styles("Heading 2") Then
Exit Sub
sFindText = "a" 'Replace to find
With Selection
..HomeKey wdStory
With .FInd
'.ClearFormatting
'.Replacement.ClearFormatting
..Wrap = wdFindContinue
..Format = False
..MatchCase = False
..MatchWholeWord = True
..MatchWildcards = False
..MatchSoundsLike = False
..MatchAllWordForms = False
While .Execute(findText:=sFindText)
Set oRng = Selection.Range
sRep = Msgbox("change the word")
If sRep = vbCancel Then
Exit Sub
End If
If sRep = vbYes Then
oRng.Text = sRepText
End If


Wend
End With
End With
End If
End Sub
 
P

Pesach Shelnitz

Hi Sally,

I fixed your macro to do what I think you want. In particular, I removed the
lines that set the style at the insertion point to Heading 2. In my opinion,
this should not be part of this macro. I set sRepText to "the" so that the
macro could make a visible change. I set .Format to True, and I added the
following line.

.Style = wdStyleHeading2

In addition, after the search loop, I added the following lines so that this
macro will not cause future searches to fail.

.ClearFormatting
.MatchWholeWord = False

Here is the result.

Sub FindHeading()

Dim oRng As Range
Dim sRep As String
Dim sFindText As String
Dim sRepText As String

sFindText = "a" 'Replace to find
sRepText = "the"
With Selection
..HomeKey wdStory
With .Find
..ClearFormatting
..Replacement.ClearFormatting
..Wrap = wdFindContinue
..Format = True
..MatchCase = False
..MatchWholeWord = True
..MatchWildcards = False
..MatchSoundsLike = False
..MatchAllWordForms = False
..Style = wdStyleHeading2
While .Execute(findText:=sFindText)
Set oRng = Selection.Range
sRep = MsgBox("Change the word?", vbYesNo)
If sRep = vbCancel Then
Exit Sub
End If
If sRep = vbYes Then
oRng.Text = sRepText
End If
Wend
..ClearFormatting
..MatchWholeWord = False
End With
End With
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top