Применение закладок для заполнения различных бланков на основе документов Word из кода VBA Excel. Объект Bookmark и его свойство Range.
Работа с Word из кода VBA Excel
Часть 5. Bookmarks – закладки в документе Word
[Часть 1] [Часть 2] [Часть 3] [Часть 4] [Часть 5] [Часть 6]
Добавление закладок в шаблон
Закладки (Bookmarks) являются удобным средством для вставки изменяющихся реквизитов в шаблоны документов. К закладкам можно обращаться по имени и не заморачиваться подсчетом количества символов до того места, где должен быть вставлен текст.
Вставляются закладки в шаблон документа вручную. Например, для следующего шаблона
Шаблон договора аренды с закладками
это можно сделать так:
- Вставляем в макет шаблона в места вставки изменяемых реквизитов поясняющий текст. В нашем шаблоне это – <Город>, <Дата>, <Наименование арендатора> и <Наименование арендодателя>. Реквизиты <Город> и <Дата> добавлены в ячейки таблицы, чтобы их можно было разместить в одной строке, а выровнять по разным краям. Границы ячеек оставлены для наглядности.
- Выделяем текст <Город> и вставляем закладку под именем Bookmark1 через меню: Вставка ⇒ Закладка. Добавляем остальные закладки: <Дата> – Bookmark2, <Наименование арендатора> – Bookmark3, <Наименование арендодателя> – Bookmark4.
- Сохраняем бланк документа как шаблон Word. Полный путь для нашего примера: «C:ТестоваяДокумент1.dotx».
Создание и заполнение бланка
Реквизиты, добавляемые в места вставки, отмеченные закладками, обычно хранятся в таблицах Excel. Но мы вставим их напрямую в код процедуры:
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 |
Sub Primer() On Error GoTo Instr Dim myWord As New Word.Application, myDocument As Word.Document ‘Создаем новый документ по шаблону Set myDocument = myWord.Documents.Add(«C:ТестоваяДокумент1.dotx») myWord.Visible = True With myDocument ‘Замещаем текст закладок .Bookmarks(«Bookmark1»).Range = «г. Омск» .Bookmarks(«Bookmark2»).Range = Format(Now, «DD.MM.YYYY») .Bookmarks(«Bookmark3»).Range = «Каев Кай Гердович (ИП)» .Bookmarks(«Bookmark4»).Range = «ООО «Снежная королева»» ‘Удаляем границы ячеек .Tables(1).Borders.OutsideLineStyle = wdLineStyleNone .Tables(1).Borders.InsideLineStyle = wdLineStyleNone 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 |
В результате работы кода VBA Excel получаем заполненный бланк документа на основе шаблона Word:
Заполненный бланк договора аренды
Add Bookmark
This Word macro will add a bookmark:
Sub AddBookmark()
ActiveDocument.Bookmarks.Add "automateexcel_com_01"
End Sub
Delete Bookmark
This VBA macro will delete a bookmark:
Sub DeleteBookmark()
If ActiveDocument.Bookmarks.Exists("automateexcel_com_01") Then 'we need to check if bookmark named "automateexcel_com_01" exists in active doc
ActiveDocument.Bookmarks(Index:="automateexcel_com_01").Delete
End If
End Sub
Go To Bookmark
This simple macro will go to a bookmark:
Sub GoToBookmark()
If ActiveDocument.Bookmarks.Exists("automateexcel_com_01") Then 'we need to check if bookmark named "automateexcel_com_01" exists in active doc
Selection.GoTo What:=wdGoToBookmark, Name:="automateexcel_com_01"
End If
End Sub
Modify Bookmark
This macro will modify a bookmark’s content:
Sub ModifyBookmarkContent()
' change bookmark contents
' more complicated, because changing bookmark range content will delete bookmark
Dim oRangeBKM As Range
If ActiveDocument.Bookmarks.Exists("automateexcel_com_01") Then 'we need to check if bookmark named "automateexcel_com_01" exists in active doc
'Identify current Bookmark range and insert text
Set oRangeBKM = ActiveDocument.Bookmarks("automateexcel_com_01").Range
oRangeBKM.Text = "automateexcel.com"
'Make again the bookmark
ActiveDocument.Bookmarks.Add "automateexcel_com_01", oRangeBKM
End If
End Sub
This is a modify bookmark function:
Sub UpdateBookmarkContent(strBookMarkName As String, strNewText As String)
' "usable' procedure for add in
Dim oRangeBKM As Range
If ActiveDocument.Bookmarks.Exists(strBookMarkName) Then 'we need to check if bookmark named "automateexcel_com_01" exists in active doc
'Identify current Bookmark range and insert text
Set oRangeBKM = ActiveDocument.Bookmarks(strBookMarkName).Range
oRangeBKM.Text = strNewText
'Make again the bookmark
ActiveDocument.Bookmarks.Add strBookMarkName, oRangeBKM
End If
End Sub
You can call the function by adding the bookmark name and new text as arguments:
Sub CallBookmarkFunction()
Call UpdateBookmarkContent("automateexcel_com_01", "automateexcel.com")
End Sub
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Bookmark object (Word) |
vbawd10.chm2408 |
vbawd10.chm2408 |
word |
Word.Bookmark |
be6b0c7b-60ca-97e7-ef19-6de335da3197 |
06/08/2017 |
medium |
Bookmark object (Word)
Represents a single bookmark in a document, selection, or range. The Bookmark object is a member of the Bookmarks collection. The Bookmarks collection includes all the bookmarks listed in the Bookmark dialog box (Insert menu).
Remarks
Using the Bookmark Object
Use Bookmarks (index), where index is the bookmark name or index number, to return a single Bookmark object. You must exactly match the spelling (but not necessarily the capitalization) of the bookmark name. The following example selects the bookmark named «temp» in the active document.
ActiveDocument.Bookmarks("temp").Select
The index number represents the position of the bookmark in the Selection or Range object. For the Document object, the index number represents the position of the bookmark in the alphabetical list of bookmarks in the Bookmarks dialog box (click Name to sort the list of bookmarks alphabetically). The following example displays the name of the second bookmark in the Bookmarks collection.
MsgBox ActiveDocument.Bookmarks(2).Name
Use the Add method to add a bookmark to a document range. The following example marks the selection by adding a bookmark named «temp.»
ActiveDocument.Bookmarks.Add Name:="temp", Range:=Selection.Range
Remarks
Use the BookmarkID property with a range or selection object to return the index number of a Bookmark object in the Bookmarks collection. The following example displays the index number of the bookmark named «temp» in the active document.
MsgBox ActiveDocument.Bookmarks("temp").Range.BookmarkID
Use predefined bookmarkswith the Bookmarks property. The following example sets the bookmark named «currpara» to the location marked by the predefined bookmark named «Para».
ActiveDocument.Bookmarks("Para").Copy "currpara"
Use the Exists method to determine whether a bookmark already exists in the selection, range, or document. The following example ensures that the bookmark named «temp» exists in the active document before selecting the bookmark.
If ActiveDocument.Bookmarks.Exists("temp") = True Then ActiveDocument.Bookmarks("temp").Select End If
Methods
- Copy
- Delete
- Select
Properties
- Application
- Column
- Creator
- Empty
- End
- Name
- Parent
- Range
- Start
- StoryType
See also
- Word Object Model Reference
[!includeSupport and feedback]
Bookmark
Represents position of selection in word document. Bookmark can be compared like Excel Named Range object. Bookmark is very useful object while automating word document using VBA (Visual Basic for Application). Microsoft offers Bookmarks collection by which we can iterate all available bookmarks within a document. The Bookmarks collection can be iterated using index (representing an integer) or bookmark name (representing a string name).
Create book mark Video
Add/Insert
To insert a bookmark in a document manually following steps can be performed:
Step 1: Point location where you wish to insert a bookmark
Step 2: Click on Bookmark command available on Insert Tab
Step 3: n the dialog, write name that you wish to have and click on Add
That’s it, your bookmark is inserted in the document and pointing to the selected location while adding it.
Add() method
Bookmarks collection object offers Add method to add bookmark in selected location or range.
Syntax
Bookmarks.Add(Name as String,[Range])
Name is a string where you need to specify name of the bookmark and Range is an optional argument.
Code example
Public Sub InsertBookmark() 'Declare range variable Dim oRange As Range 'Get current selection reference Set oRange = Selection.Range 'Insert a bookmark oRange.Bookmarks.Add "VBAOVERALL" End Sub
Output
Exists() method
This method helps user to check if a bookmark exists in the document/range/selection or not.
Code example
Public Sub BookmarkExists() 'Declare document variable Dim oDocument As Document 'Get current document reference Set oDocument = ActiveDocument 'Check if bookmark exists If oDocument.Bookmarks.Exists("VBAOVERALL") = True Then MsgBox "VBAOVERALL bookmark exists" Else MsgBox "Sorry!!! bookmark does not exist" End If End Sub
Output
Delete() method
This method ensures deleting your existing bookmark in a range/document/selection.
Code example
Public Sub DeleteBookmark() 'Declare range variable Dim oDocument As Document 'Get current selection reference Set oDocument = ActiveDocument 'Check if bookmark exists If oDocument.Bookmarks.Exists("VBAOVERALL") = True Then 'Delete bookmark oDocument.Bookmarks("VBAOVERALL").Delete Else MsgBox "Sorry!!! bookmark does not exist" End If End Sub
Count property
Provides number of bookmarks available in given document/selection/range.
Code example
Public Sub CountBookmarks() Dim i As Integer For i = 1 To i <= ActiveDocument.Bookmarks.Count Debug.Print ActiveDocument.Bookmarks(i).Name Next i End Sub
Above example prints all bookmarks name available in the given document in Immediate Window.
Name property
It returns name of the bookmark by identifying ID
BookmarkID property
BookmarkID property with a range or selection object to return the index number of a Bookmark object in the Bookmarks collection. The following example displays the index number of the bookmark named “temp” in the active document.
Code example
ActiveDocument.Bookmarks("VBAOVERALL").Range.BookmarkID
Copy() method
You can use predefined bookmarks with the Bookmark property. The following example sets the bookmark named “VBAOVERALL” to the location marked by the predefined bookmark named “Info”.
Code example
ActiveDocument.Bookmarks("VBAOVERALL").Copy "Info"
Select() method
This method is responsible to select a bookmark in given selection/range/document.
Code example
ActiveDocument.Bookmarks("VBAOVERALL").Select
Next>>Style Object Word VBA
title | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|
Bookmarks object (Word) |
word |
827bed64-3034-0eb4-401d-f117cdb98898 |
06/08/2017 |
medium |
Bookmarks object (Word)
A collection of Bookmark objects that represent the bookmarks in the specified selection, range, or document.
Remarks
Use the Bookmarks property to return the Bookmarks collection for a document, range, or selection. The following example ensures that the bookmark named «temp» exists in the active document before selecting the bookmark.
If ActiveDocument.Bookmarks.Exists("temp") = True Then ActiveDocument.Bookmarks("temp").Select End If
Use the Add method to set a bookmark for a range in a document. The following example marks the selection by adding a bookmark named «temp».
ActiveDocument.Bookmarks.Add Name:="temp", Range:=Selection.Range
Use Bookmarks (index), where index is the bookmark name or index number, to return a single Bookmark object. You must exactly match the spelling (but not necessarily the capitalization) of the bookmark name. The following example selects the bookmark named «temp» in the active document.
ActiveDocument.Bookmarks("temp").Select
The index number represents the position of the bookmark in the Selection or Range object. For the Document object, the index number represents the position of the bookmark in the alphabetical list of bookmarks in the Bookmarks dialog box (click Name to sort the list of bookmarks alphabetically). The following example displays the name of the second bookmark in the Bookmarks collection.
MsgBox ActiveDocument.Bookmarks(2).Name
Remarks
The ShowHidden property effects the number of elements in the Bookmarks collection. If ShowHidden is True, hidden bookmarks are included in the Bookmarks collection.
Methods
- Add
- Exists
- Item
Properties
- Application
- Count
- Creator
- DefaultSorting
- Parent
- ShowHidden
See also
- Word Object Model Reference
[!includeSupport and feedback]