Select number vba word

I’m using a VBA script to try to find the starting number of a paragraph (they are list items not formatted as such — not trying to format, just find the numbers).

1. First Item
2. Second Item
No number - don't include despite 61.5 in paragraph.
25 elephants should not be included
12. Item Twelve, but don't duplicate because of Susie's 35 items

Is there any way to say in VBA «If start of paragraph has 1-2 numbers, return those numbers». In regex, what I’m looking for is ^(d+).

Here is a working bit of VBA code — haven’t figured out how to CREATE the excel file yet, so if you go to test create a blank test.xslx in your temp folder. Of course this may be simple enough that testing isn’t necessary.

Sub FindWordCopySentence()
On Error Resume Next
Dim appExcel As Object
Dim objSheet As Object
Dim aRange As Range
Dim intRowCount As Integer
intRowCount = 1

' Open Excel File
If objSheet Is Nothing Then
    Set appExcel = CreateObject("Excel.Application")
     'Change the file path to match the location of your test.xls
    Set objSheet = appExcel.workbooks.Open("C:temptest.xlsx").Sheets("Sheet1")
    intRowCount = 1
End If

' Word Document Find
Set aRange = ActiveDocument.Range
With aRange.Find
    Do
        .ClearFormatting
        ' Find 1-2 digit number
        .Text = "[0-9]{1,2}"
        .MatchWildcards = True
        .Execute
        If .Found Then
            ' Copy to Excel file
            aRange.Expand Unit:=wdSentence
            aRange.Copy
            aRange.Collapse wdCollapseEnd
            objSheet.Cells(intRowCount, 1).Select
            objSheet.Paste
            intRowCount = intRowCount + 1
        End If
    Loop While .Found
End With
Set aRange = Nothing

If Not objSheet Is Nothing Then
    appExcel.workbooks(1).Close True
    appExcel.Quit
    Set objSheet = Nothing
    Set appExcel = Nothing
End If

End Sub

Thanks!

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

If You want to learn how to find a word or phrase in Word file and get its paragraph or word number stay here, You’ve come to the right place!

Find word and get its paragraph number from Word file

Some time ago I wrote about finding phrase in Word or .pdf files, but now we want something more…

Long story short

Recently, I got inspired by topic from StackOverflow, much about finding a word position in the Word file. When I saw this, I wanted to try my skills and create a tool, which finds a word or whole phrase in the Word file and returns its position – number of paragraph or word.

Background

To get things more complicated and be consistent with my website name I wanted to create it in Excel.

Imagine, that in column “A” You store the words, in column “B” locations of Word files You want to search for and in column “C” macro returns words position.

First things first

At the beginning we need to declare variables, which will stand for Word variables: Word application, Word document and Word document ranges.

Dim wd As Word.Application
Dim wdDoc As Word.Document
Dim rng As Word.Range, rng2 As Word.Range, rParagraphs As Word.Range

Get the search info

After all needed declarations let’s get search phrase srcwd and Word file localization wdfile.

Dim txt As String, wdfile As String, srcwd As String
Dim CurPos As Long, GetParNum As Long

wdfile = ThisWorkbook.Sheets(1).Range("B1")
srcwd = ThisWorkbook.Sheets(1).Range("A1")

Create Word objects

To open Word file from Excel, You need to create Word application object and set its document to next variable.

Set wd = CreateObject("Word.Application")
Set wdDoc = wd.Documents.Open(wdfile)

Assign content

Later on set all Word file content range to rng.

Set rng = wdDoc.Content

Text of this document can be taken out from this range variable.

We got opened target Word file and all of its text assigned to variable. Now we can start to seek for chosen phrase and get its paragraph or word number. To do it we will use function .Find

With rng.Find
    .Text = srcwd
    .Forward = True
    .Execute
End With

This will find and select the next occurrence (.Forward = True) of the searched word (srcwd).

Remember about the .Execute, because without it won’t work at all, regardless of parameters number!

Get paragraph number

Finally, we can get the paragraph or word number!

First, we need to set the cursor in the end of the found word. In other case macro will not count the paragraph, which the word is in it!

CurPos = rng.Words(1).End

Next let’s set the range from the beginning of the document to the position of cursor.

Set rParagraphs = wdDoc.Range(Start:=0, End:=CurPos)

Thanks to that we got range containing everything up to searched word and now all we have to do is count the number of paragraphs!

GetParNum = rParagraphs.Paragraphs.Count

If You want to know what is its word number just change Paragraphs to Words.

GetWordsNum = rParagraphs.Words.Count

Whole code

There is one matter left to do in the end of our code. We have to save somewhere the paragraph number. Let’s write it down to the column C, after that close the document with no changes and quit Word application (see end of below code).

Option Explicit

Sub src4Word()

Dim wd As Word.Application
Dim wdDoc As Word.Document
Dim rng As Word.Range, rng2 As Word.Range
Dim rParagraphs As Word.Range
Dim txt As String, wdfile As String, srcwd As String
Dim CurPos As Long, GetParNum As Long

wdfile = ThisWorkbook.Sheets(1).Range("B1")
srcwd = ThisWorkbook.Sheets(1).Range("A1")

Set wd = CreateObject("Word.Application")
Set wdDoc = wd.Documents.Open(wdfile)
Set rng = wdDoc.Content

With rng.Find
    .Text = srcwd
    .Forward = True
    .Execute
End With

CurPos = rng.Words(1).End
Set rParagraphs = wdDoc.Range(Start:=0, End:=CurPos)
GetParNum = rParagraphs.Paragraphs.Count

ThisWorkbook.Sheets(1).Range("C1") = GetParNum
wdDoc.Close 0
wd.Quit

End Sub

Summary

Now You know how to find a word or phrase in Word file and get its paragraph or even its word number! It looks so easy! You can use this code to the other variations, for example to get whole text of the searched word paragraph. The choice is yours!

I’m very advanced in VBA, Excel, also easily linking VBA with other Office applications (e.g. PowerPoint) and external applications (e.g. SAP). I take part also in RPA processes (WebQuery, DataCache, IBM Access Client Solutions) where I can also use my SQL basic skillset. I’m trying now to widen my knowledge into TypeScript/JavaScript direction.
View all posts by Tomasz Płociński

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 PDF (бесплатные загрузки)
  • Примеры Word VBA «Шпаргалка»
  • Учебное пособие по макросам Word VBA
  • Пример простого макроса Word
  • Объект документа Word
  • Документы
  • Диапазон, выделение, абзацы
  • Примеры макросов Word

Добро пожаловать в наше мега-руководство по Word VBA / макросам!

Эта страница содержит:

    1. Учебное пособие по Word VBA в формате PDF (бесплатная загрузка)
    2. Word VBA «Шпаргалка», содержащая список наиболее часто используемых фрагментов кода Word VBA.
    3. Полное руководство по Word VBA / Macro.
    4. Список всех наших руководств по макросам Word VBA с возможностью поиска

Возможно, вас заинтересует наше интерактивное руководство по VBA для Excel. Хотя некоторые из примеров / упражнений относятся к Excel VBA, большая часть содержимого является общим для всех VBA, и вам может быть полезно изучить такие концепции, как If, Loops, MessageBoxes и т. Д.

VBA PDF (бесплатные загрузки)

Загрузите наше бесплатное руководство по Microsoft Word VBA! Или учебники VBA для других программ Office!

Скачать

Ниже вы найдете простые примеры кода VBA для работы с Microsoft Word.

Выбрать / перейти к

ОписаниеКод VBABackspaceSelection.TypeBackspaceВыбрать весь документSelection.HomeKey Unit: = wdStory
Selection.ExtendКопироватьSelection.CopyУдалитьSelection.Delete Unit: = wdCharacter, Count: = 1Вставить послеSelection.InsertAfter «текст»Начало строкиSelection.HomeKey Unit: = wdLineКонец линииSelection.EndKey Unit: = wdLineВставитьSelection.PasteВыбрать всеSelection.WholeStoryВыбрать всю строкуSelection.EndKey Unit: = wdLine, Extend: = wdExtendВверх по абзацуSelection.MoveUp Unit: = wdParagraph, Count: = 1Переместить вправо на один символSelection.MoveRight Unit: = wdCharacter, Count: = 1Переместить вправо на одну ячейку в таблицеSelection.MoveRight Unit: = wdCellПерейти к началу документаSelection.HomeKey Unit: = wdStoryПерейти в конец документаSelection.EndKey Unit: = wdStoryПерейти на страницу 1Selection.GoTo What: = wdGoToPage, Which: = wdGoToNext, Name: = ”1 ″Перейти к началу страницыSelection.GoTo What: = wdGoToBookmark, Name: = ” Page”
Selection.MoveLeft Unit: = wdCharacter, Count: = 1

Return to Top

Закладки

ОписаниеКод VBAДобавлятьС ActiveDocument.Bookmarks
.Add Range: = Selection.Range, Name: = «Name».
.DefaultSorting = wdSortByName
.ShowHidden = Ложь
Конец сСчитатьDim n as Integer
n = ActiveDocument.Bookmarks.CountУдалитьActiveDocument.Bookmarks («Имя закладки»). УдалитьСуществуют?Если ActiveDocument.Bookmarks.Exists («BookmarkName») = True, то
‘Сделай что-нибудь
Конец, еслиПерейти кSelection.GoTo What: = wdGoToBookmark, Name: = ”BookmarkName”ВыбиратьActiveDocument.Bookmarks («Имя закладки»). ВыберитеЗаменить текстSelection.GoTo What: = wdGoToBookmark, Name: = ”BookmarkName”
Selection.Delete Unit: = wdCharacter, Count: = 1
Selection.InsertAfter «Новый текст»
ActiveDocument.Bookmarks.Add Range: = Selection.Range, _
Name: = ”BookmarkName”

Return to Top

Документ

ОписаниеКод VBAАктивироватьДокументы («Example.doc»). АктивироватьДобавить в переменнуюDim doc As Document
Установить doc = Documents.AddДобавлятьDocuments.AddДобавить (из другого документа)Documents.Add Template: = ”C: Forms FormDoc.doc”, _
NewTemplate: = FalseЗакрыватьДокументы («Example.doc»). ЗакрытьЗакрыть — сохранить измененияДокументы («Example.doc»). Закройте SaveChanges: = wdSaveChangesЗакрыть — не сохранятьДокументы («Example.doc»). Закройте SaveChanges: = wdDoNotSaveChanges.Закрыть — запрос на сохранениеДокументы («Example.doc»). Закройте SaveChanges: = wdPromptToSaveChanges.

Return to Top

Столбцы

ОписаниеКод VBAСохранить какДокументы («Example.doc»). SaveAs («C: Example Example.doc»)СохранитьДокументы («Example.doc»). СохранитьЗащищатьДокументы («Example.doc»). Защитить пароль: = «пароль»Снять защитуДокументы («Example.doc»). Снять пароль: = «пароль»Число страницDim varNumberPages как вариант
varNumberPages = _
ActiveDocument.Content.Information (wdActiveEndAdjustedPageNumber)РаспечататьДокументы («Example.doc»). Распечатать

Return to Top

Устали искать примеры кода VBA? Попробуйте AutoMacro!

Шрифт

ОписаниеКод VBAРазмерSelection.Font.Size = 12ЖирныйSelection.Font.Bold = TrueКурсивSelection.Font.Italic = TrueПодчеркиваниеSelection.Font.Underline = wdUnderlineSingleВсе заглавные буквыSelection.Font.AllCaps = TrueЦветSelection.Font.TextColor = vbRedИмяSelection.Font.Name = «Абади»Нижний индексSelection.Font.Subscript = TrueSuperScriptSelection.Font.Superscript = TrueЦвет выделенияSelection.Range.HighlightColorIndex = wdYellowСтильSelection.Style = ActiveDocument.Styles («Нормальный»)

Return to Top

Вставлять

ОписаниеКод VBAВставить автотекстSelection.TypeText Текст: = ”a3 ″
Selection.Range.InsertAutoTextВставить код датыВставить файлSelection.InsertFile («C: Docs Something.doc»)Вставить разрыв страницыSelection.InsertBreak Тип: = wdPageBreakВставить символ абзацаSelection.TypeText Text: = Chr $ (182)Вставить вкладкуSelection.TypeText Текст: = vbTabВставить текстSelection.TypeText Text: = «Любой текст»Вставить абзац типаSelection.TypeParagraphВставить абзацSelection.InsertParagraph

Return to Top

Петли

ОписаниеКод VBAСделать до конца документаСделать до ActiveDocument.Bookmarks (« Sel») = ActiveDocument.Bookmarks (« EndOfDoc»)
‘Сделай что-нибудь
SubДля каждого документа в ДокументахDim doc As Document
Для каждого документа в документах
‘Сделай что-нибудь
Следующий документЦикл по абзацамПодпункты через абзацы
Dim i As Long, iParCount As Long
iParCount = ActiveDocument.Paragraphs.CountFori = 1 На iParCount
ActiveDocument.Paragraphs (i) .Alignment = wdAlignParagraphLeft
Далее я

Return to Top

Пункт

ОписаниеКод VBAKeepLinesTogetherSelection.ParagraphFormat.KeepTogether = TrueKeepWithNextSelection.ParagraphFormat.KeepWithNext = ИстинаПробел послеSelection.ParagraphFormat.SpaceAfter = 12Пространство доSelection.ParagraphFormat.SpaceBefore = 0Выровнять по центруSelection.ParagraphFormat.Alignment = wdAlignParagraphCenterВыровнять по правому краюSelection.ParagraphFormat.Alignment = wdAlignParagraphRightВыровнять по левому краюSelection.ParagraphFormat.Alignment = wdAlignParagraphLeftЛевый отступSelection.ParagraphFormat.LeftIndent = InchesToPoints (3,75)Правый отступSelection.ParagraphFormat.RightIndent = InchesToPoints (1)Межстрочный интервалС Selection.ParagraphFormat
.LineSpacingRule = wdLineSpaceExactly
.LineSpacing = 12
Конец сПеребрать все абзацыПодпункты через абзацы
Dim i As Long, iParCount As Long
iParCount = ActiveDocument.Paragraphs.CountFori = 1 На iParCount
ActiveDocument.Paragraphs (i) .Alignment = wdAlignParagraphLeft
Далее я

Return to Top

Учебное пособие по макросам Word VBA

Это руководство по использованию VBA с Microsoft Word. Это руководство научит вас писать простой макрос и взаимодействовать с документами, диапазонами, выделениями и абзацами.

Примечание. Если вы новичок в Macros / VBA, вам также может быть полезна эта статья: Как писать макросы VBA с нуля.

VBA — это язык программирования, используемый для автоматизации программ Microsoft Office, включая Word, Excel, Outlook, PowerPoint и Access.

Макросы представляют собой блоки кода VBA, которые выполняют определенные задачи.

Когда ты Записать макрос, Word запишет код VBA в макрос, что позволит вам повторять ваши действия. Вы можете увидеть список всех доступных макросов из Просмотр> Макросы.

После записи макроса вы сможете редактировать макрос из списка макросов:

Когда вы нажимаете Редактировать, вы открываете Редактор VBA. Используя редактор VBA, вы можете редактировать записанные макросы или писать макрос Word с нуля. Для доступа к редактору VBA используйте ярлык ALT + F11 или щелкните Visual Basic от Лента разработчика.

Пример простого макроса Word

Это простой пример макроса Word VBA. Он выполняет следующие задачи:

  • Открывает документ Word
  • Записывает в документ
  • Закрывает и сохраняет документ Word.
123456789101112131415 Sub WordMacroExample ()’Открыть документ и назначить переменнойDim oDoc как документУстановите oDoc = Documents.Open («c: Users something NewDocument.docx»).’Написать в документSelection.TypeText «www.automateexcel.com»Selection.TypeParagraph’Сохранить и закрыть документoDoc.SaveoDoc.CloseКонец подписки

Основы работы с макросами Word

Весь код VBA должен храниться в подобных процедурах. Чтобы создать процедуру в VBA, введите «Sub WordMacroExample» (где «WordMacroExample» — желаемое имя макроса) и нажмите ВХОДИТЬ. VBA автоматически добавит круглые скобки и End Sub.

Объект документа Word

При взаимодействии с Microsoft Word в VBA вы часто будете ссылаться на Word «Объекты». Наиболее распространенные объекты:

Объект приложения — сам Microsoft Word

Объект документа — документ Word

Объект диапазона — Часть документа Word

Объект выделения — Выбранный диапазон или положение курсора.

заявка

Приложение — это объект «верхнего уровня». Через него можно получить доступ ко всем остальным объектам Word.

Помимо доступа к другим объектам Word, можно применить настройки «уровня приложения»:

1 Application.Options.AllowDragAndDrop = True

Это пример доступа к «Выборке» в «Windows (1)» в Приложении:

1 Application.Windows (1) .Selection.Characters.Count

Однако к наиболее распространенным объектам Word можно получить доступ напрямую, без ввода полной иерархии. Поэтому вместо этого вы можете (и должны) просто ввести:

1 Selection.Characters.Count

Документы

ActiveDocument

Часто у вас есть два или более документов, открытых в Word, и вам нужно указать, с каким конкретным документом Word следует взаимодействовать. Один из способов указать, какой документ использовать ActiveDocument. Например:

1 ActiveDocument.PrintOut

… Напечатал бы ActiveDocument. ActiveDocument — это документ в Word, который «имеет фокус»

Чтобы переключить ActiveDocument, используйте команду Activate:

1 Документы («Example.docx»). Активировать

Этот документ

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

Переменные документа

Однако для более сложных макросов может быть сложно отслеживать активный документ. Также может быть неприятно переключаться между документами.

Вместо этого вы можете использовать переменные документа.

Этот макрос назначит ActiveDocument переменной, а затем распечатает документ, используя переменную:

12345 Sub VarExample ()Dim oDoc как документУстановите oDoc = ActiveDocumentoDoc.PrintOutКонец подписки

Документ Методы

Открыть документ

Чтобы открыть документ Word:

1 Documents.Open «c: Users SomeOne Desktop Test PM.docx»

Мы рекомендуем всегда назначать документ переменной при его открытии:

12 Dim oDoc как документУстановите oDoc = Documents.Open («c: Users SomeOne Desktop Test PM.docx»).

Создать новый документ

Чтобы создать новый документ Word:

Мы можем указать Word создать новый документ на основе некоторого шаблона:

1 Documents.Add Template: = «C: Program Files Microsoft Office Templates MyTemplate.dotx»

Как всегда, присвоение документа переменной при создании или открытии помогает избавить от серьезных проблем:

12 Dim oDoc как документУстановите oDoc = Documents.Add (Template: = «C: Program Files Microsoft Office Templates MyTemplate.dotx»)

Сохранить документ

Чтобы сохранить документ:

или Сохранить как:

1 ActiveDocument.SaveAs FileName: = c: Users SomeOne Desktop test2.docx «, FileFormat: = wdFormatDocument

Закрыть документ

Чтобы закрыть документ и сохранить изменения:

1 ActiveDocument.Close wdSaveChanges

или без сохранения изменений:

1 ActiveDocument.Close wdDoNotSaveChanges

Распечатать документ

Это напечатает активный документ:

1 ActiveDocument.PrintOut

Диапазон, выделение, абзацы

Диапазон а также Выбор являются, вероятно, наиболее важными объектами в Word VBA и, безусловно, наиболее часто используемыми.

Диапазон относится к некоторой части документа, обычно, но не обязательно, к тексту.

Выбор относится к выделенному тексту (или другому объекту, например изображениям) или, если ничего не выделено, к точке вставки.

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

Диапазон

Диапазон может быть любой частью документа, включая весь документ:

12 Dim oRange As RangeУстановите oRange = ActiveDocument.Content

или он может быть маленьким, как один символ.

Другой пример, этот диапазон будет относиться к первому слову в документе:

12 Dim oRange As RangeУстановите oRange = ActiveDocument.Range.Words (1)

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

В следующем примере мы выделим первое слово второго абзаца жирным шрифтом:

123 Dim oRange As RangeУстановите oRange = ActiveDocument.Paragraphs (2) .Range.Words (1)oRange.Bold = True

Установить текст диапазона

Чтобы установить текстовое значение диапазона:

123 Dim oRange As RangeУстановите oRange = ActiveDocument.Paragraphs (2) .Range.Words (1)oRange.Text = «Привет»

(Совет: обратите внимание на пробел после «Hello». Поскольку слово «объект» включает пробел после слова, просто «hello» мы получим «Hellonext word»)

С диапазонами можно делать сотни вещей. Всего несколько примеров (предполагается, что вы уже сделали объектную переменную апельсин относится к интересующему диапазону):

Изменить шрифт

1 oRange.Font.Name = «Arial»

Отображение в окне сообщения количества символов в определенном диапазоне

1 MsgBox oRange.Characters.Count

Вставьте текст перед ним

1 oRange.InsertBefore «это вставленный текст»

Добавить сноску к диапазону

12 ActiveDocument.Footnotes.Add Диапазон: = oRange, _Text: = «Подробнее читайте на easyexcel.net.»

Скопируйте в буфер обмена

1234 oRange.CopyЧасто вам нужно перейти к конкретному диапазону. Итак, вы можете начать, начать и закончитьoRange.Start = 5oRange.End = 50

После приведенного выше кода oRange будет относиться к тексту, начинающемуся с пятого и заканчивающемуся 50-м символом в документе.

Выбор

Выбор используется даже шире, чем Диапазон, потому что с ним легче работать Выборы чем Диапазоны, ЕСЛИ ваш макрос взаимодействует ТОЛЬКО с ActiveDocument.

Сначала выберите желаемую часть вашего документа. Например, выберите второй абзац в активном документе:

1 ActiveDocument.Paragraphs (2) .Range.Select

Затем вы можете использовать объект выбора для ввода текста:

1 Selection.TypeText «Какой-то текст»

Мы можем ввести несколько абзацев ниже «Некоторый текст»:

12 Selection.TypeText «Какой-то текст»Selection.TypeParagraph

Часто необходимо знать, выделен ли какой-то текст или у нас есть только точка вставки:

12345 Если Selection.Type wdSelectionIP ТогдаSelection.Font.Bold = TrueЕщеMsgBox «Вам нужно выделить текст».Конец, если

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

Начало документа:

1 Selection.HomeKey Unit: = wdStory, Extend: = wdMove

Начало текущей строки:

1 Selection.HomeKey Unit: = wdLine, Extend: = wdMove

Параметр Extend wdMove перемещает точку вставки. Вместо этого вы можете использовать wdExtend, который выделит весь текст между текущей точкой вставки.

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

Переместить выделение

Самый полезный метод изменения положения точки вставки — «Перемещение». Чтобы переместить выделение на два символа вперед:

1 Selection.Move Unit: = wdCharacter, Count: = 2

чтобы переместить его назад, используйте отрицательное число для параметра Count:

1 Selection.Move Unit: = wdCharacter, Count: = — 2

Параметр единицы измерения может быть wdCharacter, wdWord, wdLine или другим (используйте справку Word VBA, чтобы увидеть другие).

Чтобы вместо этого переместить слова:

1 Selection.Move unit: = wdWord, Count: = 2

С выделением легче работать (по сравнению с диапазонами), потому что он похож на робота, использующего Word, имитирующего человека. Где находится точка вставки — какое-то действие произойдет. Но это означает, что вы должны позаботиться о том, где находится точка вставки! Это непросто после многих шагов в коде. В противном случае Word изменит текст в нежелательном месте.

Если вам нужно какое-то свойство или метод, недоступный в объекте Selection, вы всегда можете легко получить диапазон, связанный с выбором:

1 Установите oRange = Selection.Range.

СОВЕТ: Использование Выбор часто проще, чем использование диапазонов, но также и медленнее (важно, когда вы имеете дело с большими документами)

Абзацы

Вы не можете напрямую использовать объект Paragraphs для изменения текста:

1 ActiveDocument.Paragraphs (1) .Text = «Нет, это не сработает»

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

1 ActiveDocument.Paragraphs (1) .Range.Text = «Теперь работает :)»

Но вы можете напрямую изменить его стиль:

1 ActiveDocument.Paragraphs (1) .Style = «Нормальный»

или измените форматирование на уровне абзаца:

1 ActiveDocument.Paragraphs (1) .LeftIndent = 10

или, может быть, вы хотите сохранить этот абзац на одной строке со следующим абзацем:

1 ActiveDocument.Paragraphs (1) .KeepWithNext = True

Сделайте абзац по центру:

1 ActiveDocument.Paragraphs (1) .Alignment = wdAlignParagraphCenter

ОЧЕНЬ полезно назначить конкретный абзац объектной переменной. Если мы присвоим переменной конкретный абзац, нам не нужно беспокоиться, станет ли первый абзац вторым, потому что мы вставили перед ним один абзац:

12 dim oPara как абзацУстановите oPara = Selection.Paragraphs (1) ‘здесь мы присваиваем первый абзац текущего выделения переменной

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

1234567 Sub ParagraphExample ()Dim oPara как абзацУстановить oPara = ActiveDocument.Paragraphs (1)MsgBox oPara.Range.TextoPara.Range.InsertParagraphBefore ‘Вставить абзацMsgBox oPara.Range.TextКонец подписки

Объект абзаца очень часто используется в циклах:

123456789101112 Sub LoopThroughParagraphs ()Dim oPara как абзацДля каждого параметра в ActiveDocument.Paragraphs«Сделай что-нибудь с этим. Мы просто покажем’текст абзаца, если его стиль — «Заголовок 4″Если oPara.Style = «Заголовок 4», тоMsgBox oPara.Range.TextКонец, еслиДалее oParaКонец подписки

Word VBA Tutorial Заключение

В этом руководстве были рассмотрены основы Word VBA. Если вы новичок в VBA, вам также следует ознакомиться с нашим общим руководством по VBA, чтобы узнать больше о переменных, циклах, окнах сообщений, настройках, условной логике и многом другом.

Примеры макросов Word

Примеры макросов Word
Шаблоны
Добавить новые документы
Подсчет слов в выделенном фрагменте
Текстовые поля
Сохранить как PDF
Закладки
Таблицы
Найти, найти и заменить
Открытые документы

Word VBA: часто задаваемые вопросы

Что такое макрос Word?

Макрос — это общий термин, обозначающий набор инструкций по программированию, которые автоматизируют задачи. Макросы Word автоматизируют задачи в Word с помощью языка программирования VBA.

Есть ли в слове VBA?

Да, в Microsoft Word есть редактор VBA. Доступ к нему можно получить, нажав клавиши ALT + F11 или перейдя в раздел «Разработчик»> «Visual Basic».

Как использовать VBA в Word?

1. Откройте редактор VBA (ALT + F11 или Разработчик> Visual Basic).
2. Выберите «Вставить»> «Модуль», чтобы создать модуль кода.
3. Введите «Sub HelloWorld» и нажмите Enter.
4. Между строками «Sub HelloWorld» и «End Sub» введите «MsgBox« Hello World! »
5. Вы создали макрос!
6. Теперь нажмите «F5», чтобы запустить макрос.

Понравилась статья? Поделить с друзьями:
  • Select line in word
  • Select language in word
  • Select in excel from row
  • Select function in word
  • Select from worksheet in excel