Vba word select from to

In this article I will explain how you can use VBA for word to select text.


Select Entire Document:

Using the code snippet below you can select the entire word document:

Selection.WholeStory

Result:

Word VBA Select All


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:

Word VBA Move Cursor To Start of 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:

Word VBA Select Line, 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:

Word VBA Select Line, To End


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:

Word VBA Select Line, To Start


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:

Word VBA Select 5 Charcter to right
The code below will select 10 characters to the left:

Selection.MoveLeft Unit:=wdCharacter, Count:=10, Extend:=wdExtend

Result:

Word VBA Select 10 Charcter to left


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

Word VBA, Select up to space
Result:

Word VBA, Select up to space, Result
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:

  • Excel VBA String Proccessing and Manipulation

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

  • #3

Hi pac,

To select the current paragraph:

Selection.Paragraphs(1).Range.Select

But this will inlcude the paragraph mark, if you do not want the paragraph
mark,
add the following line right after the first one:

Selection.MoveLeft Unit:=wdCharacter, Count:=1, _
Extend:=wdExtend

But, even better still, work with the range object:

Dim myRange As Range

Set myRange = Selection.Paragraphs(1).Range
‘to remove the paragrpah mark if necessary:
myRange.SetRange myRange.Start, myRange.End — 1

Now, use myRange to copy, delete, etc. As in:

myRange.Copy
myRange.Delete

Or, if you really need to select it:

myRange.Select

HTH
Cheers!

INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Select text in Word with VBA

Select text in Word with VBA

(OP)

7 Jul 06 01:45

Hi,
Can anyone tell me how I can select text in Word with VBA.

I will select text between a start word and a end word.

Thanks in advance.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Join Tek-Tips® Today!

Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Tek-Tips Forums:

  • Tek-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

Аннотация: Лекция посвящена описанию объектов Selection и Range, описанию особенностей работы с автоматически выполняемыми макросами и шаблонами.

11.1. Объект Selection

Выше нам уже встречался и объект Selection, и объект Range. Здесь пришло время поговорить о них подробнее, обсудить особенности их использования.

Напомню, что объект Application.Selection представляет собой выделенный участок документа или, если ничего не выделено, позицию курсора. Именно этим объектом пользуется макрорекордер при записи макроса, выполняющего какие-либо операции с текстом.

У Selection есть два основных применения. Первое — автоматическое создание документов, не требующее правки шаблонов и других подобных операций. И второе — работа с фрагментом документа, предварительно выделенного пользователем.

Выделения можно создавать и программно, но эту методику практически никогда не используют на практике. Например, код листинга 11.1 выделяет седьмое слово в документе и форматирует его курсивом:

ActiveDocument.Words.Item(7).Select
Selection.Font.Italic = True


Листинг
11.1.
Выделяем седьмое слово и форматируем его

Предположим, мы используем такую конструкцию в шаблоне для автоматического форматирования текста. Если мы правильно рассчитаем номер слова, которое нужно отформатировать (или отредактировать, вставить в документ и т.д.) — то все будет работать правильно. Но стоит нам отредактировать шаблон — даже совсем немного, но так, что количество слов в нем изменится, наш макрос будет работать неправильно.

Объект Selection обычно используют без объявления объектной переменной. Например, для вставки в выделенную позицию документа текста «Привет» достаточно конструкции листинга 11.2.

Selection.Text = "Привет"


Листинг
11.2.
Добавляем текст в выделенную позицию документа

Минус использования Selection при автоматической обработке текста зависит от того, что он слишком чувствителен к действиям пользователя. Например, мы напишем программу, которая, имитируя выделение фрагментов текста с клавиатуры, обрабатывает текст. Если во время обработки текста пользователь вмешается, случайно кликнув мышью в документе, работа такой программы будет нарушена.

Рассмотрим основные свойства и методы объекта Selection.

11.2. Методы объекта Selection

11.2.1. ClearFormatting — очистить форматирование

Этот метод очищает форматирование выделенного участка документа.

11.2.2. Copy, Cut, Paste, Delete

Методы Copy и Cut, соответственно, копируют и вырезают выделенный фрагмент в буфер обмена, а метод Paste — вставляет материалы из буфера в область выделения.

Метод Delete удаляет выделенный фрагмент

11.2.3. InsertAfter, InsertBefore — добавление текста

Как следует из их названий, методы InsertAfter и InsertBefore позволяют вставить текст после или до выделения. Существуют и другие методы, название которых начинается с Insert. Они позволяют вставлять множество других объектов в выделенную область. Например, InsertBreak вставляет разрыв страницы, колонки или раздела, InsertCells вставляет в выделенную таблицу ячейки и т.д.

11.2.4. TypeBackspace — удалить символ

Удаляет один символ, предшествующий позиции курсора, имитируя нажатие клавиши Backspace на клавиатуре.

11.2.5. TypeParagraph — перевод строки

Имитирует нажатие клавиши Enter на клавиатуре — вставляет в текст знак перевода строки.

11.2.6. TypeText — вывести текст в документ

Вводит в документ текст. У метода есть лишь один параметр — Text. Он должен содержать тот текст, который должен быть выведен в документ. Ниже мы рассмотрим примеры, где используется этот метод.

11.2.7. WholeStory — выделить весь документ

Позволяет выделить весь документ. Пожалуй, это единственный удобный метод программного управления выделением.

11.3. Свойства объекта Selection

11.3.1. Bookmarks и другие

Это свойство возвращает коллекцию Bookmarks, которая содержит все закладки, имеющиеся в выделении. Существуют подобные свойства для символов ( Characters ), таблиц ( Tables ) и многих других коллекций объектов. Работа с ними ни чем не отличается от работы с аналогичными коллекциями, входящими в Document.

11.3.2. End и Start

Эти свойства позволяют узнать и модифицировать, соответственно, конечную ( End ) и начальную ( Start ) позиции выделения.

11.3.3. Font — шрифт

Это свойство позволяет узнавать и настраивать параметры шрифта выделенного фрагмента. Например, код, приведенный в листинге 11.3 форматирует текст. Пояснения к примеру приведены в комментариях.

'Полужирный
    Selection.Font.Bold = wdToggle
    'Курсивный
    Selection.Font.Italic = wdToggle
    'Подчеркнутый
    Selection.Font.Underline = wdUnderlineSingle
    'Гарнитура Arial Narrow
    Selection.Font.Name = "Arial Narrow"
    'Размер шрифта - 14
    Selection.Font.Size = 14
    'Цвет шрифта - красный - из
    'перечисления wdColorR
    Selection.Font.Color = wdColorRed


Листинг
11.3.
Форматируем текст

11.3.4. Information — подробности о выделении

Позволяет узнать подробности о выделении. Это свойство может принимать параметр типа wdInformation, который и определяет, что именно возвратит свойство.

11.3.5. Range — переход от Selection к Range

Это свойство позволяет получить объект Range, соответствующий выделению.

Например, этим свойством можно воспользоваться так, как показано в листинге 11.4.

Dim obj_Range As Range
Set obj_Range = Selection.Range


Листинг
11.4.
Получаем объект Range из Selection

11.3.5. Text — текст выделения

Это свойство позволяет получить текст, содержащийся в выделении, и изменить его.

11.4. Пример работы с Selection

11-01-Selection.docm— пример к п. 11.4.

Рассмотрим пример использования вышеперечисленных свойств и методов (а заодно – и некоторых других), решив небольшую задачу.

11.4.1. Задание

Создать новый документ, и добавить в него текст, который был выделен в текущем документе. Каждое слово этого текста надо напечатать отдельно, с новой строки. Каждое слово должно предваряться таким текстом: «Слово №x:», где x — номер слова в выделенном тексте. После вывода слов нужно подсчитать количество слов и количество букв в этих словах и вывести строку «Всего обработано «x» слов, состоящих из «xx» букв». Готовый документ сохранить на диске C:, задав в качестве его имени такую структуру:

"Имя_исходного_документа"+ "текущая дата"+ "обработано".docm

После того, как слова будут выведены, нужно заключить выделенный участок исходного документа в скобки, отметить синим цветом шрифта и выделить первый символ текущего выделения.

11.4.2. Решение

Создадим новый макрос ( Copy_To_File ), воспользовавшись окном Макросы, которое можно открыть с вкладки Вид.

Добавим в макрос код из листинга 11.5.

'Переменая для хранения ссылки на новый документ
    Dim obj_NewDoc As Document
    'Для ссылки на исходный документ
    Dim obj_OurDoc As Document
    'Динамический массив для хранения слов
    Dim WordsArray() As String
    'Переменная для хранения количества слов
    Dim WordsCount
    'Переменная для формирования строк,
    'которые выводятся в новый документ
    Dim OutString
    'Переменная для хранения количества
    'символов в обработанных словах
    Dim LettersCount
    'В этой переменной будем создавать
    'имя файла
    Dim NewDocName
    'Запишем ссылку на активный документ
    'Для того, чтобы вернуться в него
    'после работы с новым документом
    Set obj_OurDoc = ActiveDocument
    WordsCount = Selection.Words.Count
    LettersCount = Selection.Characters.Count
    ReDim WordsArray(WordsCount)
    'Переносим слова из выделения
    'в массив для удобства работы с ними
    For i = 1 To WordsCount
        WordsArray(i) = Selection.Words.Item(i)
    Next i
    'Создадим новый документ
    Set obj_NewDoc = Documents.Add
    'И сделаем его активным
    obj_NewDoc.Activate
    'Теперь объект Selection относится к активному
    'документу и мы начинаем вводить в него данные
    Selection.TypeText ("Список выделенных слов")
    Selection.TypeParagraph
    For i = 1 To WordsCount
        OutString = "Слово №" + Str(i) + ": " + _
        WordsArray(i)
        Selection.TypeText (OutString)
        Selection.TypeParagraph
    Next i
    Selection.TypeText ("Всего обработано " + _
    Str(WordsCount) + _
    " слов(а), в которых содержится " + _
    Str(LettersCount) + " символа(ов)")
    'Создаем имя нового документа
    NewDocName = obj_OurDoc.Name + " " + _
    Str(Date) + " Обработано.docx"
    'Установим корневой каталог диска C:
    'для сохранения нового файла по умолчанию
    ChangeFileOpenDirectory "C:"
    'Используем метод SaveAs для
    'автоматического сохранения
    'документа
    ActiveDocument.SaveAs _
    FileName:=NewDocName, _
    FileFormat:=wdFormatDocumentDefault
    'Закрываем активный документ
    ActiveDocument.Close
    'Активируем документ, в котором мы выделяли
    'слова
    obj_OurDoc.Activate
    'Отмечаем обработанный участок
    'скобками и выделением синим цветом
    Selection.InsertAfter (") ")
    Selection.InsertBefore (" (")
    Selection.Font.Color = wdColorBlue
    'Выделяем первый символ текущего выделения и
    'выводим сообщение о том, что операция
    'выполнена
    Selection.Characters(1).Select
    MsgBox ("Выполнено!")


Листинг
11.5.
Решение задачи

Как видите, в этом примере мы используем исключительно объект Selection для работы с текстом документов. Обратите внимание на то, что мы нигде специально не храним информацию о выделенной области первого документа. Создав второй документ, мы просто делаем его активным и работаем с ним, используя его объект Selection. В это время выделение сохраняется в исходном документе. Однако, если в это время пользователь случайно или умышленно изменит выделение текущего документа — программа будет работать неправильно — она выделит не тот фрагмент, который был передан ей для обработки, а совсем другой.

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Selection object (Word)

vbawd10.chm2421

vbawd10.chm2421

word

Word.Selection

7b574a91-c33e-ecfd-6783-6b7528b2ed8f

05/23/2019

high

Selection object (Word)

Represents the current selection in a window or pane. A selection represents either a selected (or highlighted) area in the document, or it represents the insertion point if nothing in the document is selected. There can be only one Selection object per document window pane, and only one Selection object in the entire application can be active.

[!IMPORTANT]
This method has changed. Using VBA Selection commands like Selection.BoldRun on user selection with Comments no longer applies bold formatting on user-selected text or Selection.TypeTxt command or on user selection with Comments no longer inserts text.

Remarks

Use the Selection property to return the Selection object. If no object qualifier is used with the Selection property, Microsoft Word returns the selection from the active pane of the active document window. The following example copies the current selection from the active document.

The following example deletes the selection from the third document in the Documents collection. The document does not have to be active to access its current selection.

Documents(3).ActiveWindow.Selection.Cut

The following example copies the selection from the first pane of the active document and pastes it into the second pane.

ActiveDocument.ActiveWindow.Panes(1).Selection.Copy 
ActiveDocument.ActiveWindow.Panes(2).Selection.Paste

The Text property is the default property of the Selection object. Use this property to set or return the text in the current selection. The following example assigns the text in the current selection to the variable strTemp, removing the last character if it is a paragraph mark.

Dim strTemp as String 
 
strTemp = Selection.Text 
If Right(strTemp, 1) = vbCr Then _ 
 strTemp = Left(strTemp, Len(strTemp) - 1)

The Selection object has various methods and properties with which you can collapse, expand, or otherwise change the current selection. The following example moves the insertion point to the end of the document and selects the last three lines.

Selection.EndOf Unit:=wdStory, Extend:=wdMove 
Selection.HomeKey Unit:=wdLine, Extend:=wdExtend 
Selection.MoveUp Unit:=wdLine, Count:=2, Extend:=wdExtend

The Selection object has various methods and properties with which you can edit selected text in a document. The following example selects the first sentence in the active document and replaces it with a new paragraph.

Options.ReplaceSelection = True 
ActiveDocument.Sentences(1).Select 
Selection.TypeText "Material below is confidential." 
Selection.TypeParagraph

The following example deletes the last paragraph of the first document in the Documents collection and pastes it at the beginning of the second document.

With Documents(1) 
 .Paragraphs.Last.Range.Select 
 .ActiveWindow.Selection.Cut 
End With 
 
With Documents(2).ActiveWindow.Selection 
 .StartOf Unit:=wdStory, Extend:=wdMove 
 .Paste 
End With

The Selection object has various methods and properties with which you can change the formatting of the current selection. The following example changes the font of the current selection from Times New Roman to Tahoma.

If Selection.Font.Name = "Times New Roman" Then _ 
 Selection.Font.Name = "Tahoma"

Use properties like Flags, Information, and Type to return information about the current selection. Use the following example in a procedure to determine whether there is anything selected in the active document; if there is not, the rest of the procedure is skipped.

If Selection.Type = wdSelectionIP Then 
 MsgBox Prompt:="You have not selected any text! Exiting procedure..." 
 Exit Sub 
End If

Even when a selection is collapsed to an insertion point, it is not necessarily empty. For example, the Text property will still return the character to the right of the insertion point; this character also appears in the Characters collection of the Selection object. However, calling methods like Cut or Copy from a collapsed selection causes an error.

It is possible for the user to select a region in a document that does not represent contiguous text (for example, when using the Alt key with the mouse). Because the behavior of such a selection can be unpredictable, you may want to include a step in your code that checks the Type property of a selection before performing any operations on it (Selection.Type = wdSelectionBlock).

Similarly, selections that include table cells can also lead to unpredictable behavior. The Information property will tell you if a selection is inside a table (Selection.Information(wdWithinTable) = True). The following example determines if a selection is normal (for example, it is not a row or column in a table, it is not a vertical block of text); you could use it to test the current selection before performing any operations on it.

If Selection.Type <> wdSelectionNormal Then 
 MsgBox Prompt:="Not a valid selection! Exiting procedure..." 
 Exit Sub 
End If

Because Range objects share many of the same methods and properties as Selection objects, using Range objects is preferable for manipulating a document when there is not a reason to physically change the current selection. For more information about Selection and Range objects, see Working with the Selection object and Working with Range objects.

Methods

  • BoldRun
  • Calculate
  • ClearCharacterAllFormatting
  • ClearCharacterDirectFormatting
  • ClearCharacterStyle
  • ClearFormatting
  • ClearParagraphAllFormatting
  • ClearParagraphDirectFormatting
  • ClearParagraphStyle
  • Collapse
  • ConvertToTable
  • Copy
  • CopyAsPicture
  • CopyFormat
  • CreateAutoTextEntry
  • CreateTextbox
  • Cut
  • Delete
  • DetectLanguage
  • EndKey
  • EndOf
  • EscapeKey
  • Expand
  • ExportAsFixedFormat
  • ExportAsFixedFormat2
  • Extend
  • GoTo
  • GoToEditableRange
  • GoToNext
  • GoToPrevious
  • HomeKey
  • InRange
  • InsertAfter
  • InsertBefore
  • InsertBreak
  • InsertCaption
  • InsertCells
  • InsertColumns
  • InsertColumnsRight
  • InsertCrossReference
  • InsertDateTime
  • InsertFile
  • InsertFormula
  • InsertNewPage
  • InsertParagraph
  • InsertParagraphAfter
  • InsertParagraphBefore
  • InsertRows
  • InsertRowsAbove
  • InsertRowsBelow
  • InsertStyleSeparator
  • InsertSymbol
  • InsertXML
  • InStory
  • IsEqual
  • ItalicRun
  • LtrPara
  • LtrRun
  • Move
  • MoveDown
  • MoveEnd
  • MoveEndUntil
  • MoveEndWhile
  • MoveLeft
  • MoveRight
  • MoveStart
  • MoveStartUntil
  • MoveStartWhile
  • MoveUntil
  • MoveUp
  • MoveWhile
  • Next
  • NextField
  • NextRevision
  • NextSubdocument
  • Paste
  • PasteAndFormat
  • PasteAppendTable
  • PasteAsNestedTable
  • PasteExcelTable
  • PasteFormat
  • PasteSpecial
  • Previous
  • PreviousField
  • PreviousRevision
  • PreviousSubdocument
  • ReadingModeGrowFont
  • ReadingModeShrinkFont
  • RtlPara
  • RtlRun
  • Select
  • SelectCell
  • SelectColumn
  • SelectCurrentAlignment
  • SelectCurrentColor
  • SelectCurrentFont
  • SelectCurrentIndent
  • SelectCurrentSpacing
  • SelectCurrentTabs
  • SelectRow
  • SetRange
  • Shrink
  • ShrinkDiscontiguousSelection
  • Sort
  • SortAscending
  • SortByHeadings
  • SortDescending
  • SplitTable
  • StartOf
  • ToggleCharacterCode
  • TypeBackspace
  • TypeParagraph
  • TypeText
  • WholeStory

Properties

  • Active
  • Application
  • BookmarkID
  • Bookmarks
  • Borders
  • Cells
  • Characters
  • ChildShapeRange
  • Columns
  • ColumnSelectMode
  • Comments
  • Creator
  • Document
  • Editors
  • End
  • EndnoteOptions
  • Endnotes
  • EnhMetaFileBits
  • ExtendMode
  • Fields
  • Find
  • FitTextWidth
  • Flags
  • Font
  • FootnoteOptions
  • Footnotes
  • FormattedText
  • FormFields
  • Frames
  • HasChildShapeRange
  • HeaderFooter
  • HTMLDivisions
  • Hyperlinks
  • Information
  • InlineShapes
  • IPAtEndOfLine
  • IsEndOfRowMark
  • LanguageDetected
  • LanguageID
  • LanguageIDFarEast
  • LanguageIDOther
  • NoProofing
  • OMaths
  • Orientation
  • PageSetup
  • ParagraphFormat
  • Paragraphs
  • Parent
  • PreviousBookmarkID
  • Range
  • Rows
  • Sections
  • Sentences
  • Shading
  • ShapeRange
  • Start
  • StartIsActive
  • StoryLength
  • StoryType
  • Style
  • Tables
  • Text
  • TopLevelTables
  • Type
  • WordOpenXML
  • Words
  • XML

See also

  • Word Object Model Reference

[!includeSupport and feedback]

Понравилась статья? Поделить с друзьями:
  • Vba word rows count
  • Vba word диалог выбора файла
  • Vba word replace wdreplaceall
  • Vba word двусторонняя печать
  • Vba word replace all text