vbams-wordbookmarks

Format one word in bold at a given bookmark


I'm trying to insert text at a given bookmark named "bmk_condition". The text consists of a condition number, a description, and a deadline (if available).

I want the condition and its number (e.g., Condition 2) to be in bold, while the rest should be in normal text.
enter image description here

From what I gathered on various forums, I need to set the bookmark.range.font.bold property. However, my "Condition .." text remains unformatted.

Here is a sample of my code (data extraction is omitted for brevity):

Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdBmk As Word.Bookmark
    
Set wdApp = GetObject(, "Word.Application")
Set wdDoc = wdApp.Documents.Add("template.dotx", False, 0)

wdApp.Visible = True
wdDoc.Activate

Set wdBmk = pWdDoc.Bookmarks("bmk_condition")
wdBmk.Range.Collapse Direction:=wdCollapseStart

'Insert condition #2
wdBmk.Range.Font.Bold = False
wdBmk.Range.Text = "Lorem Ipusm" & vbCrLf & "Deadline: xxxxxx"
wdBmk.Range.Font.Bold = True
wdBmk.Range.Text = "Condition 2"

'Insert condition #1
wdBmk.Range.Font.Bold = False
wdBmk.Range.Text = "Lorem Ipsum"
wdBmk.Range.Font.Bold = True
wdBmk.Range.Text = "Condition 1"

Solution

  • I'm assuming here that the Bookmark is a 0-char length 'insertion point' (I think it is based on your picture of the document).

    Your core problem is that when you do wdBmk.Range.Font.Bold = True (or False) then your code is acting on the 0-char length location of the Bookmark ... not on the text you have added. You can fix this as follows:

    Add this Sub:

    Sub AddTextToBookmark(doc As Word.Document, wdBmk As Word.Bookmark, sText As String, bBold As Boolean)
        Dim rng As Word.Range
        wdBmk.Range.Text = sText & vbCrLf
        Set rng = doc.Range(wdBmk.Start, wdBmk.Start + Len(sText))
        rng.Font.Bold = bBold
    End Sub
    

    'AddTextToBookmark()' does the core of the 'adding text' and 'making bold'. Now to use it, remove all of your existing code following the Set wdBmk = pWdDoc.Bookmarks("bmk_condition") line, then add:

    AddTextToBookmark wdDoc, wdBmk, "Lorem Ipusm" & vbCrLf & "Deadline: xxxxxx", False
    AddTextToBookmark wdDoc, wdBmk, "Condition 2", True
    AddTextToBookmark wdDoc, wdBmk, "Lorem Ipsum" & vbCrLf, False
    AddTextToBookmark wdDoc, wdBmk, "Condition 1", True
    

    You also have, I think, a typo in the code you have posted in the question ... (pWdDoc instead of wdDoc) ... are you using "Option Explicit"?