Exportación de una tabla a un documento de Word

En este ejemplo se toma la tabla denominada "Table1" de la hoja 1 y se copia en un documento Word existente denominado "Informe de trimestres" en la ubicación marcada denominada "Informe".

Código de ejemplo proporcionado por: Dennis Wallentin, VSTO & .NET & Excel

Sub Export_Table_Word()

    'Name of the existing Word doc.
    Const stWordReport As String = "Quarter 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("Sheet1")
    Set rnReport = wsSheet.Range("Table1")
    
    'Initialize the Word objects.
    Set wdApp = New Word.Application
    Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordReport)
    Set wdbmRange = wdDoc.Bookmarks("Report").Range
    
    '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
        .PasteSpecial Link:=False, _
                      DataType:=wdPasteMetafilePicture, _
                      Placement:=wdInLine, _
                      DisplayAsIcon:=False
    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

Acerca del colaborador

Dennis Wallentin es el autor de VSTO & .NET & Excel, un blog que se centra en soluciones de .NET Framework para Excel y Excel Services. Dennis lleva más de veinte años desarrollando soluciones de Excel y es, además, coautor de "Professional Excel Development: The Definitive Guide to Developing Applications Using Microsoft Excel, VBA and .NET (2nd Edition)".

Soporte técnico y comentarios

¿Tiene preguntas o comentarios sobre VBA para Office o esta documentación? Vea Soporte técnico y comentarios sobre VBA para Office para obtener ayuda sobre las formas en las que puede recibir soporte técnico y enviar comentarios.