0
votes

I'm writing data from Excel cells to a Word document table using vba and having trouble setting part of the string as bold in the Word cell.

                        objTable.cell(2, 1).Range.Text = "Answer: "
                        objTable.cell(2, 1).Characters(1, 7).Bold = True
                        objTable.cell(2, 1).Range.InsertAfter 
    Text:=ws.Cells(row, ANSWER_COLUMN) * 100 & "%"

I'm getting an error with the character selection when I have two parameters. When I have 1 parameter however it works, but only sets that single character bold. I need the entire "Answer: " label to be bold and then the text after it to not be. Once again, the table I'm selecting is a simple Word table.

1

1 Answers

0
votes

The reason for an error is clear: Characters is a collection and the only thing you can pass to it is an index value for a single character. It's not a multi-dimenionsal array or a method.

In order to extend a range or selection use one of the Move methods. For this example, MoveEnd would do the job.

There are various ways this could be done. My preferred approach is below:

  • get a Range for the cell
  • assign the content to the cell (it can be done in one go, rather than piece-meal)
  • get the starting point of the cell and extend the required number of characters (the number of characters is calculated by the length of the label)
  • apply the formatting

I get the impression writing label + content might be required more than once. If that's the case, this could be set up as a separate procedure that can be called at need...

Note: If you're working with late-binding change Word.Table, Word.Range, etc. to Object in the declarations.

Sub TestWriteToCell()
    Dim objTable As Word.Table
    'Change this to what you're using to pick up the table - 
    'You didn't provide this part of the code, so I had to "make do"
    Set objTable = ActiveDocument.Tables(1)
    Dim rngCell As Word.Range
    Dim sCellContent As String
    Dim sLabel As String

    sLabel = "Answer:"
    sCellContent = sLabel & " " & ws.Cells(Row, ANSWER_COLUMN) * 100 & "%"
    Set rngCell = objTable.Cell(2, 1).Range
    WriteToCellWithFormatting(rngCell, sLabel, sCellContent)
End Sub

Sub WriteToCellWithFormatting(rngCell As Word.Range, sLabel As String, sCellContent As String)
    Dim lBoldLength As Long

    lBoldLength = Len(sLabel)
    rngCell.Text = sCellContent
    'At this point rngCell contains the entire cell content
    'So get to the starting point...
    rngCell.Collapse wdCollapseStart
    '...then extend the required number of characters
    rngCell.MoveEnd wdCharacter, lBoldLength
    rngCell.Bold = True
End Sub