1

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

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

4

1 回答 1

3

好的,我发现了问题。我远程进入朋友的机器进行检查。如果打开了其他word文档,我会遇到与您相同的错误。如果没有打开其他 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
于 2012-04-26T09:58:11.157 回答