Excel VBA:在向 MS-Word 添加文本时设置字体样式和大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21975012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA: setting font style and size while adding text to MS-Word
提问by Tu Bui
I want to create a word document using Excel VBA, and add text with various font styles and sizes. Here is my code:
我想使用 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
How can I define font style and size on-the-fly in the if-else statement above?
如何在上面的 if-else 语句中即时定义字体样式和大小?
回答by LondonRob
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!
请注意,我已经删除了与问题没有直接关系的大部分代码。希望您可以从我的代码推断出您的代码!