gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:42:41 24 4
gpt4 key购买 nike

我想使用 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

请注意,我已经删除了大部分与问题不直接相关的代码。希望您可以从我的代码推断出您的代码!

关于vba - Excel VBA : setting font style and size while adding text to MS-Word,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21975012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com