在Word表格单元格中设置为粗体特定字符

时间:2016-02-11 14:49:25

标签: excel vba excel-vba ms-word word-vba

我有一个带有自定义脚本的MS Excel工作表。该脚本的一部分用于编辑MS Word文档中的信息。

需要编辑的内容是存储在Word文档中的表格单元格中的文本。我设法自己编辑文本,但我需要将文本的一部分设置为粗体。

我该怎么做?

这是一个例子。假设我需要在表格单元格(1,1)中输入“123456789”并将第一个字符“12345”设置为粗体。像这样: enter image description here

来自Excel。这是我试过的:

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

我知道我可以将整个单格格设置为粗体:

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

但是我可以解决单元格中的特定字符吗?

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

试试这个 在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

你应该使用它。

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