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

问题描述:

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

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 

当我运行此我得到一个错误:

Method 'ApplyListTemplateWithLevel' of object 'ListFormat' failed

我在Excel VBA中的引用列表检查Microsoft Word 12.0 Object Library

+0

我测试的代码在Excel 2010中的Word 2010.它完美...测试它于2007年 – 2012-04-26 08:43:46

+0

该死! VMWare上的我的Vista正在配置更新。我需要一些时间才能测试上述内容...... – 2012-04-26 08:50:37

+0

最后在Office 2007中进行了测试。它工作得很好。 – 2012-04-26 09:29:27

好吧,我发现这个问题。我远程进入一台朋友机器进行检查。如果打开其他文档文档,我也会遇到同样的错误。如果没有其他文档文档打开,那么你的代码就可以正常工作。

试试看看这个代码。它延迟与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 
+0

它的工作 - 太棒了!你的时间非常感谢。 – ploddingOn 2012-04-26 10:42:46