Tuesday, March 22, 2016

MICROSOFT ACCESS 2010 VBA - WRITE TO MS WORD DOCUMENT

''' MICROSOFT ACCESS 2010 VBA - WRITE TO MS WORD DOCUMENT '''
'''''''''''''''''''''''''''''''''

https://youtu.be/iUYWzS7YdGI

Option Compare Database
Option Explicit




Private Sub lblEnglishSpaceDog_Click()

    Dim theWordApp As Word.Application
    Dim theWordDoc As Word.Document
    Dim theOpenFileName As String
    Dim theSaveFileName As String
    Dim theString As String

 
    theOpenFileName = "C:\SHTUFF\Aardvark.docx"


    ' check if Word is already running, if not, instantiate it.
    On Error Resume Next
    Error.Clear
    Set theWordApp = GetObject(, "word.application")
    If Err.Number <> 0 Then ' if Word is not already running
        Set theWordApp = New Word.Application 'instantiate
    End If
    On Error GoTo 0

    theWordApp.Visible = True


    ''''''''''
    '    OPEN THE WORD DOC.
    ''''''''''''
    Set theWordDoc = theWordApp.Documents.Open(theOpenFileName, , True)
    theWordApp.Activate


    With theWordApp

        theWordDoc.Content.InsertBefore "*HELLO world*" 'WRITE A LINE BEFORE THE EXISTIN TEXT


        ' Type and Format Text
        With .Selection 'curr.position in Word doc.
            .ParagraphFormat.Alignment = wdAlignParagraphCenter 'center this text
            .BoldRun 'turn on bold
            .Font.Size = 16
            .TypeText "*** ENGLISHSPACEDOG ***" 'in the Word doc.
            .BoldRun 'toggle off bold
            .TypeText vbNewLine & "** 2016 **" 'go to a new line and type stuff.
            .TypeParagraph
            .Font.Size = 11
            .ParagraphFormat.Alignment = wdAlignParagraphLeft 'WorD constant
            .TypeParagraph ' start a new paragraph.
            .TypeText "*QWERTY*" ' and type stuff.
        End With 'Selection
     

        theString = InputBox("type somethin", 100, 100)   'pause
        theWordDoc.Content.InsertAfter ">>>" & theString & "<<<" 'WRITE A LINE AFTER allTHE EXISTIN TEXT

 
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''
        'Save WORD Document
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''

        theSaveFileName = "C:\SHTUFF\Aardvark " & _
            Format(Now, "yyyy-mm-dd hh-mm-ss") & ".docx" '<<<<<< filename contains date/timestamp <<<<<<<
         
           '(SaveAs is for Office 2003 and earlier - deprecated)
        .ActiveDocument.SaveAs2 theSaveFileName '<<<<<< filename <<<<<<<
            'replaces existing .doc iff exists
         
         
        ' Close Document and Quit Word
        .ActiveDocument.Close 'close .DOC
        .Quit 'exit Word
     
    End With
 


    Set theWordDoc = Nothing 'garbage collection'
    Set theWordApp = Nothing


End Sub