Results 1 to 4 of 4
  1. #1
    euanl is offline Novice
    Windows 7 64bit Access 2013
    Join Date
    Jun 2013
    Posts
    25

    Sending Access Recordset to existing table in Word Document

    Hi

    New to the forum (as you will no doubt have sussed by me post count).

    I am attempting to send an access recordset, generated from a query to a specific table in an existing Word document. If (and when) I get this working I will be using it to fill several different tables in the Word document in order to create a report. The Word document itself is the template for said report and has several sections that need filled in from data from the database. I have a bit of code that fills in several named fields within the report but need the tables filled in programatically also, if you get my meaning.

    Can someone please help me with this, it is driving me mental. I spent all day yesterday trying to find an answer online to no avail. The nearest I got was this chunk of code. The instruction told me to create fields in the document It almost works but it only adds a single row to the table:

    Private Sub cmdPrint_Click()

    Dim appWord As Word.Application
    Dim doc As Word.Document
    'Dim rst As ADODB.Recordset
    'ADO refused to work how I wanted so I decided to use DAO
    Dim rst As DAO.Recordset
    Dim qdf As DAO.QueryDef


    'Avoid error 429, when Word isn't open.
    On Error Resume Next
    Err.Clear
    'Set appWord object variable to running instance of Word.
    Set appWord = GetObject(, "Word.Application")
    If Err.Number <> 0 Then
    'If Word isn't open, create a new instance of Word.
    Set appWord = New Word.Application
    End If
    'Populate recordset object.
    Set rst = New ADODB.Recordset

    'original coding
    'rst.Open Me.RecordSource, CurrentProject.Connection

    'I want to use an existing query, and use DAO:

    Set db = CurrentDb
    Set qdf = db.QueryDefs("qryWLOutput")
    Set rst = qdf.OpenRecordset

    'Cycle through records to fill Word form fields.
    Do While Not rst.EOF
    Set doc = appWord.Documents.Open("C:\Users\eleslie\Documents \Test\Management.doc", , True)
    'Save as new file (when I do this for real I will prompt the user to select the correct folder for saving the files, or preferably dynamically get the database to find the correct folder)
    doc.SaveAs ("C:\Users\eleslie\Documents\Test\Thisistheoutputf romthetest.doc")

    With doc
    .FormFields("fldReq_by").Result = rst!fldReq_by
    .FormFields("fldDate_Requested").Result = rst!Date_Requested
    .FormFields("fldDetails").Result = rst!Details
    .FormFields("fldDate_Req").Result = rst!Date_Req

    .Visible = True
    .Activate
    '.PrintOut
    '.SaveAs "'" & rst!CustomerID & "'"
    rst.MoveNext
    End With
    Loop
    Set doc = Nothing
    Set appWord = Nothing
    Exit Sub
    errHandler:


    MsgBox Err.Number & ": " & Err.Description

    End Sub

    The original instructions said to create fields in the document, which works fine for the populating single fields, but when you try to do it in a table it just scrolls through all the records in the recordset in front of your very eyes and dumps the last record in a single row. Obviously I want each record in the recordset to appear in a separate row, and I don't want to limit the amount of rows as each version of the recordset will contain a different amount of records.

    What am I doing wrong. Arrrgghhhhh!!!

    Thanks in advance for any hep you can give me, and if it is just me being stupid be gentle, I am an Access forum virgin.

  2. #2
    DepricatedZero's Avatar
    DepricatedZero is offline Cthulhu Fhtagn!
    Windows 8 Access 2007
    Join Date
    Apr 2013
    Location
    Cincinnati
    Posts
    65
    Hi and welcome! I've run into the same issue - Access's reporting features are...dismal. Easily powerful, but it seems like they forgot they had built a relational database when they constructed the reporting tools.

    I'm in the middle of rolling out a hotfix atm, once I'm finished I have some code that might help you.

  3. #3
    euanl is offline Novice
    Windows 7 64bit Access 2013
    Join Date
    Jun 2013
    Posts
    25
    Thanks for that.

    Quote Originally Posted by DepricatedZero View Post
    Hi and welcome! I've run into the same issue - Access's reporting features are...dismal. Easily powerful, but it seems like they forgot they had built a relational database when they constructed the reporting tools.

    I'm in the middle of rolling out a hotfix atm, once I'm finished I have some code that might help you.

  4. #4
    DepricatedZero's Avatar
    DepricatedZero is offline Cthulhu Fhtagn!
    Windows 8 Access 2007
    Join Date
    Apr 2013
    Location
    Cincinnati
    Posts
    65
    It's important to note that this is a Module but not a Class. It can be called without being instantiated first.

    Here are the first few functions:

    Code:
    Option Explicit
    Enum reportTypes
        CustomerDetail = 1
        Addressing = 2
    End Enum
    
    Public Function Test()
        BuildReport "Detailed Report", CustomerDetail
        
    End Function
    Public Sub BuildReport(fileName As String, report As reportTypes)
        Dim wordApp As Word.Application
        Dim wordDoc As Word.Document
        
        Set wordApp = New Word.Application
        Set wordDoc = wordApp.Documents.Add()
        SetLayout wordDoc, wordApp
        
        wordDoc.Tables.Add wordDoc.Paragraphs(wordDoc.Paragraphs.Count).Range, 1, 1
        Dim tablePosition As Integer
        tablePosition = wordDoc.Tables.Count
        
        Select Case report
        Case CustomerDetail:
            BuildCustomerDetailReport wordDoc
        Case Addressing:
            BuildAddressingReport wordDoc
        End Select
            
        Dim exportPath As String
        exportPath = "" 'your path here    
        
        wordDoc.ExportAsFixedFormat fileName & ".pdf" _
            , wdExportFormatPDF, True, wdExportOptimizeForOnScreen, wdExportAllDocument, _
            , , wdExportDocumentContent, False, True, wdExportCreateHeadingBookmarks _
            , True, True, False
        
        wordDoc.Close False
        wordApp.Quit False
        Set wordDoc = Nothing
        Set wordApp = Nothing
        
        
    End Sub
    
    Private Sub SetLayout(wordDoc As Word.Document, wordApp As Word.Application)
        With wordDoc.Paragraphs.TabStops
            .ClearAll
            .Add position:=InchesToPoints(0.75), Alignment:=wdAlignTabRight
            .Add position:=InchesToPoints(0.8), Alignment:=wdAlignTabLeft
            .Add position:=InchesToPoints(4.5), Alignment:=wdAlignTabRight
            .Add position:=InchesToPoints(4.55), Alignment:=wdAlignTabLeft
        End With
        'wordDoc.Paragraphs.LineSpacingRule = wdLineSpaceExactly
        'wordDoc.Paragraphs.LineSpacing = 10
        With wordDoc.PageSetup
            .TopMargin = wordApp.InchesToPoints(0.2)
            .BottomMargin = wordApp.InchesToPoints(0.5)
            .LeftMargin = wordApp.InchesToPoints(0.5)
            .RightMargin = wordApp.InchesToPoints(0.5)
        End With
        With wordDoc.Styles("Heading 2").Font
            .Bold = True
            .Size = 18
            .name = "Calibri"
            .Color = RGB(31, 73, 125)
        End With
        With wordDoc.Styles("Heading 3").Font
            .Bold = True
            .Size = 14
            .name = "Calibri"
            .Color = RGB(31, 73, 125)
        End With
        With wordDoc.Styles("Heading 4").Font
            .Bold = True
            .Italic = False
            .Size = 12
            .name = "Calibri"
            .Color = RGB(31, 73, 125)
        End With
        With wordDoc.Styles("Heading 1").Font
            .Bold = True
            .Italic = True
            .Size = 20
            .name = "Calibri"
            .Color = RGB(23, 54, 93)
        
        End With
        With wordDoc.Styles("Normal").Font
            .Bold = False
            .Size = 11
            .name = "Calibri"
            .Color = wdColorBlack
        End With
    End Sub
    This works by creating a new, blank word document, setting styles, and then calling functions to build the appropriate report. Once the report is finished building it saves it as a PDF in the specified folder (you could add a reference to pass a path directly or code it in. We want all reports to always go to one folder so I hard coded it here). Then it closes the word document, closes Word, and unsets them. The SetLayout function is used to customize the different Headers and set tabs. This way, all reports follow a standardized layout.

    If you just want to show the Word doc instead of saving it, wordApp.visible = true instead of killing the document and app should do the trick - and you can delete the ExportToFixedFormat function out of there.

    I am still working on this - actually likely what I'll be doing for most of today - but here are some of the 'builder' functions I use:


    Code:
    Private Sub BuildCustomerDetailReport(wordDoc As Word.Document)
        
        wordDoc.Paragraphs.Add
        With wordDoc.Paragraphs(wordDoc.Paragraphs.Count)
            .Alignment = wdAlignParagraphCenter
            With .Range
                .Bold = True
                With .Font
                    .Size = 20
                    .Color = wdColorBlack
                    .name = "Calibri"
                End With
                .text = "Customer Management and Resources"
            End With
        End With
        
            wordDoc.Paragraphs.Add
        With wordDoc.Paragraphs(wordDoc.Paragraphs.Count)
            .Alignment = wdAlignParagraphCenter
            With .Range
                .Bold = True
                With .Font
                    .Size = 14
                    .Color = wdColorBlack
                    .name = "Calibri"
                End With
                .text = [redacted]
            End With
        End With
        CreateCustomerTier "Platinum", wordDoc
        CreateCustomerTier "Gold", wordDoc
        CreateCustomerTier "Silver", wordDoc
        
    End Sub
    
    Private Sub CreateCustomerTier(custTier As String, wordDoc As Word.Document)
        Dim db As DAO.Database
        Dim rs As DAO.Recordset
        Dim def As DAO.QueryDef
        
        Set db = CurrentDb
        Set def = db.QueryDefs![qryReport_CustomerDetails_PARAM]
        
        def.Parameters![tier] = custTier
        
        Set rs = def.OpenRecordset
        
        rs.MoveFirst
        
        Delimit wordDoc, rs!strTier & " Customers", HeadingOne
        
        wordDoc.Tables.Add wordDoc.Paragraphs(wordDoc.Paragraphs.Count).Range, 1, 4
        
        Dim customerTable As Integer
        
        customerTable = wordDoc.Tables.Count
        Dim currentColumn As Integer
        Do Until rs.EOF
            With wordDoc.Tables(customerTable)
                currentColumn = currentColumn + 1
                If currentColumn = 5 Then
                    currentColumn = 1
                    .Rows.Add
                End If
                .Cell(.Rows.Count, currentColumn).Range.text = rs!strCustName
                .Cell(.Rows.Count, currentColumn).Range.Style = "Heading 3"
            End With
            CreateHeader wordDoc, rs
            FillCustomerTables wordDoc, rs!strCustName
            rs.MoveNext
        Loop
        rs.Close
    End Sub
    That last function, CreateCustomerTier, is probably most relevant to your exact question - but it seemed like a broader answer would be helpful to you.

    If you're already successfully launching a template document, you need to know several things:

    Which table are you manipulating and how to reference it - in this case it is almost always working on the last created table. Note though that the first table created in each "CreateCustomerTier" function is tracked and added to as the report builds each page.

    You also need to know which cell of the table you want to populate, what row and column it's in.

    Hope that helps if nothing else, I know just seeing context for some of these calls can be immensely helpful for me.

Please reply to this thread with any new information or opinions.

Similar Threads

  1. Recreate Word document in Access Report
    By cphelps48 in forum Reports
    Replies: 2
    Last Post: 11-29-2011, 04:32 PM
  2. Replies: 3
    Last Post: 05-19-2011, 10:20 AM
  3. Closing Word Document From Access
    By bburton in forum Programming
    Replies: 2
    Last Post: 04-25-2011, 10:23 AM
  4. Open a word document from access
    By natalia in forum Programming
    Replies: 1
    Last Post: 10-13-2010, 08:04 AM
  5. Word document INTO Access form
    By jonathonhicks in forum Forms
    Replies: 0
    Last Post: 04-30-2007, 05:59 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Other Forums: Microsoft Office Forums