-->

Excel VBA: setting font style and size while addin

2020-07-13 23:50发布

问题:

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!