VBA Word, Select Text
In this article I will explain how you can use VBA for word to select text.
Contents
Select Entire Document:
Using the code snippet below you can select the entire word document:
Selection.WholeStory
Result:
Select The Current Line:
Using the code below you can select the current line:
Sub main()
Selection.HomeKey Unit:=wdLine
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
End Sub
Assume the cursor is somewhere in the middle of the line:
The first line moves the cursor to the start of the line:
Selection.HomeKey Unit:=wdLine
The next line move the cursor to the end of the line while selecting the text:
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Result:
Select to End of Line:
The code below will only select till the end of the line:
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Result:
Select to Start of Line:
The code below will select text up to the start of the line:
Selection.HomeKey Unit:=wdLine, Extend:=wdExtend
Result:
Select Certain Number of Characters:
Lets say we need to select only a certain number of characters from the current location of the cursor. The code below will select 5 characters to the right:
Selection.MoveRight Unit:=wdCharacter, Count:=5, Extend:=wdExtend
Result:
The code below will select 10 characters to the left:
Selection.MoveLeft Unit:=wdCharacter, Count:=10, Extend:=wdExtend
Result:
Select Text up to a Certain Character:
You might want to select text until you reach a certain character. For example a space character, “*”, “/”, …
The code below selects text until a space character is reached:
Sub test()
Dim flag As Boolean
flag = True
While flag = True
Selection.MoveRight Unit:=wdCharacter, Count:=1, _
Extend:=wdExtend
'checks the last character to see if its a space
If Strings.Right(Selection.Range.Text, 1) = " " Then
'if it was a space the loop flag will end
flag = False
End If
Wend
End Sub
The line below selects one additional character to the right:
Selection.MoveRight Unit:=wdCharacter, Count:=1, _
Extend:=wdExtend
The if statement below checks to see if the last character selected is a space character:
If Strings.Right(Selection.Range.Text, 1) = " " Then
...
End If
For more information about the Strings.Right function please see the article below. Although the article was written for Excel, it can be extended to VBA for Word:
See also:
- Word VBA, Move Cursor to Start of Document
- Word VBA, Move Cursor to End of Document
- Word VBA, Move Cursor to End of Line
- Word VBA, Move Cursor to Start of Line
- Excel VBA String Processing and Manipulation
- Word VBA Bookmarks
- Word VBA, Read All Lines
If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website www.software-solutions-online.com
10 thoughts on “VBA Word, Select Text”