Excel VBA: setting font style and size while adding text to MS-Word

…衆ロ難τιáo~ 提交于 2019-12-21 17:13:09

问题


I want to create a word document using Excel VBA, and add text with various font styles and sizes. Here is my code:

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

How can I define font style and size on-the-fly in the if-else statement above?


回答1:


Would something like this fit the bill?

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

Note that I've got rid of most of the code which isn't directly pertinent to the question. Hopefully you can extrapolate from my code to yours!



来源:https://stackoverflow.com/questions/21975012/excel-vba-setting-font-style-and-size-while-adding-text-to-ms-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!