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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10329871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 15:56:34  来源:igfitidea点击:

Excel VBA for creating numbered list in Word

excelvbaexcel-vbams-wordoffice-2007

提问by ploddingOn

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

我正在尝试在 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

When I run this I get an error:

当我运行它时,我收到一个错误:

Method 'ApplyListTemplateWithLevel' of object 'ListFormat' failed

对象“ListFormat”的方法“ApplyListTemplateWithLevel”失败

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

我已经检查了Microsoft Word 12.0 Object LibraryExcel VBA 参考列表中的 。

采纳答案by Siddharth Rout

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.

好的,我发现了问题。我远程进入朋友的机器进行检查。如果打开了其他 Word 文档,我会遇到与您相同的错误。如果没有打开其他 Word 文档,那么您的代码就可以正常工作。

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

试试这个代码。它与 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