Select whole word at cursor position

  • Thread starter ל×ון גולדנברג
  • Start date
×

ל×ון גולדנברג

Hi,

Assume my cursor is placed within a random word of a document.

I'm looking for VBA commands which will select this whole word.
(Similar to double-clicking).

The code should select the word in 3 various cursor positions:

1) Within the word (between its characters).
2) At the beginning of the word (between the first character and the leading
space).
3) At the end of the word between the last character and the following space).

I'm familiar with the code for selecting the whole line, at the cursors
position:

Selection.HomeKey Unit:=wdLine
Selection.EndKey Unit:=wdLine, Extend:=wdExtend

but could not figure out how to implement it for a single word.

As more as I think - it sounds very similar to the inner Dictionary
implementation - saying: the recognition of the whole word from only placing
the cursor between its characters.

Farther more, if the code could return the words number - I would be able to
implement what ever I want by selecting: ActiveDocument.Words(x).select

Thanks, Elm
 
A

Adam Bartkowski

Hi,

Selection.Expand Unit:=wdWord expands selection to the whole word (or
sentence, or paragraph etc.)

To expand to the left / right for count_of_units, use

Selection.MoveEnd Unit:=wd_const, Count:=count_of_units
Selection.MoveStart Unit:=wd_const, Count:=count_of_units

count_of_units can also be negative

or

Selection.MoveEndUntil Cset:=search_chars,
Count:=count_of_units_or_direction_const
Selection.MoveStartUntil Cset:=search_chars,
Count:=count_of_units_or_direction_const

AB
 
G

Greg Maxey

Part of the challenge is that in the Word object module, the space following
a "word" is part of the preceeding word. This means that placing the
cursor where you think is the begining of a word (between the first
character and the space separating the previous word) is actually placing
the cursor in the preceding word and normal code for selecting the current
word will select what looks like the previous word.

You might be able to trick word using something like this:

Sub ScratchMacro()
Dim oRng As Word.Range
If Selection.Characters(1) = Chr(32) Then Selection.Move wdCharacter, -1
Selection.Words(1).Select

Set oRng = ActiveDocument.Content
oRng.End = Selection.Range.End
MsgBox oRng.Words.Count
End Sub
 
×

מיכ×ל (מיקי) ×בידן®

Thank you, both.
Your clear replies contributed, a lot, to my Word VBA knowledge.
 

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