Problems with Replace

  • Thread starter Budget Programmer
  • Start date
B

Budget Programmer

Hello,
I'm a little bit new to Word VBA. Been working with Excel VBA for a while.

I built the following macro to delete text that had the style of
"Instructions" applied to it. The idea is for the user to execute this after
they're done filling out the document.

For the most part, it works well. There are a couple of problems however.
If the instructions are immediately followed by a table, inserted JPG, etc.
it doesn't delete the preceeding text. It could be a single space, a line of
text, whatever. The issue is when the text (styled with "Instructions")
immediately preceeds something WITHOUT a hard return, it doesn't get deleted.

Please give me some guidance. I appreciate your help.

Sub Test2()

Dim objDocumentRange As Range
Dim strTargetStyle As String
Dim strResultText As String

strTargetStyle = "Instructions"
strResultText = ""

Set objDocumentRange = ActiveDocument.Range

With objDocumentRange.Find
.Style = strTargetStyle
.MatchAllWordForms = True
.Text = strResultText
.Execute Replace:=wdReplaceAll
End With

End Sub
 
S

Shauna Kelly

Hi

Is "Instructions" a paragraph style or a character style? And, in either
case, has it been applied to a whole paragraph (including the
end-of-paragraph marker) or just some of the text?

Hope this helps.

Shauna Kelly. Microsoft MVP.
http://www.shaunakelly.com/word
 
H

Helmut Weber

Hi,

there are a couple of issues with replacing text.

If there is a problem, I usually don't try replacing
any longer, but set the found range to "", like that:

Sub Test7611()
Dim rDcm As Range
Set rDcm = ActiveDocument.Range
With rDcm.Find
.Style = "Heading 3"
While .Execute
rDcm.Text = ""
Wend
End With
End Sub

--
Greetings from Bavaria, Germany

Helmut Weber, MVP WordVBA

Win XP, Office 2003
"red.sys" & Chr$(64) & "t-online.de"
 
N

NZ VBA Developer

G'day!

I think my answer my be tempered somewhat by the answers to Shauna's
questions, but assuming "Instructions" is a paragraph style and it's applied
to the whole paragraph, I've used something like this in small documents:

Sub Cleanup ( )
Dim myPara as Paragraph
For Each myPara in ActiveDocument.Paragraphs
If myPara.Style="Instructions" Then myPara.Range.Delete
Next
End Sub

I wouldn't try it for really big documents as looping through each paragraph
could be really slooooow, but it's simple and achieves the desired result.
 
B

Budget Programmer

Helmut,
That did it. It got everything.
Vielen Dank für Ihre Hilfe!
 

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