Friday, March 18, 2016

How to Export Spreadsheet Data from EXCEL 2010 to Microsoft WORD

Here's the VBA code below for my latest YouTube video:

https://youtu.be/W6dIjZK06pU


''''''''''''''''''''''''''''' 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.
       
        ' Creating a New Document
        .Documents.Add 'add a new DOC (Document1.doc or .docx or .docm)
     
        ' Type Text
        With .Selection 'curr.position in Word doc.
            .ParagraphFormat.Alignment = wdAlignParagraphCenter 'center this text
            .BoldRun 'turn on bold
            .Font.Size = 14
            .TypeText "This is the Title" 'in the Word doc.
            .BoldRun 'toggle off bold
            .TypeText vbNewLine & "WHO" 'go to a new line and type stuff.
            .TypeParagraph
            .Font.Size = 11
            .ParagraphFormat.Alignment = wdAlignParagraphLeft 'WorD constant
            .TypeParagraph ' start a new paragraph.
            .TypeText "what" ' and type stuff.
         
            ''''''''''''''''''''''''''''''''''''''''''''''''''''''
            ' Copy from Excel into Word
            ''''''''''''''''''''''''''''''''''''''''''''''''''''''
            Sheet2.Activate ' goto sheet2
            Range("A1", Range("A1").End(xlDown).End(xlToRight)).Copy    ' copy  data to  clipboard
            .Paste                                                       'paste from the clipboard to the Word Doc.
     
        End With 'Selection
     
 
     
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''
        ' Save WORD Document
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''
        Dim TheFileName As String
        TheFileName = "C:\SHTUFF\Aardvark.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


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