Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Selecting previous word in MS Word 2007

Status
Not open for further replies.

Bruce18W

Technical User
May 9, 2011
27
US
Hi,

I'm trying to select the previous word in Word, so that I can later replace it with a close match. This is the code I'm using. right at the start *** Help needed here *** I get tripped up with trying to select the word but not the space after the word. any/all help appreciated!

Public Sub extendsel()

Dim sel As Selection
Dim Msg As String, strTemp As String, ReplacementWord As String
Dim target As Range
Dim Attempts As Integer, Response As Integer
*** Help needed here ***
Selection.Collapse
Selection.MoveLeft Unit:=wdWord, Count:=1
Selection.MoveRight Unit:=wdWord, Count:=1, Extend:=wdExtend
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Set target = Selection.Range

strTemp = Selection.Text
Debug.Print Selection.Text

Selection.Find.ClearFormatting

With Selection.Find
.Text = strTemp
.Replacement.Text = ""
.Forward = False
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
Debug.Print Selection.Text
Selection.MoveRight Unit:=wdWord, Count:=1, Extend:=wdExtend
Debug.Print Selection.Text
Msg = Selection.Text
Response = MsgBox(Msg, vbYesNoCancel)
If Response = vbYes Then
Selection.Start = target.Start
Selection.End = target.End
Selection.Text = Msg
Selection.Collapse Direction:=wdCollapseEnd
Exit Sub
Attempts = 10
ElseIf Response = vbCancel Then
Exit Sub
Else
Attempts = 1
While .Found And Attempts < 4
'Selection.MoveLeft Unit:=wdWord, Count:=1
Selection.Collapse Direction:=wdCollapseStart
Selection.Find.Text = strTemp
Selection.Find.Wrap = wdFindContinue
Selection.Find.Forward = False
Selection.Find.MatchWholeWord = False
.Execute
Debug.Print Selection.Text
Selection.MoveRight Unit:=wdWord, Count:=1, Extend:=wdExtend
Debug.Print Selection.Text
Msg = Selection.Text
Response = MsgBox(Msg, vbYesNoCancel)
If Response = vbYes Then
Selection.Start = target.Start
Selection.End = target.End
Selection.Text = Msg
Selection.Collapse Direction:=wdCollapseEnd
Exit Sub
ElseIf Response = vbCancel Then
Exit Sub
Else
Attempts = Attempts + 1
End If
Wend
End If
End With
End Sub

 
Hi Bruce,

Try:
Code:
Selection.Words.First.Previous.Words.First.Select
If Selection.Characters.Last.Text = " " Then _
Selection.End = Selection.End - 1
Note: when posting code, please use code tags.

Cheers
Paul Edstein
[MS MVP - Word]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top