用于在Word中创build编号列表的Excel VBA

我想在Excel中使用VBA代码在Word文档中创build编号列表。

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

好吧,我发现这个问题。 我远程进入一个朋友机器来检查。 如果打开其他文档文档,我也遇到同样的错误。 如果没有其他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