2016-07-07 75 views
0

我试图将Excel中的内容复制到MS单词中的书签上。但是我得到了运行时错误424.请帮助我。我对Visual基础知识和编程非常陌生。我附上我的代码。 感谢试图将内容从Excel复制到MS Word

Sub WordDoc() 
Dim wrdApp As Object 
Dim Number As String 
Dim wrdDoc As Object 
Set wrdApp = CreateObject("Word.Application") 
wrdApp.Visible = True 
Set wrdDoc = wrdApp.Documents.Open("H:\IP Automation\createDoc.docx") 
Number = Worksheets("Sheet1").Range("A2") 
Call InsBookmark(ID, Number) 
End Sub 


Sub InsBookmark(strBMName, strVariable) 
If strVariable <> "" Then 
If ActiveDocument.Bookmarks.Exists(ID) Then 
ActiveDocument.Bookmarks(ID).Select 
Selection.Delete 
Selection.InsertAfter (strVariable) 

End If 
End If 
End Sub 
+0

其中是抛出的错误? – RGA

回答

1

你不应该单独这分为两个潜艇,作为Word文档不会跨越它们坚持这样“的ActiveDocument”不会工作。只需将第二个子代码复制到第一个中,然后用wrdDoc代替ActiveDocument

0

这应该适合您。试试看看你是怎么相处的。

Sub Export_Table_Word() 

    'Name of the existing Word doc. 
    Const stWordReport As String = "Final Report.docx" 

    'Word objects. 
    Dim wdApp As Word.Application 
    Dim wdDoc As Word.Document 
    Dim wdbmRange As Word.Range 

    'Excel objects. 
    Dim wbBook As Workbook 
    Dim wsSheet As Worksheet 
    Dim rnReport As Range 

    'Initialize the Excel objects. 
    Set wbBook = ThisWorkbook 
    Set wsSheet = wbBook.Worksheets("PwC Contact Information") 
    Set rnReport = wsSheet.Range("Table1") 

    'Initialize the Word objets. 
    Set wdApp = New Word.Application 
    Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordReport) 
    Set wdbmRange = wdDoc.Bookmarks("Report").Range 


    Dim tbl As Table 
    For Each tbl In wdDoc.Tables 
     tbl.Delete 
    Next tbl 


    'If the macro has been run before, clean up any artifacts before trying to paste the table in again. 
    On Error Resume Next 
    With wdDoc.InlineShapes(1) 
     .Select 
     .Delete 
    End With 
    On Error GoTo 0 

    'Turn off screen updating. 
    Application.ScreenUpdating = False 

    'Copy the report to the clipboard. 
    rnReport.Copy 

    'Select the range defined by the "Report" bookmark and paste in the report from clipboard. 
    With wdbmRange 
     .Select 
     .Paste 
    End With 

    'Save and close the Word doc. 
    With wdDoc 
     .Save 
     .Close 
    End With 

    'Quit Word. 
    wdApp.Quit 

    'Null out your variables. 
    Set wdbmRange = Nothing 
    Set wdDoc = Nothing 
    Set wdApp = Nothing 

    'Clear out the clipboard, and turn screen updating back on. 
    With Application 
     .CutCopyMode = False 
     .ScreenUpdating = True 
    End With 

    MsgBox "The report has successfully been " & vbNewLine & _ 
      "transferred to " & stWordReport, vbInformation 

End Sub