how to change text of a part of a sentence automatically

M

mjlaali

Hi,

I would like to know, how can I select part of a sentence Range object and
change it's text automatically.
 
P

Pesach Shelnitz

Hi,

The following macro demonstrates the simplest way to change part of the
sentence in which the cursor is located. Note that it doesn't do anything if
the search text is not found.

Sub ReplaceTextInSentence()

Dim OldText As String
Dim NewText As String

OldText = InputBox("Type the text that you want to replace.")
NewText = InputBox("Type the new text.")
With Selection.Sentences(1).Find
.Text = OldText
.Replacement.Text = NewText
.Forward = True
.Wrap = wdFindStop
.MatchCase = False
.Execute Replace:=wdReplaceOne
End With
End Sub
 
M

mjlaali

Hi,

Thanks for the reply, but if we don't know the text of the part and we just
know where the starting point and the ending point of the part is, regarding
to the starting point of the sentence.

thanks again,
 
P

Pesach Shelnitz

Hi,

You didn't include you code for determining where the starting point and the
ending point of the part are, so I can only demonstrate how to do this in an
example case in which the starting point is the beginning of the second word
in the sentence where the cursor is located and the ending point is the end
of the second word. Note that the sentence must have three or more words for
the macro to work correctly.

Sub ReplaceRangeInSentence()

Dim NewText As String
Dim MyRange As Range

NewText = InputBox("Type the new text.")
Set MyRange = Selection.Sentences(1)
With MyRange
.MoveStart wdWord, 1
.Collapse Direction:=wdCollapseStart
.MoveEnd wdWord, 1
.MoveEnd wdCharacter, -1
.Text = NewText
End With

Set MyRange = Nothing
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