我正在尝试在Excel中使用VBA代码在Word文档中创建编号列表。
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Add
With wrdDoc
For i = 0 To 5
.Content.InsertAfter ("Paragraph " & i)
.Content.InsertParagraphAfter
Next
.Paragraphs(1).Range.ListFormat.ApplyListTemplateWithLevel ListTemplate:= _
ListGalleries(wdNumberGallery).ListTemplates(1), ContinuePreviousList:= _
False, ApplyTo:=wdListApplyToWholeList, DefaultListBehavior:= _
wdWord10ListBehavior
End With
Set wrdApp = Nothing
Set wrdDoc = Nothing
当我运行时,我收到一个错误:
对象'ListFormat'的方法'ApplyListTemplateWithLevel'失败
我已经检查了Excel VBA引用列表中的Microsoft Word 12.0 Object Library
。
答案 0 :(得分:1)
好的,我发现了问题。我转发到朋友机检查。如果有其他单词文档打开,我会得到与您相同的错误。如果没有其他word文档打开,那么你的代码就可以了。
试试这段代码。它与Word应用程序后期绑定,因此您不需要添加引用。
Sub Sample()
Dim oWordApp As Object, oWordDoc As Object
'~~> 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
DoEvents
.Paragraphs(1).Range.ListFormat.ApplyListTemplateWithLevel ListTemplate:= _
ListGalleries(wdNumberGallery).ListTemplates(1), ContinuePreviousList:= _
False, ApplyTo:=wdListApplyToWholeList, DefaultListBehavior:= _
wdWord10ListBehavior
End With
Set oWordApp = Nothing
Set oWordDoc = Nothing
End Sub