Word

Insert Text into Bookmarks

Ease of Use

Easy

Version tested with

97 

Submitted by:

Steiner

Description:

Inserts text into a bookmark, but keeps that bookmark in the document. 

Discussion:

If you insert text into a document using bookmarks and ActiveDocument.Bookmarks("bm_Test").Range.Text="Text", you'll soon notice that either the bookmark is replaced by the text (if the bookmark marked a range) or the text is inserted after the bookmark, and therefore not part of it (if the bookmark marked a position). If you want to use the text later on (maybe restart the form and insert different values) this can be a pain. The following code inserts the text right INTO the bookmark. So the bookmark stays in the document and contains the newly inserted text. 

Code:

instructions for use

			

Public Sub WB(ByVal BName As String, ByVal inhalt As String) If ActiveDocument.Bookmarks.Exists(BName) Then Dim r As Range Set r = ActiveDocument.Bookmarks(BName).Range r.Text = inhalt ActiveDocument.Bookmarks.Add BName, r Else Debug.Print "Bookmark not found: " & BName End If End Sub

How to use:

  1. Copy the code above.
  2. Open your Word document.
  3. Open the Visual Basic Editor (Alt + F11)
  4. From the menu, choose Insert-Module.
  5. Paste the code into the code window at right.
  6. Call the method from your code: WB "YourBookmarkName", "YourText"
  7. If the bookmark is found, the text will be inserted; if not, a message is given in the debug-window (if you want a messagebox instead, replace Debug.Print with Msgbox).
 

Test the code:

  1. Create a bookmark "bm_Test" inside your document
  2. Enter the following in the debug-window: WB "bm_Test", "Hello World"
 

Sample File:

No Attachment 

Approved by Anne Troy


This entry has been viewed 193 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express