gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:09:57 25 4
gpt4 key购买 nike

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

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

Method 'ApplyListTemplateWithLevel' of object 'ListFormat' failed



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

最佳答案

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

试试这个代码。它与 Word 应用程序后期绑定(bind),因此您不需要添加引用。

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

关于vba - Excel VBA 用于在 Word 中创建编号列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10329871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com