Применение закладок для заполнения различных бланков на основе документов 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:
Заполненный бланк договора аренды
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]
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
Word VBA Using Bookmarks to Move the Cursor
Bookmarks are a great way to specify important locations on the word document. Using VBA you can move the cursor to those bookmarks.
–
Creating Bookmarks Manually:
For example assume you have the following data in a word document:
We want to be able to modify the value for each field using VBA for Word. Using bookmarks this process can be greatly simplified.
Step 1: Move the cursor before the name field:
Step 2: Create a bookmark:
Step 3: Do the same for the other fields:
–
VBA and Bookmarks:
Now that we have created bookmarks for the different fields in the last section we can easily modify each field. For example lets say we want to modify the name field to john. We could use the code below:
Sub main()
Selection.GoTo What:=wdGoToBookmark, Name:="bmName"
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Text = " John" & vbCr
End Sub
Result:
The line below moves the cursor to the bookmark named “bmName”:
Selection.GoTo What:=wdGoToBookmark, Name:="bmName"
The line below selects text until the end of the line:
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
For more information about selecting text in VBA for Word please see the link below:
- VBA Word, Select Text
The line below change the value of the selected text to “John”:
Selection.Text = " John" & vbCr
Example:
The code below will change the value in all the fields:
Sub main()
'change name
Selection.GoTo What:=wdGoToBookmark, Name:="bmName"
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Text = " New Name" & vbCr
'change last name
Selection.GoTo What:=wdGoToBookmark, Name:="bmLastName"
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Text = " New Last Name" & vbCr
'change address
Selection.GoTo What:=wdGoToBookmark, Name:="bmAddress"
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Text = " New Address" & vbCr
'change phone
Selection.GoTo What:=wdGoToBookmark, Name:="bmPhone"
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Text = " New Phone" & vbCr
End Sub
Result:
You can download the file and code related to this article from the link below:
- Bookmarks.docm
See also:
- VBA Word, Select Text
- Word VBA, Move Cursor to End of Line
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