如何使用Excel中的Visual Basic创建Word文档,使某些文本变为粗体?

时间:2011-06-21 08:17:57

标签: vb6 excel-2003 word-2003

我见过this,但它对我不起作用;我无法将insertafter更改为typetext。我应该在下面更改哪些内容使文本的一部分变为粗体?

Sub CreateNewWordDoc()
    Dim wrdDoc As Word.Document
    Dim wrdApp As Word.Application
    Set wrdApp = CreateObject("Word.Application")
    Set wrdDoc = wrdApp.Documents.Add
    With wrdDoc
        .Content.InsertAfter "not bold "
        .Content.Font.Bold = True
        .Content.InsertAfter "should be bold"
        .Content.Font.Bold = False
        .Content.InsertAfter " again not bold, followed by newline"
        .Content.InsertParagraphAfter
        .Content.Font.Bold = True
        .Content.InsertAfter "bold again"
        .Content.Font.Bold = False
        .Content.InsertAfter " and again not bold"
        .Content.InsertParagraphAfter
        .SaveAs ("testword.doc")
        .Close
    End With
    wrdApp.Quit
    Set wrdDoc = Nothing
    Set wrdApp = Nothing
End Sub

1 个答案:

答案 0 :(得分:0)

当您撰写.Content.Font.Bold = True.Content.Font.Bold = False时,您在粗体而非粗体之间来回切换整个 Content。这种最后一种陈述是.Content.Font.Bold = False,所以当然没有什么是粗体的。

这是一种做你想做的事的方法。这真的很糟糕,写得很快,但它应该让你走上正轨。

    .Content.InsertAfter "not bold "
    .Content.InsertAfter "should be bold"
    .Content.InsertAfter " again not bold, followed by newline"
    .Content.InsertParagraphAfter
    .Content.InsertParagraphAfter
    .Content.InsertParagraphAfter
    .Content.InsertAfter "bold again"
    .Content.InsertAfter " and again not bold"
    .Content.InsertParagraphAfter

    .Words(3).Font.Bold = True
    .Words(4).Font.Bold = True
    .Words(5).Font.Bold = True
    .Words(16).Font.Bold = True
    .Words(17).Font.Bold = True