Word vba selection end

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

Selection.End property (Word)

vbawd10.chm158662660

vbawd10.chm158662660

word

Word.Selection.End

99e3bd79-a8f1-8057-1ac2-b9e76eab99ff

06/08/2017

medium

Selection.End property (Word)

Returns or sets the ending character position of a selection. Read/write Long.

Syntax

expression.End

expression A variable that represents a Selection object.

Remarks

If this property is set to a value smaller than the Start property, the Start property is set to the same value (that is, the Start and End property are equal).

The Selection object has a starting position and an ending position. The ending position is the point farthest away from the beginning of the story. This property returns the ending character position relative to the beginning of the story. The main document story (wdMainTextStory) begins with character position 0 (zero). You can change the size of a selection by setting this property.

Example

This example retrieves the ending position of the selection. This value is used to create a range so that a field can be inserted after the selection.

pos = Selection.End 
Set myRange = ActiveDocument.Range(Start:=pos, End:=pos) 
ActiveDocument.Fields.Add Range:=myRange, Type:=wdFieldAuthor

See also

Selection Object

[!includeSupport and feedback]

Всем привет, с вами автор блога scriptcoding.ru. В этой статье мы рассмотрим методы объекта Word Selection, которые позволяют очистить материал от форматирования, преобразовать в таблицу, а также производить копирование, вставку и так далее. Помним, что данный класс отвечает за выделение текста в Word.

Содержание

  1. Методы класса Word.Selection – выделение текста в Word
  2. Примера на языке VBScript – выделение текста в редакторе Word
  3. Примера на языке JScript – выделение текста в редакторе Word

Методы класса Word.Selection – выделение текста в Word

Я приведу по два примера программного кода на языках JScript, VBScript и VBA. Хотя по сути, код под макрос (VBA) и сценарий VBScript особо не отличается. Для тех, кто забыл: для создания макроса в документе Microsoft Office нужно вызвать редактор Visual Basic for Application (комбинация клавиш Alt + F11), далее, добавить в проект новый модуль (макрос).

Методы с префиксом Clear… позволяют очистить выделенный материал от форматирования (абзацы, стили, символы и так далее):

ClearCharacterAllFormatting() — Все форматирование.

ClearCharacterDirectFormatting() — Форматирование знаков.

ClearCharacterStyle() — Форматирование знаков, применяемых через стили.

ClearFormatting() – Все форматирования (параграфы, стили и так далее).

ClearParagraphAllFormatting() — Форматирование абзаца.

ClearParagraphDirectFormatting() — Форматирование абзацев, применяемых вручную.

ClearParagraphStyle() — Форматирование абзацев, применяемых через стили.

Collapse(Direction) – Позволяет убрать выделение текста Word и переместить указатель в начало или конец. VBA Selection. Если параметры отсутствуют, то просто убирается выделение. Параметр Direction содержит значение константы WdCollapseDirection:

  • wdCollapseEnd — 0 – Указатель вконец
  • wdCollapseStart — 1 – Указатель вначале

ConvertToTable(Separator, NumRows, NumColumns, InitialColumnWidth, Format, ApplyBorders, ApplyShading, ApplyFont, ApplyColor, ApplyHeadingRows, ApplyLastRow, ApplyFirstColumn, ApplyLastColumn, AutoFit, AutoFitBehavior, DefaultTableBehavior) – Довольно мощный метод, который позволяет преобразовать выделенный Word текст в таблицу.

Separator — Символ-разделитель, может быть знаком или значением константы WdTableFieldSeparator:

  • wdSeparateByParagraphs — 0 — абзаца.
  • wdSeparateByTabs — 1 — табуляции.
  • wdSeparateByCommas — 2 — запятая.
  • wdSeparateByDefaultListSeparator — 3 — разделитель списка по умолчанию.

NumRows— Количество строк.

NumColumns— Количество столбиков.

InitialColumnWidth— Начальная ширина каждого столбца, в пунктах.

Format– Определяет формат таблицы и содержит значение константы WdTableFormat.

ApplyBorders— TRUE — применять границы.

ApplyShading— TRUE — применить затенение.

ApplyFont— TRUE применять свойства шрифтов.

ApplyColor— TRUE применять цветовые свойства.

ApplyHeadingRows— TRUE — применить свойства заголовок-строка.

ApplyLastRow— TRUE — применить свойства последней строке.

ApplyFirstColumn— TRUE — применить свойства первого столбцов.

ApplyLastColumn— TRUE — применить свойства последнего столбца.

AutoFit— TRUE — уменьшить ширину столбцов таблицы как можно больше.

AutoFitBehavior — Устанавливает правила авто-подбора (если DefaultTableBehavior содержит значение wdWord8TableBehavior, то этот аргумент игнорируется, VBA Selection), содержит значения константы WdAutoFitBehavior:

  • wdAutoFitContent — 1 — автоматически размер
  • wdAutoFitFixed — 0 — фиксированный размер
  • wdAutoFitWindow — 2 — автоматический размер по ширине активного окна

DefaultTableBehavior— Значение, указывающее, следует ли автоматически изменять размер ячеек таблицы по содержимому. Selection VBA. Содержит значение константы WdDefaultTableBehavior:

  • wdWord8TableBehavior — 0 — отключает Авто-подбор (по умолчанию)
  • wdWord9TableBehavior — 1 — включить Авто-подбор

Выделение блока текста в Word, VBA Selection

Хорошо, с теоретической частью мы закончили, теперь можно приступить к программированию.

Примера на языке VBScript – выделение текста в редакторе Word

' ----------------------------------------------------------------------------
' Объект Selection - выделение текста в Word
' Преобразование в таблицу - язык VBScript
' VBA_Selection_Table.vbs
' ----------------------------------------------------------------------------
Option Explicit
 
dim oWord, oDoc, oSel, i
 
Set oWord = CreateObject("Word.Application")
Set oDoc = oWord.Documents
oDoc.Add()
Set oSel = oWord.Selection
oWord.Visible = True
 
For i = 0 To 10
With oSel
.InsertBreak 6
.InsertBefore "один, два, три, четыре, пять, шесть, selection word vba"
.EndOf
.InsertBreak 6
End With
Next
 
oWord.Documents(1).Select()
oSel.ConvertToTable ",", 31,,,18

В данном примере в цикле For (смотрите статью «Урок 6 по VBScript: Циклы for…next и for each…next«), который выполняется шесть раз, происходит вставка перевода на новую строку, вставка текстовой фразы и перемещаем курсов к конец строки. С помощью оператора with мы можем экономить размер программного кода – не нужно лишний раз писать имя класса. Вконце происходит выделение текста Word и преобразование его в таблицу.

Примера на языке JScript – выделение текста в редакторе Word

// ----------------------------------------------------------------------------
// Объект Selection - выделение текста в Word
// Преобразование в таблицу - язык JScript
// VBA_Selection_Table.js
// ----------------------------------------------------------------------------
 
var oWord1, oDoc1, oSel1, i;
 
oWord1 = WScript.CreateObject("Word.Application");
oDoc1 = oWord1.Documents;
oDoc1.Add();
oSel1 = oWord1.Selection;
oWord1.Visible = true;
 
for (i=0; i<=10;i++){
with(oSel1){
InsertBreak(6);
InsertBefore("один, два, три, четыре, пять, шесть, selection word vba");
EndOf();
InsertBreak(6);
}
}
 
oWord1.Documents(1).Select();
oSel1.ConvertToTable(",", 31,"","",18);

Логика работы данного программного кода аналогичны предыдущему примеру, тут мы уже использовали цикл for языка JS, читайте в статье «Урок 9 по JScript — оператор цикла for«. Тут тоже использовался оператор with, обратите внимание, что имена переменных изменились, а в конце каждой строки кода прописана точка с запятой.

Примера на языке Visual Basic for Application – выделение текста в редакторе Word

'VBA
Dim oWord2 As Object, oDoc2 As Object, oSel2 As Object, i
 
Set oWord2 = CreateObject("Word.Application")
Set oDoc2 = oWord2.Documents
oDoc2.Add
Set oSel2 = oWord2.Selection
oWord2.Visible = True
 
For i = 0 To 10
With oSel2
.InsertBreak 6: .InsertBefore "один, два, три, четыре, пять, шесть, selection word vba"
.EndOf: .InsertBreak 6
End With
Next
 
oWord2.Documents(1).Select
oSel2.ConvertToTable Separator:=",", NumRows:=31, Format:=18

Хорошо, давайте продолжим рассматривать методы класса Selection.

выделение текста в редакторе Word, Selection VBA

EndOf() – Перемещает курсор в конец выделения.

StartOf() – Перемещает курсор в начало выделения.

SetRange(start, end) – Позволяет задать начальное и конечное значение для выделения текста Word.

TypeText() – Выполняет ту же функцию, что и свойство Text – ввод информации.

TypeParagraph() — Метод вставляет параграф.

Copy(), Cut(), Paste(), Delete() – Копирует, вырезает, вставляет и удаляет выделенный текст в Word.

CopyAsPicture() – Копирует выбранный материал как изображение.

И так, теперь рассмотрим программный код с данными методами.

' ----------------------------------------------------------------------------
' Класс Selection - выделение текста в Word
' Копирование и вставка - язык VBScript
' VBA_Selection_Copy_Paste.vbs
' ----------------------------------------------------------------------------
Option Explicit
 
dim oWord3, oDoc3, oSel3, i
 
Set oWord3 = CreateObject("Word.Application")
Set oDoc3 = oWord3.Documents
oDoc3.Add()
Set oSel3 = oWord3.Selection
oWord3.Visible = True
 
' Вводим информацию в документ сто раз
For i=0 to 100
  oSel3.TypeText "Пример ввода данных - selection word vba. "
Next
 
With oSel3
  ' Выделяем, копируем и вставляем
  .SetRange 100, 300
  .Copy
  .MoveDown
  .Paste
 
  ' Выбираем материал и копируем ее как изображение
  .SetRange 100, 300
  .CopyAsPicture
End With

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

// ----------------------------------------------------------------------------
// Класс Selection - выделение текста в Word
// Копирование и вставка - язык JScript
// VBA_Selection_Copy_Paste.js
// ----------------------------------------------------------------------------
 
var oWord5, oDoc5, oSel5, i;
 
oWord5 = WScript.CreateObject("Word.Application");
oDoc5 = oWord5.Documents;
oDoc5.Add();
oSel5 = oWord5.Selection;
oWord5.Visible = true;
 
// Вводим данные в документ сто раз
for(i=0; i<=100; i++){
  oSel5.TypeText("Пример ввода информации - selection word vba. ");
}
 
with(oSel5){
  // Выделяем, копируем и вставляем
  SetRange(100, 300);
  Copy();
  MoveDown();
  Paste();
 
  // Выделяем и копируем как изображение
  SetRange(100, 300);
  CopyAsPicture();
}

Ну и в заключение, привожу программный код для макроса:

' VBA
Dim oWord6 As Object, oDoc6 As Object, oSel6 As Object, i
 
Set oWord6 = CreateObject("Word.Application")
Set oDoc6 = oWord6.Documents
oDoc6.Add
Set oSel6 = oWord6.Selection
oWord6.Visible = True
 
For i = 0 To 100
  oSel6.TypeText "Пример ввода информации - selection word vba. "
Next
 
With oSel6
  .SetRange 100, 300: .Copy: .MoveDown: .Paste
  .SetRange 100, 300: .CopyAsPicture
End With

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

In my vba code I need to go to the end of the word document.
The vba is written and executed from Excel.
The statement : Selection.EndKey unit:=wdStory, Extend:=wdMove » will not run.
Can anyone explain where I do the mistyping.

I have tried to use the statement in other vba codes, but without success.

Sub InsertFromFilesTestEnd()


Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document


    Set wrdApp = New Word.Application
    Set wrdDoc = wrdApp.Documents.Open("c:userspeterdocumentsdirekte 0302 1650.docm")
        wrdApp.Visible = True
        wrdApp.Activate
        Application.ScreenUpdating = False

Selection.EndKey unit:=wdStory, Extend:=wdMove
End Sub

Hopefully you can guide me to the end of my document. When so, I am sure I can use «selection» to move around in the document.

Cindy Meister's user avatar

asked Feb 8, 2019 at 13:04

Peter Grandjean's user avatar

2

The issue here is that Selection isn’t qualified to which application’s Selection you are wanting. As such, it’s using the default for Excel VBA, which would be the Excel Application in which the VBA was launched. Implicitly you are saying:

Application.Selection.EndKey unit:=wdStory, Extend:=wdMove

The error is because Excel’s Application.Selection object doesn’t have an EndKey method and so VBA has no idea what you are trying to do here.

Instead you want to qualify that Selection with the instance of the Word.Application object you are already working with:

wrdApp.Selection.EndKey unit:=wdStory, Extend:=wdMove

answered Feb 8, 2019 at 13:57

JNevill's user avatar

JNevillJNevill

45.8k3 gold badges36 silver badges60 bronze badges

0

Using Selections in cases like this is quite unnecessary. Aside from being inefficient, it’s also prone to producing a lot of screen flicker. Try, for example:

Sub InsertFromFilesTestEnd()
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = New Word.Application
With wrdApp
    .Visible = True
    .ScreenUpdating = False
    Set wrdDoc = .Documents.Open("c:userspeterdocumentsdirekte 0302 1650.docm")
    With wdrDoc
        .Range.Characters.Last.InsertFile FileName:="MyFileName", Range:="", _
            ConfirmConversions:=False, Link:=False, Attachment:=False
    End With
    .Activate
    .ScreenUpdating = True
End With
End Sub

answered Feb 10, 2019 at 20:30

macropod's user avatar

macropodmacropod

12.6k2 gold badges9 silver badges21 bronze badges

Microsoft Word Selection Object with code example

Selection

Selection Object Represents the current cursor position in a Word Document. Selection object offers various properties and methods which can be used to manipulate document area.

Copy

Public Sub CopySelection()
	Dim oRange As Range
	Set oRange = Selection.Range
	oRange.Copy
End Sub

Cut

Public Sub CutSelection()
	Documents(3).ActiveWindow.Selection.Cut
End Sub

Copy Paste

Public Sub CopyPasteSelection()
	ActiveDocument.ActiveWindow.Panes(1).Selection.Copy 
	ActiveDocument.ActiveWindow.Panes(2).Selection.Paste
End Sub

Text property

Public Sub RemoveParaMarkFromSelection()
	Dim sTemp as String 
	sTemp = Selection.Text 
	
	If Right(sTemp, 1) = vbCr Then  
		sTemp = Left(sTemp, Len(sTemp) - 1)
	End if
End Sub

Collapse and Expand

Public Sub CollapseSelection()
	Selection.EndOf Unit:=wdStory, Extend:=wdMove 
	Selection.HomeKey Unit:=wdLine, Extend:=wdExtend 
	Selection.MoveUp Unit:=wdLine, Count:=2, Extend:=wdExtend
End Sub

Select

Public Sub SelectExample()
	Options.ReplaceSelection = True 
	ActiveDocument.Sentences(1).Select 
	Selection.TypeText "This is a new paragraph." 
	Selection.TypeParagraph
End Sub

Delete

Public Sub CopyPasteSelection()
	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
End Sub

Font

Public Sub ChangeFont()
	If Selection.Font.Name = "Times New Roman" Then  
		Selection.Font.Name = "Arial"
	End If
End Sub

Type

Public Sub SelectionType()
	If Selection.Type = wdSelectionIP Then 
		MsgBox Prompt:="You have not selected any text!!!" 
		Exit Sub 
	End If
End Sub

Next>>InsertFile Method Microsoft Word VBA

Old

07-02-2017, 03:14 AM

paik1002
paik1002 is offline

How to get start and end range indices of a selection Windows 7 64bit How to get start and end range indices of a selection Office 2010 64bit

Advanced Beginner

How to get start and end range indices of a selection

 

Join Date: Dec 2015

Posts: 63

paik1002 is on a distinguished road

Default

How to get start and end range indices of a selection


Two related questions:

Q1. How do I detect if text is already selected.
Q2. If text has already been selected (highlighted), how to get start and end range indices of the selection?

I need to get the text re-selected after doing something else (hence above text selection becomes unselected), so I need to know the exact range indices.

VBA codes please. Help would be appreciated.

Reply With Quote

Old

07-02-2017, 05:04 AM

Default


Declare and apply a range to the selection, while it is selected e.g.

Code:

Sub Macro1()
'Graham Mayor - http://www.gmayor.com - Last updated - 02 Jul 2017
Dim oRng As Range
    Set oRng = Selection.Range
    If Len(oRng) = 0 Then
        MsgBox "Nothing selected!"
    Else
        'do something with orng
    End If
lbl_Exit:
    Set oRng = Nothing
    Exit Sub
End Sub

__________________
Graham Mayor — MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com

Reply With Quote

Old

07-02-2017, 05:39 AM

paik1002
paik1002 is offline

How to get start and end range indices of a selection Windows 7 64bit How to get start and end range indices of a selection Office 2010 64bit

Advanced Beginner

How to get start and end range indices of a selection

 

Join Date: Dec 2015

Posts: 63

paik1002 is on a distinguished road

Default


Thank you!
One more question related to your answer: How re-select the same text (maybe after being unselected) using another macro (e.g. Macro2)?

Macro1 will get the range of a selected text and memorize it.
Macro2 will find the selected text and reselect it from memory.

Yours gratefully.

Reply With Quote

Old

07-02-2017, 06:21 AM

gmaxey
gmaxey is offline

How to get start and end range indices of a selection Windows 7 32bit How to get start and end range indices of a selection Office 2016

Word MVP 2003-2009

 

Join Date: May 2010

Location: Brasstown, NC

Posts: 1,250

gmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the roughgmaxey is a jewel in the rough

Default


Provided something doesn’t happen to drop the variable out of scope something like this perhaps:

Code:

Option Explicit
Private oRng As Range
Sub SetSelection()
  Set oRng = Selection.Range
End Sub
Sub Reselect()
  oRng.Select
End Sub

Reply With Quote

Old

07-02-2017, 07:35 AM

paik1002
paik1002 is offline

How to get start and end range indices of a selection Windows 7 64bit How to get start and end range indices of a selection Office 2010 64bit

Advanced Beginner

How to get start and end range indices of a selection

 

Join Date: Dec 2015

Posts: 63

paik1002 is on a distinguished road

Default


Bulls eye! Thank you very much and have a good day.

Reply With Quote

Old

07-02-2017, 08:08 PM

Default


The beauty of ranges is that you don’t need to select them in order to process them. What was it that you were doing with the ‘selection’?

__________________
Graham Mayor — MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com

Reply With Quote

Old

07-02-2017, 09:44 PM

paik1002
paik1002 is offline

How to get start and end range indices of a selection Windows 7 64bit How to get start and end range indices of a selection Office 2010 64bit

Advanced Beginner

How to get start and end range indices of a selection

 

Join Date: Dec 2015

Posts: 63

paik1002 is on a distinguished road

Default


I am planning to use it mostly for navigational purposes combined with editing functions such as copy/paste. I do get lost a lot when moving around in a document, so I found it convenient to keep track of past edits.

Since you mention the versatility of ranges,
may I ask further how I can extend or contract ranges given the current selection of text (e.g. oRng.Select) or the memory of it (e.g. Set oRng = Selection.Range)?
Maybe add/subtract an adjacent word at the outer periphery (front or back) of the current selection of text.

For example:
the body of text is: Hello there how are you doing these days?
current selection: how are you doing
add to selection: how are you doing these days?
subtract to selection: how are you

Please kindly provide example VB codes if possible.

Reply With Quote

Old

07-02-2017, 10:44 PM

Default


You can manipulate a range in a variety of ways, but a couple of examples using your text. Note that you don’t have to select the range to process it. The .select rows are only inserted to show what is happening to the range directly in the text. If you are moving range ends then choose a method that is unambiguous with regard to the text

Code:

Sub Macro1()
Dim oRng As Range
    Set oRng = Selection.Range
    oRng.MoveEndUntil "?"
    oRng.End = oRng.End + 1
    oRng.Select    'not necessary to process the range
    MsgBox oRng.Text
    oRng.MoveEndUntil "u", wdBackward
    oRng.Select    'not necessary to process the range
    MsgBox oRng.Text
End Sub

Sub Macro2()
Dim oRng As Range
    Set oRng = Selection.Range
    'move to the end of the paragraph (before the paragraph mark)
    oRng.End = oRng.Paragraphs(1).Range.End - 1
    oRng.Select    'not necessary to process the range
    MsgBox oRng.Text
    'Move the end back four 'words'
    oRng.MoveEnd wdWord, -4
    'Remove the final space from the range
    oRng.End = oRng.End - 1
    oRng.Select    'not necessary to process the range
    MsgBox oRng.Text
End Sub

You can also have multiple ranges e.g.

Code:

Sub Macro3()
Dim orng As Range
Dim oStart As Range
    Set oStart = Selection.Range
    Set orng = Selection.Range
    'move to the end of the paragraph (before the paragraph mark)
    orng.End = orng.Paragraphs(1).Range.End - 1
    orng.Select    'not necessary to process the range
    MsgBox orng.Text
    'Move the end back four 'words'
    orng.MoveEnd wdWord, -4
    'Remove the final space from the range
    orng.End = orng.End - 1
    orng.Select    'not necessary to process the range
    MsgBox orng.Text
    'go back to the original selection
    oStart.Select     'not necessary to process the range
    MsgBox oStart.Text
End Sub

__________________
Graham Mayor — MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com

Reply With Quote

Понравилась статья? Поделить с друзьями:
  • Word vba select paragraphs
  • Word vba save as document
  • Word vba range весь текст
  • Word vba range start
  • Word vba range font