Vba word selection in table

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Ask Question

Asked
11 years, 3 months ago

Modified
2 years, 9 months ago

Viewed
16k times

6

How can I determine the current row where a selection is active of the table in a Word VBA macro?

I’ve tried all variants with no success:

MsgBox Selection.Range
MsgBox Selection.Rows.Item.Index

  • vba
  • ms-word
  • row

Improve this question

edited Jul 5, 2020 at 12:10

Martijn Pieters's user avatar

Martijn Pieters

1.0m288 gold badges4004 silver badges3309 bronze badges

asked Dec 29, 2011 at 13:11

Crimix's user avatar

CrimixCrimix

3991 gold badge2 silver badges11 bronze badges

0

Add a comment
 | 

1 Answer

Sorted by:

Reset to default

15

I figured it out myself:

MsgBox Selection.Information(wdEndOfRangeRowNumber)
MsgBox Selection.Cells(1).RowIndex

Improve this answer

edited Jan 1, 2012 at 20:45

joran's user avatar

joran

168k32 gold badges428 silver badges464 bronze badges

answered Jan 1, 2012 at 20:20

Crimix's user avatar

CrimixCrimix

3991 gold badge2 silver badges11 bronze badges

1

  • And also Selection.Information(wdStartOfRangeRowNumber)

    – Winand

    Oct 27, 2022 at 7:12

Add a comment
 | 

Your Answer

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged

  • vba
  • ms-word
  • row

or ask your own question.

  • The Overflow Blog
  • Are meetings making you less productive?

  • The philosopher who believes in Web Assembly

  • Featured on Meta
  • Improving the copy in the close modal and post notices — 2023 edition

  • Temporary policy: ChatGPT is banned

  • The [protection] tag is being burninated

  • Content Discovery initiative 4/13 update: Related questions using a Machine…

Related

2612

How do you display code snippets in MS Word preserving format and syntax highlighting?

20

VBA How to get path to The Current Users Application data folder?

497

How do I add indexes to MySQL tables?

0

Qualify Selection Object in VBA Word

0

VBA — Macro to extend selection to end of current table column, then find and replace only within that selection

0

VBA Word trying to shade SELECTED cells in one table in word that are bold

0

VBA Macros Lost After Updating to 2010 Word

1

How to make Microsoft Word visible after opening an Excel file in Word VBA

5

Set table column widths in Word macro VBA

Hot Network Questions

  • Change size of dingbat

  • «Why» do animals excrete excess nitrogen instead of recycling it?

  • How would a future humanity «terraform» the moon?

  • Does Ohm’s law always apply at any instantaneous point in time?

  • Can ultra-low-frequency photon rockets be «safe»?

  • Ways to form pairs of 2n people

  • PC to phone file transfer speed

  • The challenge Large Language Models (LLMs) pose to programming-based homework

  • String Comparison

  • Is there a way to calculate a hash with two people so that no one knows the pre-image but if they get together they do?

  • Why doesn’t read permission on directories reveal inode numbers?

  • How can one transform a neutral lookup table texture for color blindness?

  • Good / recommended way to archive fastq and bam files?

  • What is the difference between elementary and non-elementary proofs of the Prime Number Theorem?

  • Why don’t SpaceX boosters belly flop?

  • How can I showcase characters that aren’t stealthy in a stealth-based mission?

  • How does copyrights work for mobile/web applications?

  • What does Thoreau mean about the Tract Society printing the story of Putnam?

  • How can Russia enforce the Wikimedia fines

  • Two proportion sample size calculation

  • How to tell what configuration a transistor has in a complicated circuit

  • Can I develop Windows, macOS, and Linux software or a game on one Linux distribution?

  • Did Hitler say that «private enterprise cannot be maintained in a democracy»?

  • What do ‘spile’ and ‘bung’ mean in this sentence written by Thoreau?

more hot questions

Question feed

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

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]

Создание таблиц в документе Word из кода VBA Excel. Метод Tables.Add, его синтаксис и параметры. Объекты Table, Column, Row, Cell. Границы таблиц и стили.

Работа с Word из кода VBA Excel
Часть 4. Создание таблиц в документе Word
[Часть 1] [Часть 2] [Часть 3] [Часть 4] [Часть 5] [Часть 6]

Таблицы в VBA Word принадлежат коллекции Tables, которая предусмотрена для объектов Document, Selection и Range. Новая таблица создается с помощью метода Tables.Add.

Синтаксис метода Tables.Add

Expression.Add (Range, Rows, Columns, DefaultTableBehavior, AutoFitBehavior)

Expression – выражение, возвращающее коллекцию Tables.

Параметры метода Tables.Add

  • Range – диапазон, в котором будет создана таблица (обязательный параметр).
  • Rows – количество строк в создаваемой таблице (обязательный параметр).
  • Columns – количество столбцов в создаваемой таблице (обязательный параметр).
  • DefaultTableBehavior – включает и отключает автоподбор ширины ячеек в соответствии с их содержимым (необязательный параметр).
  • AutoFitBehavior – определяет правила автоподбора размера таблицы в документе Word (необязательный параметр).

Создание таблицы в документе

Создание таблицы из 3 строк и 4 столбцов в документе myDocument без содержимого и присвоение ссылки на нее переменной myTable:

With myDocument

Set myTable = .Tables.Add(.Range(Start:=0, End:=0), 3, 4)

End With

Создание таблицы из 5 строк и 4 столбцов в документе Word с содержимым:

With myDocument

myInt = .Range.Characters.Count 1

Set myTable = .Tables.Add(.Range(Start:=myInt, End:=myInt), 5, 4)

End With

Для указания точки вставки таблицы присваиваем числовой переменной количество символов в документе минус один. Вычитаем единицу, чтобы исключить из подсчета последний знак завершения абзаца (¶), так как точка вставки не может располагаться за ним.

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

При создании, каждой новой таблице в документе присваивается индекс, по которому к ней можно обращаться:

myDocument.Tables(индекс)

Нумерация индексов начинается с единицы.

Отображение границ таблицы

Новая таблица в документе Word из кода VBA Excel создается без границ. Отобразить их можно несколькими способами:

Вариант 1
Присвоение таблице стиля, отображающего все границы:

myTable.Style = «Сетка таблицы»

Вариант 2
Отображение внешних и внутренних границ в таблице:

With myTable

.Borders.OutsideLineStyle = wdLineStyleSingle

.Borders.InsideLineStyle = wdLineStyleSingle

End With

Вариант 3
Отображение всех границ в таблице по отдельности:

With myTable

.Borders(wdBorderHorizontal) = True

.Borders(wdBorderVertical) = True

.Borders(wdBorderTop) = True

.Borders(wdBorderLeft) = True

.Borders(wdBorderRight) = True

.Borders(wdBorderBottom) = True

End With

Присвоение таблицам стилей

Вариант 1

myTable.Style = «Таблица простая 5»

Чтобы узнать название нужного стиля, в списке стилей конструктора таблиц наведите на него указатель мыши. Название отобразится в подсказке. Кроме того, можно записать макрос с присвоением таблице стиля и взять название из него.

Вариант 2

myTable.AutoFormat wdTableFormatClassic1

Выбирайте нужную константу с помощью листа подсказок свойств и методов – Auto List Members.

Обращение к ячейкам таблицы

Обращение к ячейкам второй таблицы myTable2 в документе myDocument по индексам строк и столбцов:

myTable2.Cell(nRow, nColumn)

myDocument.Tables(2).Cell(nRow, nColumn)

  • nRow – номер строки;
  • nColumn – номер столбца.

Обращение к ячейкам таблицы myTable в документе Word с помощью свойства Cell объектов Row и Column и запись в них текста:

myTable.Rows(2).Cells(2).Range = _

«Содержимое ячейки во 2 строке 2 столбца»

myTable.Columns(3).Cells(1).Range = _

«Содержимое ячейки в 1 строке 3 столбца»

В таблице myTable должно быть как минимум 2 строки и 3 столбца.

Примеры создания таблиц Word

Пример 1
Создание таблицы в новом документе Word со сплошными наружными границами и пунктирными внутри:

Sub Primer1()

Dim myWord As New Word.Application, _

myDocument As Word.Document, myTable As Word.Table

  Set myDocument = myWord.Documents.Add

  myWord.Visible = True

With myDocument

  Set myTable = .Tables.Add(.Range(0, 0), 5, 4)

End With

With myTable

  .Borders.OutsideLineStyle = wdLineStyleSingle

  .Borders.InsideLineStyle = wdLineStyleDot

End With

End Sub

В выражении myDocument.Range(Start:=0, End:=0) ключевые слова Start и End можно не указывать – myDocument.Range(0, 0).

Пример 2
Создание таблицы под ранее вставленным заголовком, заполнение ячеек таблицы и применение автосуммы:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

Sub Primer2()

On Error GoTo Instr

Dim myWord As New Word.Application, _

myDocument As Word.Document, _

myTable As Word.Table, myInt As Integer

  Set myDocument = myWord.Documents.Add

  myWord.Visible = True

With myDocument

‘Вставляем заголовок таблицы

  .Range.InsertAfter «Продажи фруктов в 2019 году» & vbCr

  myInt = .Range.Characters.Count 1

‘Присваиваем заголовку стиль

  .Range(0, myInt).Style = «Заголовок 1»

‘Создаем таблицу

  Set myTable = .Tables.Add(.Range(myInt, myInt), 4, 4)

End With

With myTable

‘Отображаем сетку таблицы

  .Borders.OutsideLineStyle = wdLineStyleSingle

  .Borders.InsideLineStyle = wdLineStyleSingle

‘Форматируем первую и четвертую строки

  .Rows(1).Range.Bold = True

  .Rows(4).Range.Bold = True

‘Заполняем первый столбец

  .Columns(1).Cells(1).Range = «Наименование»

  .Columns(1).Cells(2).Range = «1 квартал»

  .Columns(1).Cells(3).Range = «2 квартал»

  .Columns(1).Cells(4).Range = «Итого»

‘Заполняем второй столбец

  .Columns(2).Cells(1).Range = «Бананы»

  .Columns(2).Cells(2).Range = «550»

  .Columns(2).Cells(3).Range = «490»

  .Columns(2).Cells(4).AutoSum

‘Заполняем третий столбец

  .Columns(3).Cells(1).Range = «Лимоны»

  .Columns(3).Cells(2).Range = «280»

  .Columns(3).Cells(3).Range = «310»

  .Columns(3).Cells(4).AutoSum

‘Заполняем четвертый столбец

  .Columns(4).Cells(1).Range = «Яблоки»

  .Columns(4).Cells(2).Range = «630»

  .Columns(4).Cells(3).Range = «620»

  .Columns(4).Cells(4).AutoSum

End With

‘Освобождаем переменные

Set myDocument = Nothing

Set myWord = Nothing

‘Завершаем процедуру

Exit Sub

‘Обработка ошибок

Instr:

If Err.Description <> «» Then

  MsgBox «Произошла ошибка: « & Err.Description

End If

If Not myWord Is Nothing Then

  myWord.Quit

  Set myDocument = Nothing

  Set myWord = Nothing

End If

End Sub

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

Чтобы просуммировать значения в строке слева от ячейки с суммой, используйте метод Formula объекта Cell:

myTable.Cell(2, 4).Formula («=SUM(LEFT)»)

Другие значения метода Formula, применяемые для суммирования значений ячеек:

  • «=SUM(ABOVE)» – сумма значений над ячейкой (аналог метода AutoSum);
  • «=SUM(BELOW)» – сумма значений под ячейкой;
  • «=SUM(RIGHT)» – сумма значений справа от ячейки.


Add Table to Word Document

This simple macro will add a table to your Word document:

Sub VerySimpleTableAdd()
    Dim oTable As Table
    Set oTable = ActiveDocument.Tables.Add(Range:=Selection.Range, NumRows:=3, NumColumns:=3)
End Sub

Select Table in Word

This macro will select the first table in the active Word document:

Sub SelectTable()
'selects first table in active doc
    If ActiveDocument.Tables.Count > 0 Then    'to avoid errors we check if any table exists in active doc
        ActiveDocument.Tables(1).Select
    End If
End Sub

Loop Through all Cells in a Table

This VBA macro will loop through all cells in a table, writing the cell count to the cell:

Sub TableCycling()
' loop through all cells in table
    Dim nCounter As Long    ' this will be writen in all table cells
    Dim oTable As Table
    Dim oRow As Row
    Dim oCell As Cell

    ActiveDocument.Range.InsertParagraphAfter    'just makes new para athe end of doc, Table will be created here
    Set oTable = ActiveDocument.Tables.Add(Range:=ActiveDocument.Paragraphs.Last.Range, NumRows:=3, NumColumns:=3)    'create table and asign it to variable
    For Each oRow In oTable.Rows    ' outher loop goes through rows
        For Each oCell In oRow.Cells    'inner loop goes
            nCounter = nCounter + 1    'increases the counter
            oCell.Range.Text = nCounter    'writes counter to the cell
        Next oCell
    Next oRow

    'display result from cell from second column in second row
    Dim strTemp As String
    strTemp = oTable.Cell(2, 2).Range.Text
    MsgBox strTemp
End Sub

Create Word Table From Excel File

This VBA example will make a table from an Excel file:

Sub MakeTablefromExcelFile()
'advanced
    Dim oExcelApp, oExcelWorkbook, oExcelWorksheet, oExcelRange
    Dim nNumOfRows As Long
    Dim nNumOfCols As Long
    Dim strFile As String

    Dim oTable As Table    'word table
    Dim oRow As Row    'word row
    Dim oCell As Cell    'word table cell
    Dim x As Long, y As Long    'counter for loops

    strFile = "c:UsersNenadDesktopBookSample.xlsx"    'change to actual path
    Set oExcelApp = CreateObject("Excel.Application")
    oExcelApp.Visible = True
    Set oExcelWorkbook = oExcelApp.Workbooks.Open(strFile)    'open workbook and asign it to variable
    Set oExcelWorksheet = oExcelWorkbook.Worksheets(1)    'asign first worksheet to variable
    Set oExcelRange = oExcelWorksheet.Range("A1:C8")
    nNumOfRows = oExcelRange.Rows.Count
    nNumOfCols = oExcelRange.Columns.Count

    ActiveDocument.Range.InsertParagraphAfter    'just makes new para athe end of doc, Table will be created here
    Set oTable = ActiveDocument.Tables.Add(Range:=ActiveDocument.Paragraphs.Last.Range, NumRows:=nNumOfRows, NumColumns:=nNumOfCols)    'create table and asign it to variable
    '***real deal, table gets filled here
    For x = 1 To nNumOfRows
        For y = 1 To nNumOfCols
            oTable.Cell(x, y).Range.Text = oExcelRange.Cells(x, y).Value
        Next y
    Next x
    '***
    oExcelWorkbook.Close False
    oExcelApp.Quit
    With oTable.Rows(1).Range    'we can now apply some beautiness to our table :)
        .Shading.Texture = wdTextureNone
        .Shading.ForegroundPatternColor = wdColorAutomatic
        .Shading.BackgroundPatternColor = wdColorYellow
    End With
End Sub

Всем привет, с вами автор блога 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.

Понравилась статья? Поделить с друзьями:
  • Vba word selection find if not found
  • Vba word его объекты
  • Vba word selection find execute
  • Vba word добавить страницу
  • Vba word select words