Replace and Search Operation just for selected paragraphs


Dear Experts:

below code is supposed to replace redundant spaces with tabstops just within the selected paragraphs. Regrettably all the redundant spaces within the whole document get worked on.

How has the code to be changed to work only on the selection (the selection for example could be only just one paragraph).

Help is much appreciated. Thank you very much in advance.

Regards, Andreas
Sub SearchAndReplaceJustinSelectedParagraphs()

Dim intcount As Long
Dim myRange As Range


intcount = 0
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting

Set myRange = Selection.Range
myRange.Select

With myRange.Find
.Forward = True
   .Wrap = wdFindContinue
   .ClearFormatting
   .Text = " {2;}"
   .Replacement.Text = "^t"
   .MatchWildcards = True
   While .Execute(Replace:=wdReplaceOne)
   myRange.Collapse wdCollapseEnd
      intcount = intcount + 1
      Wend
End With

MsgBox intcount
End Sub

Open in new window

Andreas HermleTeam leaderAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris BottomleySoftware Quality Lead EngineerCommented:
Looks to me like replace:

   .Wrap = wdFindContinue
with
   .Wrap = wdFindStop

Chris
0
Andreas HermleTeam leaderAuthor Commented:
Hi Chris,

thank you for your prompt help. Regrettably even after changing wdFindContinue to wdFindStop, occurrences of redundant spaces after the selection also get worked on. I got no reason why?

Regards, Andreas
0
Chris BottomleySoftware Quality Lead EngineerCommented:
Can you provide a representative document?

Basically the Wrap parameter indicates what to do after searching teh selection, stop, continue or ask.  cntinue means it continues to the rest of the document, ask and stop do as they suggest.  As such they would of their own give the reported symptom.  I tried a quick test, but my document is not representative or perhaps word version ... what are you using?

Chris
0
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

Ingeborg Hawighorst (Microsoft MVP / EE MVE)Microsoft MVP ExcelCommented:
You could drop the message box and count. This would make things easier.

The code below will replace just in the selection

cheers, teylyn
Sub SearchAndReplaceJustinSelectedParagraphs()

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting

With Selection.Find
.Forward = True
   .Wrap = wdFindContinue
   .ClearFormatting
   .Text = "  "
   .Replacement.Text = "^t"
   .MatchWildcards = True
End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

Open in new window

0
Chris BottomleySoftware Quality Lead EngineerCommented:
Still not working at all for me but then that'll be my problem.  Looking deeper hower:


   myRange.Collapse wdCollapseEnd
will leave myrange as the document so also try commenting that out:
'   myRange.Collapse wdCollapseEnd

Chris
0
Chris BottomleySoftware Quality Lead EngineerCommented:
The selection replace resets the selection therefore try the following:

Chris
Sub SearchAndReplaceJustinSelectedParagraphs()
 
Dim intcount As Long
Dim myRange As Object
 
 
intcount = 0
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
 
Set myRange = Selection.Range
 
With Selection.Find
    .Forward = True
   .Wrap = wdFindStop
   .ClearFormatting
   .Text = " {2}"
   .Replacement.Text = "^t"
   .MatchWildcards = True
    While .Execute(Replace:=wdReplaceOne)
        intcount = intcount + 1
        myRange.Select
    Wend
End With
 
MsgBox intcount
End Sub

Open in new window

0
Chris BottomleySoftware Quality Lead EngineerCommented:
Andreas

If your original intention was to find 2 or more spaces and replace each group with one tab then:

The previous submission will replace any pair of spaces with a tab.

Chris
Sub SearchAndReplaceJustinSelectedParagraphs()
 
Dim intcount As Long
Dim myRange As Object
 
 
intcount = 0
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
 
Set myRange = Selection.Range
 
With Selection.Find
    .Forward = True
   .Wrap = wdFindStop
   .ClearFormatting
   .Text = " {2,}"
   .Replacement.Text = "^t"
   .MatchWildcards = True
    While .Execute(Replace:=wdReplaceOne)
        intcount = intcount + 1
        myRange.Select
    Wend
End With
 
MsgBox intcount
End Sub

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ingeborg Hawighorst (Microsoft MVP / EE MVE)Microsoft MVP ExcelCommented:
Chris,

you're probably on the right track here and I'll be happy to see you get the points.

I just wanted to point out that since Andreas used

   .Text = " {2;}"

in his original post, he is probably working with European settings, using the semicolon as the list separator, and needs to adjust this line of your code

   .Text = " {2,}"

to have a semicolon instead of a comma. I now know why the original code bombed when I ran it.

Learnt something.

cheers, teylyn
0
Chris BottomleySoftware Quality Lead EngineerCommented:
Teylyn

That will be interesting to hear, I have assumed it was not one of the regional uses ... but given it is there in the first post you are probably correct.

>>> Learnt something
Me too but unforunately had to unlearn something else to make room for the learning!

Chris
0
Ingeborg Hawighorst (Microsoft MVP / EE MVE)Microsoft MVP ExcelCommented:
Chris,

are you saying that your head's so full of learning that you have to throw out stuff to let in something new?

Probably not, but the concept made me chuckle. On second thought, you probably mean that you are extending your knowledge on some gray area of Word VBA, replacing slightly wrong assumptions with definitely correct ones.

When I ran the askers original code, it threw an error at the line I quoted above. Puzzle.  So I recorded a macro that replaces two spaces with a tab and studied the ensuing code. That alone gave me sufficient material to learn, since Word VBA is even more of a challenge to me than Excel VBA.

So, for me, the issue here is the counter and how to progress it without upsetting the range and the replace routine. I'm sure you're onto it, but it's too late at night for me to check out the nuances.

I'll be back in the morning (my morning) to see your solution and applaud your points.

cheers, teylyn

0
Chris BottomleySoftware Quality Lead EngineerCommented:
>>> are you saying that your head's so full of learning that you have to throw out stuff to let in something new?

Almost correct but it's more like

My head's so full of decayed brain cells that I have to throw out stuff to let in something new?

And yes I find Word VBA a challenge, as I did outlook before that and excel before that.  The challenges are good for rotating knowledge around the brain cells, less so for self congratulation since there is so much still to be learned!!!  Expert pah, i'll forever be a student in awe of true experts - and your metioric rise suggests that includes you.

Chris
0
Ingeborg Hawighorst (Microsoft MVP / EE MVE)Microsoft MVP ExcelCommented:
Easy, man, easy! I'm but a rookie, as you can see in my profile.

I believe the standard term for new contributors should be "rookie" instead of "expert", but then, "Rookie-exchange.com" may not sound that flash. Tehehee.

Actually, I find I'm picking up more VBA on this site than I ever expected to know. Then, with my little knowledge, I turn into a real danger (as in: "a little knowledge is a dangerous thing").  I've come across a few fairly basic challenges that I dared to tackle, and "lo and behold", I sometimes even get points for them. Which motivates me to keep at it.

I'm still very cautious in the VBA space. Give me an Excel charting problem any time. Or something to do with summing/finding/matching/sorting data with formulae. But every once in a while, my ancient  2nd or 3rd generation programming experience even applies to VBA, and I get a burst of feel-useful-vibes.

42: Goto End

:End

Cheers, teylyn
0
Andreas HermleTeam leaderAuthor Commented:
Dear Chris,

Great job. Thank you very much. The last version suits me just fine. I will acknowledge it and post a new question right away regarding a similar problem.

Thank you again, Regards, Andreas

Dear teylyn: your solution works on the whole document not just the selection. But thank you very much for your kind help, anyway.

Regards, Andreas
0
Andreas HermleTeam leaderAuthor Commented:
Great job. Thank you very much. Regards, Andreas
0
Chris BottomleySoftware Quality Lead EngineerCommented:
Andreas

WOuld you take a minute (for my interest) to answer the observation from Teylyn ...

DO you need:
 .Text = " {2;}"
or .Text = " {2,}"

i.e. comma or semicolon as the repeat character?
Chris
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Word

From novice to tech pro — start learning today.