0
votes

I have a MS Excel worksheet with custom script. Part of this script is supposed to edit information in a MS Word document.

The thing that needs to be edited is text stored in a table cell in the Word document. I managed to edit the text it self, but I need to set part of the text to bold.

How can I do this?

Here is an example. Say I need to enter "123456789" in the table cell(1,1) and set the first characters "12345" to bold. Like this: enter image description here

From Excel. Here is what I tried:

Dim SavePath as string

SavePath = "... path ..."

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(SavePath)
objWord.Visible = True

objDoc.Tables(1).Cell(1, 1).Range.Text = "123456789"

 'So far, so good. The next part (how to set part of text to bold) is what I can't figure out. This does not work:

With objDoc.Tables(1).Cell(1, 1).Range(Start:=0, End:=5)
    .Content.Font.Bold = True
End With

I know I can set a whole single cell to bold with this:

objDoc.Tables(1).Cell(ThisRow, ThisCol).Range.Bold = True

But can I address specific characters within a cell?

Can anyone help me?

1

1 Answers

1
votes

Try this Tried and tested in Windows 7 pr. 64, Word 2010 32.

Sub test()
Set objDoc = ActiveDocument
objDoc.Tables(1).Cell(1, 1).Range.Text = "123456789"
Set myrange = objDoc.Tables(1).Cell(1, 1).Range.Paragraphs(1).Range
MsgBox myrange.Text
lStartPos = myrange.Characters(1).Start
lEndPos = myrange.Characters(5).End
Set myrange = objDoc.Range(lStartPos, lEndPos)
myrange.Font.Bold = True
End Sub

you should use this.

Sub test()
Dim SavePath As String

SavePath = "... path ..."

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(SavePath)
objWord.Visible = True
objDoc.Tables(1).Cell(1, 1).Range.Text = "123456789"
Set myrange = objDoc.Tables(1).Cell(1, 1).Range.Paragraphs(1).Range
MsgBox myrange.Text
lStartPos = myrange.Characters(1).Start
lEndPos = myrange.Characters(5).End
Set myrange = objDoc.Range(lStartPos, lEndPos)
myrange.Font.Bold = True
End Sub