Search code examples
vbams-worddoc

Inserting bold and regular text into word via macro - alternating issue


I have a macro and one of the arguments is an array. For each element in the array, I add a row to the table, add the standard text "NOTE:" and then the array element text. This is the relevant part of the macro I am using:

Sub fill(..., notes)

    Dim tblNew As Table
    Dim rowNew As Row
    Dim celTable As Cell
    Dim intCount As Integer

    For Each element In notes
        Set tblNew = ActiveDocument.Tables(2)
        Set rowNew = tblNew.Rows.Add
        tblNew.Cell(tblNew.Rows.Count, 1).Range.Select
        Selection.Font.Bold = wdToggle
        If Selection.Font.Underline = wdUnderlineNone Then
            Selection.Font.Underline = wdUnderlineSingle
        Else
            Selection.Font.Underline = wdUnderlineNone
        End If
        Selection.TypeParagraph
        Selection.TypeText Text:="NOTE:"
        Selection.Font.Bold = wdToggle
        If Selection.Font.Underline = wdUnderlineNone Then
            Selection.Font.Underline = wdUnderlineSingle
        Else
            Selection.Font.Underline = wdUnderlineNone
        End If
        Selection.TypeText Text:=element
    Next element

End Sub

Now this does add all the rows, and it does add the "NOTE:" and array element text part ok, the issue is with the bolding and underlining. I want the "NOTE:" to be bold and underlined, and the element text to just be plain. With the above macro, for the first row the "NOTE:" is bold/underline and text is normal, but for the next row the "NOTE:" is normal and the element text is bold/underline. The pattern alternates row to row. So this is the pattern (minus the underlining):

NOTE:

element text

Note:

element text

Note:

element text

...and so on. I've been playing around but can't get it to be the same for each row, why is it doing this alternating behaviour?


Solution

  • I understand that NOTE: must be Bold+Underlined and the text following it must be Normal. If this is correct, please try the below code:

    Dim tblNew As Table
    Dim rowNew As Row
    Dim celTable As Cell
    Dim intCount As Integer
    Dim Notes As Variant
    
    For Each element In Notes
        Set tblNew = ActiveDocument.Tables(2)
        Set rowNew = tblNew.Rows.Add
        tblNew.Cell(tblNew.Rows.Count, 1).Range.Select
        Selection.TypeParagraph
        With Selection.Range
            .Text = "NOTE:"
            .Font.Bold = True
            .Font.Underline = wdUnderlineSingle
        End With
        Selection.EndKey Unit:=wdLine
        Selection.TypeParagraph
        With Selection.Range
            .Text = element
            .Font.Bold = False
            .Font.Underline = wdUnderlineNone
        End With
    Next element