2012-04-26 128 views
1

我想在Excel中使用VBA代碼在Word文檔中創建編號列表。用於在Word中創建編號列表的Excel VBA

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

我在Excel VBA中的引用列表檢查Microsoft Word 12.0 Object Library

+0

我測試的代碼在Excel 2010中的Word 2010.它完美...測試它於2007年 – 2012-04-26 08:43:46

+0

該死! VMWare上的我的Vista正在配置更新。我需要一些時間才能測試上述內容...... – 2012-04-26 08:50:37

+0

最後在Office 2007中進行了測試。它工作得很好。 – 2012-04-26 09:29:27

回答

1

好吧,我發現這個問題。我遠程進入一臺朋友機器進行檢查。如果打開其他文檔文檔,我也會遇到同樣的錯誤。如果沒有其他文檔文檔打開,那麼你的代碼就可以正常工作。

試試看看這個代碼。它延遲與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 
+0

它的工作 - 太棒了!你的時間非常感謝。 – ploddingOn 2012-04-26 10:42:46