How to use VBA to bold just some text

72 Views Asked by At

I'm working on a small project where I take content from an Excel Spreadsheet and put it into a word document. I can get the two applications to communicate and put the text in the correct spot, but I cannot change the formatting and I've tried multiple ways. I think I don't understand the Range object, but I'm really not sure. Below is the code. Essentially what I want it the label ("Severity") to be bolded, and then the content, which is coming from the spreadsheet to NOT be bold. Like this:

Severity: Moderate

I can get it to bold the entire thing or not, but I can't get the code to bold just the label. Appreciate any help someone can provide.

Many thanks.

Here's the code I have so far:

Sub TestBoldToWordDocument() 
    Dim wdApp As Object 
    Dim wdDoc As Object 
    Dim ExcelRange As Range 
    Dim WordRange As Object 
    Dim TextToPaste As String 
    Dim tblNew As Table 
    Dim intX As Integer 
    Dim intY As Integer 
    Sheets("CleanSheet").Activate 
    ' Create a new Word application 
    Set wdApp = CreateObject("Word.Application") 
    wdApp.Visible = True ' Set to True if you want Word to be visible 
    ' Create a new Word document 
    Set wdDoc = wdApp.Documents.Add 
 Set WordRange = wdDoc.Content 
    With WordRange 
        .InsertAfter "Severity: " 
        .Font.Bold = True 
    End With 
    With WordRange 
        .InsertAfter Sheets("CleanSheet").Cells(2, 2).Value & vbCr 
        .Font.Bold = False 
    End With 
End Sub
2

There are 2 best solutions below

0
taller On
  • After set formatting with .Font.Bold = True, InsertAfter inserts the text with the same format.
    Set wdDoc = wdApp.Documents.Add
    Set WordRange = wdDoc.Content
    Const TXT = "Severity: "
    With WordRange
        .Text = TXT & Sheets("CleanSheet").Cells(2, 2).Value & vbCr
        Dim iEnd As Long: iEnd = Len(TXT)
        wdDoc.Range(0, iEnd-1).Font.Bold = True
    End With

  • If you prefer to use Selection
    Set wdDoc = wdApp.Documents.Add
    Const wdCollapseEnd = 0
    With wdApp.Selection
        .Font.Bold = True
        .Typetext "Severity: "
        .Collapse wdCollapseEnd
        .Font.Bold = False
        .Typetext Sheets("CleanSheet").Cells(2, 2).Value & vbCr
    End With

Microsoft documentation:

Range.Collapse method (Word)

Selection.TypeText method (Word)

Selection object (Word)

0
macropod On

Do NOT use Selection. It is horribly inefficient.

Instead, you could use something as simple as:

With WordRange
    .Collapse 0 'wdCollapseEnd
    .Text = "Severity: " & Sheets("CleanSheet").Cells(2, 2).Value & vbCr
    .Words.First.Font.Bold = True
End With