尝试将内容从Excel复制到MS Word

我试图从Excel中复制一个内容到一个MS字的书签。 但是我得到了运行时错误424.请帮助我。 我对Visual的基础知识和编程也很陌生。 我附上我的代码。 谢谢

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 

你不应该把它分成两个子文件,因为doc文件不会在它们之间持续存在,所以“ActiveDocument”将不起作用。 只需将第二个子代码复制到第一个代码中,并用wrdDocreplaceActiveDocument wrdDoc

这应该适合你。 给它一个去看看你是怎么相处的。

 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