Excel VBA用于在Word中创建编号列表 [英] Excel VBA for creating numbered list in Word

查看:727
本文介绍了Excel VBA用于在Word中创建编号列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Excel中使用VBA代码在Word文档中创建编号列表.

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:

对象"ListFormat"的方法"ApplyListTemplateWithLevel"失败

Method 'ApplyListTemplateWithLevel' of object 'ListFormat' failed

我已经检查了Excel VBA引用列表中的Microsoft Word 12.0 Object Library.

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

推荐答案

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

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应用程序绑定在一起,因此您不需要添加参考.

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

这篇关于Excel VBA用于在Word中创建编号列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆