Results 1 to 6 of 6
  1. #1
    riggsdp is offline Novice
    Windows 7 64bit Access 2010 64bit
    Join Date
    Nov 2014
    Posts
    25

    Inserting records into MSWord table

    I have a form with data that I insert into a Word file using bookmarks. That part works fine, however, I need to add items from a table to the bottom of the Word file, add rows depending on the number of comments in the table, make sure they are sorted correctly, and format the header row.



    Based on other posts here, I went to this page: http://www.vb-helper.com/howto_acces...ord_table.html, and modified the code for my database but I get a compile error, user-defined type not defined on the highlighted text. Do I need to use DAO instead of ADO and if so, how do I do this without using the GetString since it is used for ADO?

    Text in red is the code in question.

    Code:
    Public Function PrintLetter(frmName As Form)
    
        Dim appWord As Word.Application
        Dim txtContract As String 'contract number
        Dim txtDOTO As String 'delivery/task order
        Dim txtCDRL As String 'CDRL number
        Dim txtNameNum As Integer 'signatory index key
        Dim txtName As String 'signatory name
        Dim txtTitle As String 'signatory title
        Dim docRev As String 'document revision
        Dim disText As Integer 'distribution text record
        Dim relateID As Integer ' relation ID between records
        Dim newRange As Range 'range for comments table
        Dim Msg, Style, Title, Response 'variables for msgbox
        
        Dim rstComments As ADODB.Recordset
        Dim dbsName As String
        Dim conn As ADODB.Connection
        Dim strSQL As String
        Dim txt As String
        Dim new_range As Range
        Dim new_field As ADODB.Field
        
        frmName.SetFocus 'make sure form is active
        
        'get index key from form for signatory
        txtNameNum = DLookup("Signatory_Name", "tblDeliveryTaskOrders", "Task_ID=" & frmName.Delivery_Task_Order)
        txtName = DLookup("Team_Member", "tblTeamMembers", "Member_ID=" & txtNameNum) 'get member name
        txtTitle = DLookup("Disposition_Title", "tblTeamMembers", "Member_ID=" & txtNameNum) 'get member title
        relateID = frmName.tblDeliveredItems_Relate_ID
    
        'check revision
        If frmName.Document_Revision = "Basic" Then 'if it's the initial release
            docRev = "" 'set variable to nothing
        Else
            docRev = frmName.Document_Revision 'else set to field value
        End If
        
        'check approval status to set record from tblDisposition
        'to get correct approval/rejection text for letter
        If frmName.Approved_Rejected = "Approved" Then 'if approved
            disText = 1 'set disposition text to record 1
        'if approved with comments
        ElseIf frmName.Approved_Rejected = "Approved with comments" Then
            disText = 2 'set disposition text to record 2
        'if rejected with comments
        ElseIf frmName.Approved_Rejected = "Rejected with comments" Then
            disText = 3 'set disposition text to record 3
        End If
        
        'set error trap
        On Error Resume Next
        Err.Clear
        
        'open MSWord
        Set appWord = GetObject(, "Word.Application")
        If Err.Number <> 0 Then
            Set appWord = New Word.Application
            appWord.Visible = True
        End If
        
        'Verify template file is in correct location using FileExists function
        
        'if file not found
        If FileExists(TrailingSlash(CurrentProject.Path) & "Disposition_Letter_Template.dotx") = False Then
            'set up msgbox for error message
            Msg = "Please make sure the Disposition_Letter_Template.dotx file" & _
            vbCrLf & "is located in the same folder as this database."
            Style = vbOKOnly
            Title = "Verify CDRL Template Location"
            Response = MsgBox(Msg, Style, Title) 'display msg box
        Else: 'if file found, do nothing, exit if statment, and continue
        End If
        
        'set up database name
        Set dbsName = CurrentDb
    
        'connect to database
        Set conn = New ADODB.Connection
        conn.Mode = adModeRead
        conn.ConnectionString = _
            "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=" & db_name
        conn.Open
    
        'get comments
        With dbsName
    
            strSQL = "SELECT Item_Number, Reference, Comment, Disposition, Relate_ID " & _
                "FROM tblComments WHERE Relate_ID = " & relateID & " ORDER BY Item_Number"
    
            'open recordset
            Set rstComments = conn.Execute(strSQL)
    
            ' Add a row containing the field names.
            For Each new_field In rstComments.Fields
                txt = txt & vbTab & new_field.Name
            Next new_field
            txt = Mid$(txt, 2) & vbCrLf 'remove leading tab.
    
            ' Get the Recordset's data as a single string
            ' with vbTab between fields and vbCrLf between rows
            txt = txt & rstComments.GetString( _
                ColumnDelimeter:=vbTab, _
                RowDelimeter:=vbCrLf, _
                NullExpr:="<null>")
        End With
    
        ' Close the Recordset
        rstComments.Close
    
        With appWord
            
            'Open the document template
            .Documents.Open (TrailingSlash(CurrentProject.Path) & "Disposition_Letter_Template.dotx")
    
            'Move to each bookmark and insert text from the form or variables
            .ActiveDocument.Bookmarks("docnum").Range.InsertBefore (CStr(frmName.Document_Number))
            .ActiveDocument.Bookmarks("revision").Select
            .Selection.Text = docRev
            .ActiveDocument.Bookmarks("date").Range.InsertBefore (CStr(frmName.Date_Disposition_Sent))
            .ActiveDocument.Bookmarks("title").Range.InsertBefore (CStr(frmName.Document_Title))
            .ActiveDocument.Bookmarks("transmittal").Range.InsertBefore (CStr(frmName.Transmittal_Letter))
            .ActiveDocument.Bookmarks("contract").Range.InsertBefore (CStr(frmName.Contract_Number.Column(1)))
            .ActiveDocument.Bookmarks("doto").Range.InsertBefore (CStr(frmName.Delivery_Task_Order.Column(1)))
            .ActiveDocument.Bookmarks("cdrl").Range.InsertBefore (CStr(frmName.CDRL_Number.Column(1)))
            .ActiveDocument.Bookmarks("disposition").Range.InsertBefore (CStr(DLookup("Disposition_Text", "tblDisposition", "Text_ID=" & disText)))
            .ActiveDocument.Bookmarks("sigtitle").Select
            .Selection.Text = txtTitle
            .ActiveDocument.Bookmarks("signatory").Select
            .Selection.Text = txtName
    
            ' Make a Range at the end of the Word document.
            Set new_range = ActiveDocument.Range
            new_range.Collapse wdCollapseEnd
    
            ' Insert the text and convert it to a table.
            new_range.InsertAfter txt
            new_range.ConvertToTable vbTab
    
            ' Autofit to the contents.
            new_range.Tables(1).AutoFitBehavior wdAutoFitContent
    
            ' Add a blank line.
            Set new_range = ActiveDocument.Range
            new_range.Collapse wdCollapseEnd
            new_range.InsertParagraph
            new_range.Collapse wdCollapseEnd
            new_range.InsertParagraph
    
            'set variables for filename
            Dim docName As String 'holds filename
            Dim fullName As String 'holds current project path and filename
            
            'set doc name to document number plus CDRL item number
            docName = (CStr(frmName.Document_Number)) & "_" & (CStr(frmName.Document_Revision)) & "_Disposition" & ".docx"
            fullName = CurrentProject.Path & "\" & docName 'set fullName to path plus docName
            
            .Activate 'activate Word file
            .ActiveDocument.SaveAs2 fileName:=fullName 'save file to current project path with file name
    
        End With
        
    End Function

  2. #2
    John_G is offline VIP
    Windows 7 32bit Access 2010 32bit
    Join Date
    Oct 2011
    Location
    Ottawa, ON (area)
    Posts
    2,615
    There are a number of problems here.

    - Why are you trying to connect to the database you are already in? All you need is the recordset, and not with the ADODB.

    - db_Name is undefined (and you don't need it anyway)

    - You don't need GetString. Once you have the recordset, just use rstComments.Comment

    - This line will fail: Set dbsName = CurrentDb because dbsName is a string, and Currentdb is a database reference.

    Since you are always reading data from the same table, you already know its structure, so it might be easier to have the MS Word template have a blank table, but with the header row, and just add rows to it in the same code block you retrieve them from the database. I do exactly the same sort of thing you are doing, using bookmarks and tables to transfer from Access to Word, and I add one row at a time as required.

    John

  3. #3
    John_G is offline VIP
    Windows 7 32bit Access 2010 32bit
    Join Date
    Oct 2011
    Location
    Ottawa, ON (area)
    Posts
    2,615
    Here is my code, stripped down quite a bit, but it does the same as you are doing, i.e. using an MS Word template with bookmarks and a table. You would obviously have to change it quite a bit, but you can get the general idea. I have highlighted in red the parts that would be most important to you.


    Code:
    Sub Export_Competency(Competency_Code As String, Competency_Instance As Integer, wrdApp As Word.Application)
      Dim CurrentProcedure As String
      Dim db As Database, rst As Recordset
      Dim SQL As String
      Dim InstanceWhere As String
      Dim TranslationNumber As Long
      Dim ExportFileName As String
      Dim TemplateFileName As String
      Dim ItemCount As Integer
      Dim CompetencyType As Integer
      Dim wrdDoc As Word.Document
      Dim Item_ID As String
      Dim File_Prefix As String
      CurrentProcedure = "Export_Competency"
      On Error GoTo Proc_Error
      '
      ' Determine the competency type
      ' Competency type 2, National Qualification, has few items associated with it
      '
      CompetencyType = DLookup("CmptcyCat_CDE", "Competency", "Cmptcy_Code_ID = '" & Competency_Code & "'")
      If CompetencyType = 1 Then File_Prefix = "SS"
      If CompetencyType = 2 Then File_Prefix = "RQ"
      If CompetencyType = 3 Then File_Prefix = "EQ"
      If CompetencyType = 4 Then File_Prefix = "PG"
      '
      ' Generate Template and output file names
      '
      TemplateFileName = DLookup("DocumentTemplates", "Control")
      TemplateFileName = TemplateFileName & "\" & "OSS_Translation_Request_Template.doc"
      
      ExportFileName = DLookup("ExportTranslationPath", "Control")
      ExportFileName = ExportFileName & "\" & File_Prefix & "_Translation_" & Competency_Code & "_" & Format(Date, "dd-MMM-yyyy")
      '
      ' open the template file
      '
      Set wrdDoc = wrdApp.Documents.Open(TemplateFileName, , , , , , , , , , , False)
      
      Set db = CurrentDb
      InstanceWhere = "[cmptcyinst_ID] = " & Competency_Instance
      
      '
      ' Description
      '
      Set rst = db.OpenRecordset("Translate competency description")  ' There is only one record in this recordset
    
      wrdDoc.Bookmarks("OSS_code").Range.InsertAfter Competency_Code
      wrdDoc.Bookmarks("OSS_name").Range.InsertAfter rst!Cmptcy_Name_En
      wrdDoc.Bookmarks("file_date").Range.InsertAfter Format(Date, "dd-MMM-YYYY")
      wrdDoc.Bookmarks("file_name").Range.InsertAfter ExportFileName
      wrdDoc.Bookmarks("Instance_ID").Range.InsertAfter Competency_Instance
      wrdDoc.Bookmarks("Instance_Type").Range.InsertAfter " 2 (Competency)"
      wrdDoc.Bookmarks("Full_Listing").Range.InsertAfter "No"
      wrdDoc.Bookmarks("Status_Code").Range.InsertAfter "5"
      wrdDoc.Bookmarks("Status_Text").Range.InsertAfter "Approved"
      ItemCount = 0
      
      
        '
        ' T/S/K Statements
        '
        Set rst = db.OpenRecordset("Select * from [Translate Competency Statement] order by Statcat_Cde, Stat_SEQ")
        While Not rst.BOF And Not rst.EOF
          If rst!Stat_Text_SREM_Lang_IND = 1 Then
            '
            ' Write_Item adds rows to the table - see below
            '
            Write_Item wrdApp, wrdDoc, ItemCount, TranslationNumber, rst!Stat_Text_SREM_En, _
            IIf(ExportFrench, Nz(rst!Stat_Text_SREM_Fr, " "), " "), Item_ID
          End If
          rst.MoveNext
        Wend
        rst.Close
    
        '
        ' Save the word document
        '
        wrdDoc.SaveAs (ExportFileName)
        MsgBox Competency_Code & " translation document saved as " & vbCrLf & ExportFileName
      Else
        MsgBox "Competency Code " & Competency_Code & " had no items requiring translation.  The status has been set to 'translated', and the translation file has been discarded", vbInformation, "Nothing to translate"
      wrdDoc.Close wdDoNotSaveChanges  ' Don't save changes to the template file
      Set wrdDoc = Nothing
      Set db = Nothing
      Exit Sub
    Proc_Error:
      Process_Error CurrentForm, CurrentProcedure, Err.Description
      wrdDoc.Close wdDoNotSaveChanges
    End Sub
    
    
    Sub Write_Item(wrdApp As Word.Application, wrdDoc As Word.Document, ItemCount As Integer, TranslationItem As Long, _
          English As String, ExistingFrench As String, Optional Item_ID As String = "?")
      Dim CurrentProcedure As String
      Dim wrdRange As Word.Range
      Dim Currentrow As Integer
      On Error GoTo Proc_Error
      CurrentProcedure = "Write_Item"
      ItemCount = ItemCount + 1
       
      If ItemCount = 1 Then
        '
        ' Go to the item bookmark, and update that row
        '
        Set wrdRange = wrdDoc.GoTo(What:=wdGoToBookmark, Name:="Item")
        wrdRange.Select
        wrdRange.InsertAfter TranslationItem
        '
        ' Move to the next cell to the right, for English
        '
        wrdApp.Selection.Move wdCell, 1
        wrdApp.Selection.InsertAfter English
        '
        ' Move to the next cell to the right, for French
        '
        wrdApp.Selection.Move wdCell, 1
        wrdApp.Selection.InsertAfter ExistingFrench
        '
        ' Move to the next cell to the right, for Item_ID
        '
        wrdApp.Selection.Move wdCell, 1
        wrdApp.Selection.InsertAfter Item_ID
      Else
        '
        ' Insert a new row
        '
        Currentrow = wrdApp.Selection.Information(wdStartOfRangeRowNumber)
        wrdDoc.Tables(1).Rows(Currentrow).Select
        wrdApp.Selection.InsertRowsBelow 1
        '
        ' when a row is added, the whole (new) row is selected
        ' Collapse de-selects the row, leaving the insertion point in the next cell
        '
        wrdApp.Selection.Collapse
        wrdApp.Selection.InsertAfter TranslationItem
        wrdApp.Selection.Move wdCell, 1
        wrdApp.Selection.InsertAfter English
        wrdApp.Selection.Move wdCell, 1
        wrdApp.Selection.InsertAfter ExistingFrench
        wrdApp.Selection.Move wdCell, 1
        wrdApp.Selection.InsertAfter Item_ID
      End If
      Exit Sub
    Proc_Error:
      Process_Error CurrentForm, CurrentProcedure, Err.Description
    End Sub

    wrdapp is defined outside the Export_Competency routine this way:

    Set wrdApp = New Word.Application

    As I said, you would have to modify this quite a bit to suit your needs, but I hope this will give you some guidance.

    John

  4. #4
    riggsdp is offline Novice
    Windows 7 64bit Access 2010 64bit
    Join Date
    Nov 2014
    Posts
    25

    Thumbs up

    You are my new best friend for the next five minutes.

    Here's what I ended up with and it works perfectly, my lead will be ecstatic:

    Code:
    Public Function PrintLetter(frmName As Form)
    
        Dim appWord As Word.Application
        Dim txtContract As String 'contract number
        Dim txtDOTO As String 'delivery/task order
        Dim txtCDRL As String 'CDRL number
        Dim txtNameNum As Integer 'signatory index key
        Dim txtName As String 'signatory name
        Dim txtTitle As String 'signatory title
        Dim docRev As String 'document revision
        Dim disText As Integer 'distribution text record
        Dim relateID As Integer ' relation ID between records
        Dim Msg, Style, Title, Response 'variables for msgbox
        'variables for comments
        Dim rstComments As Recordset
        Dim dbsName As Database
        Dim ItemCount As Integer
        Dim strSQL As String
        Dim wrdDoc As Word.Document
        
        frmName.SetFocus 'make sure form is active
        
        'get index key from form for signatory
        txtNameNum = DLookup("Signatory_Name", "tblDeliveryTaskOrders", "Task_ID=" & frmName.Delivery_Task_Order)
        txtName = DLookup("Team_Member", "tblTeamMembers", "Member_ID=" & txtNameNum) 'get member name
        txtTitle = DLookup("Disposition_Title", "tblTeamMembers", "Member_ID=" & txtNameNum) 'get member title
        relateID = frmName.tblDeliveredItems_Relate_ID
    
    
        'check revision
        If frmName.Document_Revision = "Basic" Then 'if it's the initial release
            docRev = "" 'set variable to nothing
        Else
            docRev = frmName.Document_Revision 'else set to field value
        End If
        
        'check approval status to set record from tblDisposition
        'to get correct approval/rejection text for letter
        If frmName.Approved_Rejected = "Approved" Then 'if approved
            disText = 1 'set disposition text to record 1
        'if approved with comments
        ElseIf frmName.Approved_Rejected = "Approved with comments" Then
            disText = 2 'set disposition text to record 2
        'if rejected with comments
        ElseIf frmName.Approved_Rejected = "Rejected with comments" Then
            disText = 3 'set disposition text to record 3
        End If
        
        'set error trap
        On Error Resume Next
        Err.Clear
        
        'open MSWord
        Set appWord = GetObject(, "Word.Application")
        If Err.Number <> 0 Then
            Set appWord = New Word.Application
            appWord.Visible = True
        End If
        
        'Verify template file is in correct location using FileExists function
        
        'if file not found
        If FileExists(TrailingSlash(CurrentProject.Path) & "Disposition_Letter_Template.dotx") = False Then
            'set up msgbox for error message
            Msg = "Please make sure the Disposition_Letter_Template.dotx file" & _
            vbCrLf & "is located in the same folder as this database."
            Style = vbOKOnly
            Title = "Verify CDRL Template Location"
            Response = MsgBox(Msg, Style, Title) 'display msg box
        Else: 'if file found, do nothing, exit if statment, and continue
        End If
        
        'Open the document template
        Set wrdDoc = appWord.Documents.Open(TrailingSlash(CurrentProject.Path) & "Disposition_Letter_Template.dotx")
        'Move to each bookmark and insert text from the form or variables
        wrdDoc.Bookmarks("docnum").Range.InsertBefore (CStr(frmName.Document_Number))
        wrdDoc.Bookmarks("revision").Range.InsertBefore docRev
        wrdDoc.Bookmarks("date").Range.InsertBefore (CStr(frmName.Date_Disposition_Sent))
        wrdDoc.Bookmarks("title").Range.InsertBefore (CStr(frmName.Document_Title))
        wrdDoc.Bookmarks("transmittal").Range.InsertBefore (CStr(frmName.Transmittal_Letter))
        wrdDoc.Bookmarks("contract").Range.InsertBefore (CStr(frmName.Contract_Number.Column(1)))
        wrdDoc.Bookmarks("doto").Range.InsertBefore (CStr(frmName.Delivery_Task_Order.Column(1)))
        wrdDoc.Bookmarks("cdrl").Range.InsertBefore (CStr(frmName.CDRL_Number.Column(1)))
        wrdDoc.Bookmarks("disposition").Range.InsertBefore (CStr(DLookup("Disposition_Text", "tblDisposition", "Text_ID=" & disText)))
        wrdDoc.Bookmarks("sigtitle").Range.InsertBefore txtTitle
        wrdDoc.Bookmarks("signatory").Range.InsertBefore txtName
        
        'set up database name
        Set dbsName = CurrentDb
        'open recordset
        Set rstComments = dbsName.OpenRecordset("Comments")
        'set up sql string
        strSQL = "SELECT Item_Number, Reference, Comment, Disposition, Relate_ID " & _
                "FROM tblComments WHERE Relate_ID = " & relateID & " ORDER BY Item_Number"
        'set recordset to select results
        Set rstComments = dbsName.OpenRecordset(strSQL)
        
        'write to template
        While Not rstComments.BOF And Not rstComments.EOF 'for recordset
          If rstComments!Relate_ID = relateID Then 'if record relateID = form relateID
            'call Write_Item to add to the table
            Write_Item appWord, wrdDoc, ItemCount, rstComments!Item_Number, rstComments!Reference, rstComments!Comment, rstComments!Disposition
          End If
          rstComments.MoveNext 'go to next record
        Wend
    
    
        'close the recordset
        rstComments.Close
    
    
        'set variables for filename
        Dim docName As String 'holds filename
        Dim fullName As String 'holds current project path and filename
            
        'set doc name to document number plus CDRL item number
        docName = (CStr(frmName.Document_Number)) & "_" & (CStr(frmName.Document_Revision)) & "_Disposition" & ".docx"
        fullName = CurrentProject.Path & "\" & docName 'set fullName to path plus docName
            
        wrdDoc.Activate 'activate Word file
        wrdDoc.SaveAs fileName:=fullName 'save file to current project path with file name
        
    End Function
    
    
    Sub Write_Item(wrdApp As Word.Application, wrdDoc As Word.Document, ItemCount As Integer, Item_Number As String, Reference As String, Comment As String, Disposition As String)
      
        Dim wrdRange As Word.Range
        Dim Currentrow As Integer
      
        ItemCount = ItemCount + 1 'add one to counter
       
        If ItemCount = 1 Then
            'go to the comment bookmark, and update that row
            Set wrdRange = wrdDoc.GoTo(What:=wdGoToBookmark, Name:="comments")
            wrdRange.Select 'select range
            wrdRange.InsertAfter Item_Number 'insert item number
            wrdApp.Selection.Move wdCell, 1 'move one cell to right
            wrdApp.Selection.InsertAfter Reference 'insert reference
            wrdApp.Selection.Move wdCell, 1 'move one cell to right
            wrdApp.Selection.InsertAfter Comment 'insert comment
            wrdApp.Selection.Move wdCell, 1 'move one cell to right
            wrdApp.Selection.InsertAfter Disposition 'insert disposition
        Else
            'find current row
            Currentrow = wrdApp.Selection.Information(wdStartOfRangeRowNumber)
            wrdDoc.Tables(1).Rows(Currentrow).Select 'select row
            wrdApp.Selection.InsertRowsBelow 1 'insert new row below
            wrdApp.Selection.Collapse 'deselect row leaving insertion point in next cell
            wrdApp.Selection.InsertAfter Item_Number 'insert item number
            wrdApp.Selection.Move wdCell, 1 'move one cell to right
            wrdApp.Selection.InsertAfter Reference 'insert reference
            wrdApp.Selection.Move wdCell, 1 'move one cell to right
            wrdApp.Selection.InsertAfter Comment 'insert comment
            wrdApp.Selection.Move wdCell, 1 'move one cell to right
            wrdApp.Selection.InsertAfter Disposition 'insert disposition
        End If
    
    End Sub
    Thank you!
    Dar

  5. #5
    riggsdp is offline Novice
    Windows 7 64bit Access 2010 64bit
    Join Date
    Nov 2014
    Posts
    25
    Well, it stopped working for some reason even though I haven't changed the code. It goes to the line where it calls Write_Item, but never actually goes to the sub-routine.

  6. #6
    John_G is offline VIP
    Windows 7 32bit Access 2010 32bit
    Join Date
    Oct 2011
    Location
    Ottawa, ON (area)
    Posts
    2,615
    Put a Msgbox... as the first executable line in Write_Item, i.e. right after Dim CurrentRow as integer, to confirm that the code never actually gets to the subroutine.

    You could also put one immediately before the Write_Item call to confirm it is actually getting there.

    Are you getting an error message of any kind?

    Are you sure the statement If rstComments!Relate_ID = relateID is evaluating to True?

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

Similar Threads

  1. Inserting records in multiple tables
    By Nikos in forum Database Design
    Replies: 8
    Last Post: 02-17-2012, 02:35 PM
  2. Mail Merge AC2007 DB(many-to-many) with MSWord
    By jhollingsh615 in forum Access
    Replies: 12
    Last Post: 10-07-2011, 04:42 PM
  3. Inserting multiple records into a table
    By New2Access in forum Programming
    Replies: 1
    Last Post: 07-07-2011, 09:18 PM
  4. Replies: 2
    Last Post: 05-03-2011, 01:02 AM
  5. Inserting records into tables with autonumber
    By LAazsx in forum Import/Export Data
    Replies: 1
    Last Post: 12-13-2010, 11:55 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