Friday, March 18, 2016

Export Excel to Word Template

The corresponding YouTube video is here:

https://youtu.be/BoQF9EaXZYg


''''''''''''''''''''''''''''' ENGLISHSPACEDOG '''''''''''''''''''''''''''''''''''''''''''
Option Explicit '''''''''' THIS IS VBA IN EXCEL 2010 ''''''''''''''''''''''''''''''''''''''''''
Option Base 1

Sub ExportExcelDataToWordDocument()


    'Dim wdExcelApp As Application               'Excel is the default library (optional)
    Dim wdWordApp As Word.Application   'Word app
 
 
' Creating a new instance of Word
    Set wdWordApp = New Word.Application 'instantiate a new instance of Word 2010
 
 
    With wdWordApp
     
        ' Making Word Visible on the screen
        .Visible = True             'iff false, document is invisible.
        .Activate ' make it the top pane, bring it to the front.
       

     
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        ' create a new Word Document based on the specified template
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        .Documents.Add "C:\SHTUFF\syzygy.dotm"
     
        'as before, copy the whole table from sheet to clipboard.
        Sheet2.Activate
        Range("A1", Range("A1").End(xlDown).End(xlToRight)).Copy
     
        .Selection.GoTo what:=-1, Name:="bookmark1" ' -1 means "wdgotobookmark"
        .Selection.Paste      'paste from the clipboard to the Word Doc.
       
 
     
     
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''
        ' Save WORD Document
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''
        Dim TheFileName As String
        TheFileName = "C:\SHTUFF\April.docx"
         
        '(SaveAs is for Office 2003 and earlier - deprecated)
        .ActiveDocument.SaveAs2 TheFileName
            'replaces existing .doc iff exists
         
         
        ' Close Documents and Quit Word
        .ActiveDocument.Close 'close .DOCx
        .Quit 'exit Word
    End With
 
 
    'MEMORY CLEANUP
    Set wdWordApp = Nothing 'garbage collection
    'Set wdExcelApp = Nothing 'OPTIONAL
 
 
End Sub


'''''''''''''''''''''''''''''''''''