2014-02-23 52 views
4

我想使用Excel VBA創建Word文檔,並添加各種字體樣式和大小的文本。這是我的代碼:Excel VBA:向MS-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語句中即時定義字體樣式和大小?

回答

5

會這樣符合法案嗎?

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 

請注意,我擺脫了大部分與問題無關的代碼。希望你能從我的代碼推斷給你的!

+0

tnx。我設法將你的代碼合併到我的程序中,並在計算_selStart_時稍作修改,以便在每個循環之後指向文檔的最後一個字符 –

相關問題