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

Excel VBA:在向MS Word添加文本时设置字体样式和大小,vba,excel,fonts,ms-word,Vba,Excel,Fonts,Ms Word,我想使用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 Lo

我想使用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语句中动态定义字体样式和大小

这样的东西合适吗

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

注意,我已经去掉了大部分与问题不直接相关的代码。希望你能从我的代码中推断出你的代码

tnx。我成功地将您的代码合并到我的代码中,对selStart的计算进行了微小的更改,以便它指向每个循环后文档的最后一个字符