Excel VBA for creating numbered list in Word

冷暖自知 提交于 2019-12-08 04:50:38

问题


I am trying to use VBA code in Excel to create a numbered list in a Word document.

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

When I run this I get an error:

Method 'ApplyListTemplateWithLevel' of object 'ListFormat' failed

I have checked the Microsoft Word 12.0 Object Library in the Excel VBA references list.


回答1:


Ok I found the problem. I remoted into a friends machine to check. I got the same error as you if there were other word documents open. If no other word documents are open then your code just works fine.

Try this code. It latebinds with the Word Application so you don't need a reference to be added.

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


来源:https://stackoverflow.com/questions/10329871/excel-vba-for-creating-numbered-list-in-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!