Excel VBA:在向MS-Word添加文本时设置字体样式和大小

时间:2014-02-23 21:46:08

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

我想使用Excel VBA创建word文档,并添加各种字体样式和大小的文本。这是我的代码:

Sub CreateNewWordDoc()
    Dim wrdDoc As Word.Document
    Dim wrdApp As Word.Application
    Set wrdApp = CreateObject("Word.Application")
    Set wrdDoc = wrdApp.Documents.Add

    Dim charStart As Long
    Dim charEnd As Long

    With wrdDoc
        For i = 1 To 3
            charStart = wrdApp.Selection.Start
            .Content.InsertAfter (" some text")
            charEnd = wrdApp.Selection.End
            If i = 1 Then
                'set the text range (charStart,charEnd) to e.g. Arial, 8pt
            Else
                If i = 2 Then
                    'set the text range (charStart,charEnd) to e.g. Calibri, 10pt
                Else
                    'set the text range (charStart,charEnd) to e.g. Verdana, 12pt
                End If
            End If
        Next i
        .Content.InsertParagraphAfter
        .SaveAs ("testword.docx")
        .Close ' close the document
    End With
    wrdApp.Quit
    Set wrdDoc = Nothing
    Set wrdApp = Nothing
End Sub

如何在上面的if-else语句中即时定义字体样式和大小?

1 个答案:

答案 0 :(得分:6)

这样的话会适合这个账单吗?

Sub CreateNewWordDoc()
  Dim doc As Word.Document
  Dim toAdd As String
  Dim lengthAdded As Long
  Dim selStart As Long

  Set doc = ActiveDocument
  toAdd = "Hello World" ' What to add?
  lengthAdded = Len(toAdd) ' For later!
  selStart = Selection.Start ' Where to add the text?

  doc.Range(selStart).InsertAfter (toAdd)
  With doc.Range(selStart, selStart + lengthAdded)
    ' Here's where the font stuff happens
    .Font.Name = "Arial"
    .Font.Size = 15
  End With

End Sub

请注意,我已经摆脱了与问题没有直接关系的大部分代码。希望你能从我的代码中推断出你的代码!