Fill in word forms using access

Access reports provide a flexible and easy-to-use tool for sharing data, but sometimes, it’s the wrong tool. For instance, you may find that you can’t exactly reproduce an existing paper form in Access, whereas you can in Word. Now, you might not care what the report (paper form) looks like, but perhaps management does. When this is the case, you may find it necessary to transfer Access data to Word forms. The good news is that Word and Access play well together.

Note:This information is also available as a download, which includes text files containing the VBA code from Listing A and Listing B.

The automated solution requires three pieces:

  • A method of identifying the Access data you want to transfer
  • A bit of VBA code to automate the process
  • A Word document that represents the form you need to fill.

We’ll work with existing data in the Northwind database (the sample database that comes with Access). Specifically, the example will transfer data from the Customers table, via a form, to the Word document shown in Figure A.

Figure A: The highlighted areas are text fields.

Creating the Word form

The Word form isn’t as difficult to create as it might look. The example form consists of five simple tables that contain form fields. In this context, a form is a document that contains fill-in blanks or form fields, in which you enter information. A field is a predefined cell for entering and storing information.

The form in Figure A uses five two-row tables to simulate a form. You don’t need the tables, but they help organize and manage the data. To insert a table, choose Insert from the Table menu and then choose Table. In the resulting Insert Table dialog box, enter the appropriate number of columns and rows (see Figure B). To create this form, you’ll need five tables as follows:

Columns Rows
2 2
2 2
1 2
4 2
2 2

Figure B: Identify the number of rows and columns in each table.

The example form also uses shading and text in the first row to distinguish between the heading and actual information. You can skip the formatting if you like; it isn’t critical to the technique. Alter the width of each cell column, using Figure A as a guide, if you like.

The example Word document contains a matching field for each column in the Northwind’s Customers table. You don’t have to accommodate each field; transfer just the data you need. However, you must associate a Word field with each underlying Access field that you want to copy to the Word form. To add the first field, complete the following steps in the Word form:

  1. Display the Forms toolbar by choosing Toolbars from the View menu and selecting Forms.
  2. In the document, click the table cell beneath the Customer Number heading.
  3. Click the Text Form Field button on the Forms toolbar.
  4. Double-click the field to display the Text Form Field Options dialog box.
  5. Rename the field fldCustomerID and click OK.

Repeat steps 2 through 5 to add a text field for each heading, using the following list to name each field:

Word field heading Field name Corresponding field in Access table
Customer Number fldCustomerID CustomerID
Customer fldCompanyName CompanyName
Contact fldContactName ContactName
Title fldContactTitle ContactTitle
Street Address fldAddress Address
City fldCity City
Region fldRegion Region
ZIP Code fldPostalCode PostalCode
Country fldCountry Country
Phone Number fldPhone Phone
Fax Number fldFax Fax

The field heading doesn’t have to match the field names. However, notice that the Word field names match the Access field names, with an additional fld prefix. It isn’t necessary to name the Word fields similarly to their corresponding Access fields, but doing so is self-documenting and simplifies your work.

After adding all the fields, click the Protect Form button. Doing so disables a number of features, which will keep casual users from altering your form. Then, save the form as CustomerSlip.doc and close it.

Identifying the Access data

The most common method you’ll probably use to identify a specific record is an Access form. To simply the example, use the existing Customers form in Northwind. If you’d rather not alter the actual object, use a copy or use the AutoForm wizard to generate a quick form based on the Customers table. When you have a form bound to the Customers table, add a command button to the form and name it cmdPrint, as shown in Figure C.

Figure C: The Print Customer Slip command button executes the VBA code that will pass Access data to the Word form.

With the form still in Design view, click the Code button to launch the form’s module. Add the code in Listing A to the module. The cmdPrint button’s Print event does all the work of copying data for the current customer in the Customers form to the Word document (CustomerSlip.doc).

Listing A

Private Sub cmdPrint_Click()

'Print customer slip for current customer.

Dim appWord As Word.Application

Dim doc As Word.Document

'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

Set doc = appWord.Documents.Open("C:WordFormsCustomerSlip.doc", , True)

With doc

.FormFields("fldCustomerID").Result = Me!CustomerID

.FormFields("fldCompanyName").Result = Me!CompanyName

.FormFields("fldContactName").Result = Me!ContactName

.FormFields("fldContactTitle").Result = Me!ContactTitle

.FormFields("fldAddress").Result = Me!Address

.FormFields("fldCity").Result = Me!City

.FormFields("fldRegion").Result = Me!Region

.FormFields("fldPostalCode").Result = Me!PostalCode

.FormFields("fldCountry").Result = Me!Country

.FormFields("fldPhone").Result = Me!Phone

.FormFields("fldFax").Result = Me!Fax

.Visible = True

.Activate

End With

Set doc = Nothing

Set appWord = Nothing

Exit Sub

errHandler:

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

End Sub

How it works

First, the code creates an instance of Word. If Word is already open, it uses the currently running instance. The current code uses the expression Err.Number <> 0 because Microsoft is notorious for changing error numbers from version to version. You might want to be more specific by changing 0 to 429 (or the appropriate error number for your version if different).

Next, the Open method identifies the Word form (document). In this case, that’s CustomerSlip.doc in the WordForms folder on the C: drive. The optional True value opens the file as read-only. Update the path to accommodate your system. In fact, you might consider moving the filename and path to constants in the General Declarations section. That way, you can more easily update the code if you change the filename or move it.

The With block copies the data from each Access field to its corresponding Word field. After copying all the data, the Visible and Activate methods display and then select the filled in Word form, as shown in Figure D.

Figure D: The form will look like this after all the data is copied and filled.

The error handling is minimal. Be sure to thoroughly test your production solution and accommodate all possible errors. The most common errors you’ll run into are a missing Word file, an incorrect path, or mismatched field names.

Filling multiple Word forms

Currently, the example works with only one record, the form’s current record. Sometimes, you’ll want to pass multiple records. Fortunately, it isn’t difficult to enhance the existing code to handle multiple records and forms, as shown in Listing B.

Listing B

Private Sub cmdPrint_Click()

'Print customer slip for current customer.

Dim appWord As Word.Application

Dim doc As Word.Document

Dim rst As ADODB.Recordset

'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

rst.Open Me.RecordSource, CurrentProject.Connection

'Cycle through records to fill Word form fields.

Do While Not rst.EOF

Set doc = appWord.Documents.Open("C:WordFormsCustomerSlip.doc", , True)

With doc

.FormFields("fldCustomerID").Result = rst!CustomerID

.FormFields("fldCompanyName").Result = rst!CompanyName

.FormFields("fldContactName").Result = rst!ContactName

.FormFields("fldContactTitle").Result = rst!ContactTitle

.FormFields("fldAddress").Result = rst!Address

.FormFields("fldCity").Result = rst!City

.FormFields("fldRegion").Result = rst!Region

.FormFields("fldPostalCode").Result = rst!PostalCode

.FormFields("fldCountry").Result = rst!Country

.FormFields("fldPhone").Result = rst!Phone

.FormFields("fldFax").Result = rst!Fax

.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

Instead of retrieving data from the actual form (using the Me identifier), this procedure uses a Recordset object to pass data from multiple records. Be sure to update the .FieldForm statements by referring to the recordset (rst!) instead of the Access form (Me!), as the previous procedure did.

Our example uses the form’s RecordSource property to retrieve data from the Access form’s underlying data source (the Customers table). Consequently, the form isn’t synchronized to the procedure, so the form’s current record never changes. We’re just using the form’s recordset and print button to keep the example simple. When applying this technique to your database, you can use any valid recordset source.

Notice that the code has two commented statements toward the end of the With block. Those are actions you might possibly want to take for each Word form. The first prints the completed form; the second saves the form to the current directory using the current record’s primary key value as the form’s name. You could use either or both. If you don’t save the current record, Word dumps it when the Do While loop processes the next record.

The downside is performance. If you’re working with thousands of records, this process will take a few minutes to complete.

Shortcut to Word forms

Filling a Word form with Access data can be a useful when your data is in Access and you must use Word’s formatting features to create just the right display. Fortunately, the process is simple, whether sharing one record or thousands.

Dear All,

I’m looking to program some sort of code, VBA, to export data from access 2010 to a word 2010 document which in it self represents a form. Here is the catch.

In access i have a specified name referring to the word document form. For example i have lots of forms A, B, C etc. SO i select form B it ones up form B, i then have to manually fill the form out, however access already contains all the necessary information. I.E System name, Number, Equipment Number etc.
So the question is, is there a way to export all the data from access to the word document pre specified into correct columns and rows in the word document?

I was thinking of using idetifiers such as: if line contains System ID: place space nad insert from System ID.

Could you at least point me in the right direction or provide a solution for me?

I know this is very poorly worded but my knowledge in access is very poor. Any help would be highly appreciated.

  • Remove From My Forums
  • Question

  • I found a «How do I…Dynamically fill Microsoft Word fields using Access Data?» from August 23, 2007.  This is the exact solution needed for a project at work, however, I’m using Access 2007 and Word 2007 and when I attempt to load the form, I
    receive: «Run-time error ‘3343’: Unrecognized database format….» I suspect that the code is written using another version of Windows as well as Access, as both referenced the Word document extension as .doc, and Access extension as .mdb.   The
    Access ’07 extension is .accdb, and Word ’07 is .docx. 

    Here is the VBA code I found, and modified to my particular data source.  Also, I’m using Windows XP and the DAO 3.6 Object Reference Library.

    Private Sub Document_Open()
    
      'Populate Provider dropdown field.
    
      Dim db As DAO.Database
    
      Dim rst As DAO.Recordset
    
      Dim strSQL As String
    
      Dim strPath As String
    
      Dim doc As Document
    
      Set doc = ThisDocument
    
      strSQL = "SELECT [Provider Name] FROM [Center Days of Operation] ORDER BY [Provider Name]"
    
      strPath = "C:80709_091209.accdb"
    
      'Update path to database file.
    
      Set db = OpenDatabase(strPath)
    
      Set rst = db.OpenRecordset(strSQL)
    
      Do While Not rst.EOF
    
        With doc.FormFields("ComboBox1").DropDown.ListEntries
    
          .Add Name:=rst(0)
    
        End With
    
        rst.MoveNext
    
      Loop
    
      Set db = Nothing
    
      Set rst = Nothing
    
    End Sub

    Please help. 


    iamh1

Answers

  • Hi iamh1,

    Got the same error, I am not sure what’s causing the error.

    I got it to work using ADO instead. Set reference to Microsoft ActiveX Data Object 6.0 Library.

    Then I use the UserForm’s Initialize event to populate the Combobox with the Access data.

    See for more info on the technique, below thread:

    http://www.fontstuff.com/vba/vbatut10.htm

    So in your case the code looks like this:

    Private Sub UserForm_Initialize()
        On Error GoTo UserForm_Initialize_Err
        
        Dim cnn As New ADODB.Connection
        Dim rst As New ADODB.Recordset
        
        cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                 "Data Source=C:80709_091209.accdb"
        rst.Open "SELECT [Provider Name] FROM [Center Days of Operation] ORDER BY [Provider Name];", _
                 cnn, adOpenStatic
        rst.MoveFirst
       
    
        With Me.ComboBox1
            .Clear
            Do
                .AddItem rst(0)
                rst.MoveNext
            Loop Until rst.EOF
        End With
    
    UserForm_Initialize_Exit:
        
        On Error Resume Next
        rst.Close
        cnn.Close
        Set rst = Nothing
        Set cnn = Nothing
        Exit Sub
    
    UserForm_Initialize_Err:
        MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
        Resume UserForm_Initialize_Exit
    
    End Sub

    Hope this helps,


    Daniel van den Berg | Washington, USA | «Anticipate the difficult by managing the easy»

    • Marked as answer by

      Wednesday, February 15, 2012 11:56 PM

  • Yes, I thought you are using FormFields, as you are referring to them in your code, so that was misleading.

    Sorry about that.

    So below example on how to refer to ActiveX Objects (not residing on a Form, in that case it will be different) but in Document (InlineShape);

    Sub test()
    
    
    On Error GoTo Initialize_Err
        
        Dim cnn As New ADODB.Connection
        Dim rst As New ADODB.Recordset
        
        Dim oCtl As InlineShape
        Dim oTB
        
        cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                 "Data Source=C:TestDBdatabase2.accdb"
        rst.Open "SELECT [Test] FROM [tblTest] WHERE [ID]=3;", _
                 cnn, adOpenStatic
        
        rst.MoveFirst
        
    
            Do
               ' loop through all ActiveX Textboxes in document
               For Each oCtl In ActiveDocument.InlineShapes
                 ' find txtAgencyName
                 If oCtl.OLEFormat.Object.Name = "txtAgencyName" Then
    
                      Set oTB = oCtl.OLEFormat.Object
                      ' assign value
                      oTB.Text = rst!test
    
                End If
                
                Next
    
                rst.MoveNext
             
             Loop Until rst.EOF
    
        
    Initialize_Exit:
        
        On Error Resume Next
        rst.Close
        cnn.Close
        Set rst = Nothing
        Set cnn = Nothing
        Exit Sub
    
    Initialize_Err:
        MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
        Resume Initialize_Exit
    
    End Sub
    

    Hope this helps,


    Daniel van den Berg | Washington, USA | «Anticipate the difficult by managing the easy»

    • Marked as answer by
      iamh1
      Friday, February 17, 2012 6:21 PM

Building on the code in the question and the background question…

Word can duplicate the content of a bookmark using REF field codes. Since form fields also use bookmark identifiers, this will work with existing form fields as well as bookmarked content. REF fields can be inserted directly, if a person is familiar with doing so OR by inserting a cross-reference to the bookmark.

Referring to the work-around for inserting more than 255 characters, in this case it will be necessary to also place a bookmark around the range being inserted and to update the REF fields so that they mirror the bookmark content throughout the document. The modified section of code is below.

'Declarations to be added at the beginning of the procedure
Dim fld As Word.Field
Dim bkmName As String

'Name of form field, bookmark to be added and text in REF field code
bkmName = "txtReasonforReward"     

'Existing code
If doc.ProtectionType <> wdNoProtection Then
   doc.Unprotect
End If
Set rng = doc.Bookmarks(bkmName).Range
rng.MoveStart wdCharacter, -1
x = rng.Characters.First
rng.FormFields(1).Delete
rng.Text = x & Me![Reason for Reward]

' New code
'Leave that single character out of the range for the bookmark
rng.MoveStart wdCharacter, 1
'Bookmark the inserted content
doc.Bookmarks.Add bkmName, rng
'Update fields so that REF's pick up the bookmark content
For Each fld In doc.Fields
    If fld.Type = wdFieldRef Then
        fld.Update
    End If
Next

doc.Protect wdAllowOnlyFormFields, True

This approach will get a bit unwieldy if it needs to be applied to many fields. It might make sense to do something like write the bookmark names to a Tag property of the controls in the Access form then loop the controls to pick up bookmark name and data from the control, rather than writing each out explicitly — but this is just a thought for the future.

All that being said, the «modern» way to achieve this is to work with content controls instead of form fields/bookmarks. Content controls do not have the 255 character limit, the document can be protected as a form, multiple content controls can have the same title (name) and/or tag. Furthermore, content controls can be «mapped» to a Custom XML Part stored in the document so that changing the content of one will change the content of another. Trying to describe all that would go beyond what should be in an «answer», here, but is all publicly available by searching the Internet.

Personally, if this were my project and knowing what I know of it: If form fields are not required in the document (no user input via the fields is expected) I would use bookmarks and REF fields, only.

  • Home
  • Forum
  • Access Forums
  • Programming
  • Filling Word Form Using Access Data and SQL Recordset

  1. Filling Word Form Using Access Data and SQL Recordset

    Alright. Frankly this is over my head. I’ve tried to read-up on the web and have attempted to customize some code I found for the subject. I’m getting the following error message: «3061Too few parameters. Expected 1.»

    I believe this means that for some reason txtSurveyID (a control on my Access form) is not being «passed» to the SQL. This code is definitely not clean and I’ve commented out some stuff that was in it from the original source not thinking I really need it. And there is still probably some stuff that is not needed. What am I missing here? Is my syntax for wrong in the SQL statement? The corresponding field in the Word form is obviously «wrdSurveyID».

    Code:

    Private Sub cmdGetFullSiteReport_Click()
    
    
        Dim DOC_PATH As String
        Dim DOC_NAME As String
        Dim appWord As Word.Application
        Dim doc As Word.Document
        Dim rst As DAO.Recordset
        Dim strSQL As String
        'Dim SurveyID As String
        
        DOC_PATH = "C:aaaprojectsbmp_implementation_survey2012databasereports"
        DOC_NAME = "20130109_bmp_imp_full_site_report_template.doc"
        'SurveyID = Me!txtSurveyID
        
        On Error Resume Next
    
    
        Set appWord = GetObject(, "Word.application")
            If Err = 429 Then
                Set appWord = New Word.Application
                Err = 0
            End If
        With appWord
            Set doc = .Documents(DOC_NAME)
                If Err = 0 Then
                    If MsgBox("Do you want to save the current document " _
                    & "before updating the data?", vbYesNo) = vbYes Then
                    .Dialogs(wdDialogFileSaveAs).Show
                    End If
                    doc.Close False
                End If
        
    On Error GoTo ErrorHandler
        
        Set doc = .Documents.Open(DOC_PATH & DOC_NAME, , True)
    
    
        If Not IsNull(Me!txtSurveyID) Then
            strSQL = "SELECT tblSurveySites.strSurveyID, tblSurveySites.dtmSurveyDate, tblSurveySites.dtmSurveyTime, tblSurveySites.strSurveyorsFullName, tblSurveySites.strXCoordinate, tblSurveySites.strYCoordinate, tblSurveySiteLocation.strCountyName, tblSurveySiteLocation.strFeatureName, tblSurveySiteLocation.strRoadName, tblSurveySiteLocation.strRiverBasin " & vbCrLf & _
            "FROM tblSurveySites INNER JOIN tblSurveySiteLocation ON tblSurveySites.strSurveyID = tblSurveySiteLocation.strSurveyID " & vbCrLf & _
            "WHERE (((tblSurveySites.strSurveyID)= [txtSurveyID]));"
            Set rst = CurrentDb.OpenRecordset(strSQL)
    
    
        'ElseIf Not rst.EOF Then
            'strReportsTo = Nz(rst.Fields(0).Value)
            'rst.Close
        End If
    
    
        With doc
            .FormFields("wrdSurveyID").Result = Nz(Me!strSurveyID)
        End With
    
    
        .Visible = True
        .Activate
    
    
    End With
    
    
        Set rst = Nothing
        Set doc = Nothing
        Set appWord = Nothing
        
    Exit Sub
    
    
    ErrorHandler:
    MsgBox Err & Err.Description
    
    
    End Sub


  2. Which line triggers the error?


  3. I believe this means that for some reason txtSurveyID (a control on my Access form) is not being «passed» to the SQL.

    You are correct.
    If you add a line «Debug.Print strSQL» before the line «Set rst = CurrentDb.OpenRecordset(strSQL)», you can see in the immediate window if the SQL line is formed correctly.

    Your WHERE clause is

    Code:

     "WHERE (((tblSurveySites.strSurveyID)= [txtSurveyID]));"

    Try the debug statement first

    Then change the line to

    Code:

     "WHERE (((tblSurveySites.strSurveyID)= " & Me.txtSurveyID & "));"

    Check the debug statement

    Also, you shouldn’t have (don’t need) «vbCrLf» in the strSQL string.


  4. Same and new errors

    Thanks for the feedback. With respect to identifying the line of code that triggers the error — pardon my ignorance — but how do I do that?

    I think I tried what you suggested John and it was still producing the «3061Too few paramerters. Expected 1.» error message.

    Code:

    strSQL = "SELECT tblSurveySites.strSurveyID, tblSurveySites.dtmSurveyDate, tblSurveySites.dtmSurveyTime, tblSurveySites.strSurveyorsFullName, tblSurveySites.strXCoordinate, tblSurveySites.strYCoordinate, tblSurveySiteLocation.strCountyName, tblSurveySiteLocation.strFeatureName, tblSurveySiteLocation.strRoadName, tblSurveySiteLocation.strRiverBasin FROM tblSurveySites INNER JOIN tblSurveySiteLocation ON tblSurveySites.strSurveyID = tblSurveySiteLocation.strSurveyID WHERE (((tblSurveySites.strSurveyID)= " & Me.txtSurveyID & "));"

    I then remembered that in a few INSERT statements I used single and double quotes to refer to a control on a form. So I tried that.

    Code:

    strSQL = "SELECT tblSurveySites.strSurveyID, tblSurveySites.dtmSurveyDate, tblSurveySites.dtmSurveyTime, tblSurveySites.strSurveyorsFullName, tblSurveySites.strXCoordinate, tblSurveySites.strYCoordinate, tblSurveySiteLocation.strCountyName, tblSurveySiteLocation.strFeatureName, tblSurveySiteLocation.strRoadName, tblSurveySiteLocation.strRiverBasin FROM tblSurveySites INNER JOIN tblSurveySiteLocation ON tblSurveySites.strSurveyID = tblSurveySiteLocation.strSurveyID WHERE (((tblSurveySites.strSurveyID)= ' " & Me.txtSurveyID & " '));"

    This produce the following error message «2465Microsoft Office Access can’t find the field ‘strSurveyID’ referred to in your expression.»

    Not sure what that’s all about. The field most definitely exists. Any guidance would be appreciated.

    Thanks,
    David


  5. Debugging: Read the first two paragraphs after the intro at Chip Pearson’s site — http://www.cpearson.com/excel/DebuggingVBA.aspx
    (Don’t use the STOP command in code)

    In the code, click anywhere in this line

    DOC_PATH = «C:aaaprojectsbmp_implementation_survey2012da tabasereports»

    then press the «F9». Go back to the form and run the code. You should be dumped back into the IDE.
    Press the «F8» key to execute one line at a time.

    Does table «tblSurveySites» have a field named «strSurveyID»?


  6. The apostrophe delimiter is need for criteria when field is text datatype. For date/time use # delimiter.


  7. Debug information

    Okay, looks like the error is occurring with this line:

    Code:

    .FormFields("wrdSurveyID").Result = Nz(Me!strSurveyID)

    And this would be where me fumbling in the dark starts to really become a factor. This was part of the code I’ve attempted to modify from various online sources. I forget what Nz means, but now reflecting on the error I guess it’s because there is no «strSurveyID» on my form. What I need is for this word form field (wrdSurveyID) to be set equal to «strSurveyID» from the strSQL. How to I refer to that value?


  8. I now see several things to correct.

    Code:

        With doc
            .FormFields("wrdSurveyID").Result = Nz(Me!strSurveyID)
        End With

    «Me» is a shortcut to «Forms!FormName» and is used on a form. You cannot refer to a query in code using «ME». You have to use the recordset reference, in this case «rst»

    You are also missing part of the NZ() function. From Help:

    The Nz function is useful for expressions that may include Null values. To force an expression to evaluate to a non-Null value even when it contains a Null value, use the Nz function to return a zero, a zero-length string, or a custom return value.

    You are missing the «ValueIfNull» part.

    Code:

    .FormFields("wrdSurveyID").Result = Nz(rst!strSurveyID,ValueIfNull)

    «ValueIfNull» should be replaces with what you want to be returned if «strSurveyID» is NULL.

    For Instance, if «strSurveyID» is a Long Int, you might want to return a Zero. It would look like this

    Code:

    .FormFields("wrdSurveyID").Result = Nz(rst!strSurveyID,0)

    If «strSurveyID» is a string, you might want to return custom text. It would look like this:

    Code:

    .FormFields("wrdSurveyID").Result = Nz(rst!strSurveyID,"Not found. Please re-enter")

    You might try

    Code:

        With doc
            .FormFields("wrdSurveyID").Result = Nz(rst!strSurveyID,0)
        End With

    BUT, the main problem is you opened the recordset (rst) , and didn’t check to see if there were records returned and handle the error before it gets to the «with DOC» statement

    Code:

            strSQL = "SELECT tblSurveySites.strSurveyID, tblSurveySites.dtmSurveyDate, tblSurveySites.dtmSurveyTime, tblSurveySites.strSurveyorsFullName, tblSurveySites.strXCoordinate, tblSurveySites.strYCoordinate, tblSurveySiteLocation.strCountyName, tblSurveySiteLocation.strFeatureName, tblSurveySiteLocation.strRoadName, tblSurveySiteLocation.strRiverBasin " & vbCrLf & _
            "FROM tblSurveySites INNER JOIN tblSurveySiteLocation ON tblSurveySites.strSurveyID = tblSurveySiteLocation.strSurveyID " & vbCrLf & _
            "WHERE (((tblSurveySites.strSurveyID)= [txtSurveyID]));"
            Set rst = CurrentDb.OpenRecordset(strSQL)
    'not check for records
     If rst.bof and rst.EOF then
        'do something
        ' maybe exit the sub???
    end if

    Or you could check to see if rst!strSurveyID is NULL and handle the error someway.
    You could do this:

    Code:

        With doc
            If IsNull(rst!strSurveyID) then
               'strSurveyID is NULL
               ' do something
            ELSE
            .FormFields("wrdSurveyID").Result = rst!strSurveyID
           End If
        End With

    (don’t have to do both)

    Sorry this is so long….


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

Similar Threads

  1. Replies: 15

    Last Post: 10-16-2012, 03:57 PM

  2. Replies: 1

    Last Post: 10-05-2012, 07:57 AM

  3. Replies: 1

    Last Post: 06-03-2012, 05:21 PM

  4. Replies: 6

    Last Post: 09-08-2011, 05:17 PM

  5. Replies: 2

    Last Post: 08-08-2011, 10:23 AM


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules

Using a loop to fill Word forms using Access VBA —

I’m using a code to open the Word document using the access code and then fill out the form field .
I feel there is no problem with the code, but I want to change it so that the text box takes multiple IDs (one ID in each line) and displays the remaining code on each code, I split and others Looking for stuff, I have searched but I have no success.
I tried to add code so that after saving this field it can automatically save the form, will it work with many IDs?
Here is the entry I am using ATM:

  In the form of a slow app word word. Apps as the Dyke Doc Word Restart the error on the document Resume Err.Clear Set AppWord = GetObject (, "Word.Application") if Err.Number & lt; & Gt; 0 then set AppWord = New Word.Application End if set Doctor = appWord.Documents.Open ("C:  users " & Environ $ ("username") & amp; " Desktop  Form.doc", , True) with doctor .formfield ("text4"). Results = DLookup ("[name]", "[que]", "[qu]! [Id] =" & [id2]) appWord.Visible = True .Activate End Set Doc = None Set With App - Word = Nothing goes out all errHandler: MsgBox Err.Number & amp; ":" & amp; Err.Description End sub   

Edit: iigot

  Split (ID2.Value, ",") to work.   

However, after every new line I tried to make it split value but I still do not know.
I tried the environment. New line, vbCrLf, vbCr, vbNewLine and vbLf none of them worked

  split (ID2.Value, vbCrLf)   

Good job! After that you can call the stars using X (0), pre (1) etc.

Comments

Post a Comment

Popular posts from this blog

php - which is the best way to order by count from multiple tables? -

I am thinking about these questions and I have found a job that lists all the users in the table Calculate for user and their posts photos and videos . And choose to look at these codes by using asc or DESC . I have tried both of them but seeing that it is faster than joining the sub-query I want to know differently between these questions, sometimes due to being involved, a sub-query occurs only for two tables Is Best In For? Is this the best for my work? Or you can suggest another better solution SUB-QUERY select the user *, (Select the count (*) from the post where post.userid = user.id) Postcount (Select Count from photo (*) where photo.userid = user.id) photoCount, (Choose from video count (*) where video .userid = user.id) $ starrow 20 join SELECT u.id by userCount postCOunt descend , COUNT (DISTINCT p.id) as a postcount, COUNT (DISTINCT ph.id) AS PhotoCount, COUNT (DISTINCT v.id) URAD = PO PO on UED PH osirid on pH = u.id VID ViUIDID = Postcount LIM

Verilog Error: output or inout port "Q" must be connected to a
structural net expression -

I get the error every time, I try to compile. I'm not sure why anyone can help is? I'm new to verilog. Module D_FF (clerk, d, reset_n, q); Input D, Clack, reset_en; Output Q; reg Q; lab4_gdl f1 (.lk (~ clk), d (d), .q.m (qm)); lab4_GDL f2 (.Clk (Clk), D (QM), .Q (Q)); Always start at @ (posedge clk, neggeous reset_n) (Reset_n == 0) Q & lt; = 0; Other questions & lt; = D; Edit End: The problem is what we are asking to do: In this section, you apply the memory / registration circuit on the AlterEdie 2 board. will do. The circuit has the following specifications: The present value of swift SW15-0 on the D2 board should be shown in four hexadecimal four sections of HEX3-0. This part of the circuit will be combination logic. To use an active-less asynchronous reset and KEY1 to use KEY0 as the clock input, you must store SW15-0in in a 16-bit register in the value The register should be enabled to have a 16-bit positive edge, which uses the embedded D flip-flo

how to use xmgrace to plot histogram from a plot -

Image

I have a text file with two columns (say, sample1.dat): first column 1 to 5000 and second Columns are 5000 degrees angle, in which degrees range from -180 to 180 degrees. Using the "Xmgrace sample1.dat" command, give me a bizarre diagram vs. serial no met. To get the histogram from the plot, I did the following in Grace's pop-up window: Data -> Trasnformation - & gt; Histogram In a new pop-up window called 'Grace: Histogram', I selected the source graph, but did not make any selection in the destination graph as mentioned in any maintenance tutorial. After starting in -180, close as 180 and close the number of bins as 5 and then in the window, by killing the 'Accept' command, I got the following error message: < P> [Error] Please select a source and destination article Help me get the histogram from plot. I want to use xmgrace to plot a histogram. I know how to plot it using some of the most widely used plotting tools like gnuplot a

Mosaddeq Aziz


  • #1

Hi,

I have a word document with 8 form fileds. I need to fill those fields with
data from access and generate the word document. One of the office is 2003
and another is Office XP. Can anyone help me with the coding.

regards,

Mosaddeq Aziz

Advertisements

Doug Robbins — Word MVP


  • #2

Take a look at the information referred to in the following post from
fellow MVP, Albert Kallal.

Quote

Actually, use my merge sample. it don’t give that warning, and you don’t
have to change registiry stuff etc.

The sample I have can be found here:
http://www.members.shaw.ca/AlbertKallal/msaccess/msaccess.html

What is nice/interesting about my sample is that is specially designed to
enable ANY form with ONE LINE of code….

Thus, each time you build a new form, you can word merge enable it with
great ease.

Make sure you read the instructions from above, and you should eventually
get to the follwoing page
http://www.members.shaw.ca/AlbertKallal/wordmerge/page2.html

Note that the merge can also use a query, and thus you don’t have to merge
just «one» record..

After the merge occurs, you get a plain document WITHOUT any merge fields,
and this allows the end user to save, edit, or even email the document
(since the merge fields are gone after the merge occurs).

Give the above a try.

Albert D. Kallal (Access MVP)
Edmonton, Alberta Canada
(e-mail address removed)
Unquote


Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins — Word MVP

Mosaddeq Aziz


  • #3

excellent database to work with.

thanks for it.

Advertisements

  • #4

WordMerge

Hi there,

Just launched my WordMerge free solution for your review.

http://www.ndados.com

Regards,
Filipe Freire

Want to reply to this thread or ask your own question?

You’ll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.


Ask a Question

Couldn’t find data form dialog box in Excel 2007 3 Dec 30, 2006
Help vba form, please ! 1 Apr 16, 2010
Word VBA for deleting Selected Row 0 Feb 10, 2020
Problem in Word VBA, Please Help 0 Sep 17, 2014
Retrieve data from Access database and fill data in form 0 Aug 29, 2017
show data in access 1 Feb 17, 2009
Word 2002 (sorry) 16 Sep 12, 2014
enter data in access 12 Mar 1, 2009

  • #1

Sorry about the late Friday entry:

I have a form in Access that I use to create a word document (I created form fields in word and filled them from VBA code in Access). Everything works just fine. Now I am trying to create a table in Word that’s filled with my Access fields. I am having trouble figuring this out. The Access fields are from a continuous report, so I’m guessing it has to be some sort of loop as well.

can someone please help

Thanks so much

Uncle Gizmo


  • #3

Do you have any experience using this VBA? I have been at this all day and just can’t seem to get it to work. below is my code:

Set rs = CurrentDb.OpenRecordset(«tbl_PHOTO», dbOpenDynaset)
Selection.GoTo What:=wdGoToBookmark, Name:=»fldPhoto»
With rs
Do While Not .EOF
Selection.TypeText Text:=![Number]
Selection.MoveRight Unit:=wdCell
Selection.TypeText Text:=![Location]
Selection.MoveRight Unit:=wdCell
.MoveNext
Loop
.Close
End With
Selection.SelectRow
Selection.Rows.Delete

JHB

Have been here a while


  • #4

There must be more code as that!
And where do you’ve the code, in MS-Access or Word?
What problem do you’ve, some error message or …?

  • #5

the above code was put into my already existing code in access. Since that code works just find, and is lengthy, I just added the part of the code that included the loop. It does two things;

it will either do nothing, or (when I tweak it), it will output the first continuous record and wont stop. So it will give me the same record forever unless I close the word document. It seems to not be looping or stopping after the loop.

The_Doc_Man


  • #6

This seems like you are dealing with extraneous issues.

Let’s get down to a few simple ideas. Here is the overview. You can look up the details online.

You open a Word.Application object using

Set {object-variable} = CreateObjects( «Word.Application» )

Open a document using

{object-variable}.Documents.Open {filename}

You can make that the active document, which means the ActiveDocument shortcut works for you.

You find Word tables in the Tables collection of the current document. Each table is a collection of Rows, which in turn is a collection of Columns. (OR you can do the collection of Columns as a collection of Rows — the interface works either way). To find a given cell in a table requires something like

Set {Word.Cell-object} = ActiveDocument.Tables(n).Row(j).Column(k)

From there, you have the cell pointer and can start playing with the properties of that cell. So the loop might at worst be one loop through the Documents(n) collection to find the document you want (and make it active) followed by a loop through that document’s Tables(n) collection to find the right table. After that, your loop is a nested loop through the Rows(j).Columns(k) collection to see individual cells. The innermost part of that loop is where you would diddle with the cell’s attributes.

If your problem is that you always get the first record, your recordset needs tweaking. If you have a way to tell from your recordset where a given value should go, you could do the OTHER kind of loop — read through the recordset, extract the Row and Column number from data in the recordset, and randomly access the cells based on knowing the row and column number.

Your only REAL problem with this is that somewhere you must decide how to store the data in the recordset to define where it goes in the table, or must otherwise define a formula in your Word code that computes where the data goes. But somehow you have to decide your layout before you actually code that VBA segment.

  • #7

I figured it out!! Wow that took some work but here is the code for anyone interested. I was missing the first line in the code:

Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset(«tbl_PHOTO»)

.FormFields(«fldPhoto»).Result = «****»
Selection.GoTo What:=wdGoToBookmark, Name:=»fldPhoto»
With rs
Do While Not rs.EOF
Selection.TypeText Text:=![Number]
Selection.MoveRight Unit:=wdCell
Selection.TypeText Text:=![Location]
Selection.MoveRight Unit:=wdCell
rs.MoveNext
Loop
rs.Close
End With
Selection.SelectRow
Selection.Rows.Delete

Like this post? Please share to your friends:
  • Fill in word document from access
  • Films starting with the word the
  • Fill in with the correct word you should buy
  • Films beginning with the word the
  • Fill in with the correct word personal data