我一直在玩VBA代码,允许自动创建word文档 . 在下面的例子中,我写了一个Word段落6次 . 为了进行某些格式化(项目符号,编号,在表格中放置文本等),似乎需要进行第二次传递并在创建文本后应用格式 . 这可以在一次通过中完成,如VBA允许我们使用粗体或斜体吗?
示例: - 切换编号 - 写入行
Sub Sample()
Dim oWordApp As Object, oWordDoc As Object
Dim i As Integer
'~~> Establish an Word application object
On Error Resume Next
Set oWordApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set oWordApp = CreateObject("Word.Application")
End If
Err.Clear
On Error GoTo 0
oWordApp.Visible = True
Set oWordDoc = oWordApp.Documents.Add
With oWordDoc
For i = 0 To 5
.Content.InsertAfter ("Paragraph " & i)
.Content.InsertParagraphAfter
Next
' Yields execution so that the operating system can process other events.
DoEvents
' why does this have to be done after creating text?
.Paragraphs(1).Range.ListFormat.ApplyListTemplateWithLevel ListTemplate:= _
ListGalleries(wdNumberGallery).ListTemplates(1), ContinuePreviousList:= _
False, ApplyTo:=wdListApplyToWholeList, DefaultListBehavior:= _
wdWord10ListBehavior
.Paragraphs(2).Range.ListFormat.ApplyListTemplateWithLevel ListTemplate:= _
ListGalleries(wdNumberGallery).ListTemplates(1), ContinuePreviousList:= _
False, ApplyTo:=wdListApplyToWholeList, DefaultListBehavior:= _
wdWord10ListBehavior
End With
Set oWordApp = Nothing
Set oWordDoc = Nothing
End Sub
3 回答
你显然可以做到这一点 . 几乎没有可能,但我相信下面的解决方案为您提供了如何使用
Document.Range(start,end)
属性的线索 .我在添加项目符号时遇到了一些麻烦,所以这里的代码对我有用 .
请注意,这需要添加对
Microsoft Word 15.0 Object Library
的引用这样做......