Fill in word form from 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.

Table of Contents

  • 1 How do I fill Word form fields with access data?
  • 2 How do I make a Word document accessible for multiple users?
  • 3 How do I add alternate text to an image?
  • 4 What is alternative text explain with an example?
  • 5 How do you describe a visual image?
  • 6 What are the example of visual?
  • 7 What are the 5 sensory details?
  • 8 What is a good example of imagery?

How do I fill Word form fields with access data?

In the document, click the table cell beneath the Customer Number heading. Click the Text Form Field button on the Forms toolbar. Double-click the field to display the Text Form Field Options dialog box. Rename the field fldCustomerID and click OK.

How do I insert Access data into Word?

Click the Office button and click Word options. In the resulting window, click Customize. Choose All Commands from the Choose Commands From control’s Dropdown list. Select Insert Database and then click OK.

How do I make a Word document accessible for multiple users?

How to Co-Edit a Document in Word 2016

  1. Save your Word document to OneDrive or a SharePoint Online.
  2. Click the Share button in Word and then enter one or more email addresses of people you want to share with.
  3. Set their permissions to “Can edit” (selected by default).

Can 2 people edit a document in SharePoint?

When a user wants to work on a document in Word, PowerPoint, OneNote, Visio or one of the Office Web Apps, they open it from SharePoint Server, as usual. If another user already has the document open, both users can edit the document at the same time.

How do I add alternate text to an image?

Add alternative text to an image

  1. Insert the picture you want to use into the document.
  2. Right-click the picture, and then, in the menu that pops up, click Format Picture.
  3. In the “Format Picture” pane, click .
  4. Click the arrow next to Alt Text to expand the alternative text options.
  5. In the “Description” field, enter a description of the image.

What is a text alternative?

Alternative text, or “alt text” describes the content of images, graphs and charts. It should be added to every image that conveys meaning in instructional and communications materials including Canvas sites, word processing documents, and slide presentations.

What is alternative text explain with an example?

Alt text (alternative text) is a word or phrase that can be inserted as an attribute in an HTML (Hypertext Markup Language) document to tell Web site viewers the nature or contents of an image. The alt text appears in a blank box that would normally contain the image.

What is a visual description?

Visual descriptions provide information about the visual appearance of spaces, objects, people, and more. The term “visual description” can explain when someone describes the visual context of a location, person, or space in real time, and it may also be used in reference to image and audio descriptions.

How do you describe a visual image?

Here are some adjectives for visual imagery: otherwise black, intensely brilliant, deficient, constructive, ready, concrete, preferred, actual, violent, internal, strong, definite, splendid, powerful, simple, brilliant, black. You can get the definitions of these adjectives by clicking on them.

What are the 7 types of imagery?

There are seven distinct types of imagery: visual, auditory, olfactory, gustatory, tactile, kinesthetic and organic.

What are the example of visual?

The definition of a visual is a film clip or image used to illustrate a story or a message. An example of a visual is the short clip from an old news broadcast. A picture, chart, or other presentation that appeals to the sense of sight, used in promotion or for illustration or narration.

What are 5 types of imagery?

There are five main types of imagery, each related to one of the human senses:

  • Visual imagery (sight)
  • Auditory imagery (hearing)
  • Olfactory imagery (smell)
  • Gustatory imagery (taste)
  • Tactile imagery (touch)

What are the 5 sensory details?

Sensory imagery explores the five human senses: sight, sound, taste, touch, and smell.

What is a imagery poem examples?

Fluttering and dancing in the breeze. This is a very good example of imagery. We can see the ‘vales and hills’ through which the speaker wanders, and the daffodils cover the whole landscape. The poet uses the sense of sight to create a host of golden daffodils beside the lake.

What is a good example of imagery?

Common Examples of Imagery Sound: The concert was so loud that her ears rang for days afterward. Sight: The sunset was the most gorgeous they’d ever seen; the clouds were edged with pink and gold. Smell: After eating the curry, his breath reeked of garlic. Touch: The tree bark was rough against her skin.

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 am experiencing difficulties filling form fields in a Word template with data from an Access database.

    Here is my code:

    Private Sub cmdExport_Click()
    ‘Print data for current App Number.
    Dim wordApp As Word.Application
    Dim wordDoc As Word.Document
    Set wordApp = New Word.Application
        With wordApp
        wordApp.Visible = True
        Set wordDoc = .Documents.Open(«C:Documents and SettingsuserDesktopDoc1.dotx», , False)
            With wordDoc
            wordDoc.FormFields(«fldAppNumber»).Result = Me!AppNum
            wordDoc.FormFields(«fldAgent»).Result = Me!Agent
            .Visible = True
            .Activate
            End With
        End With
    End Sub

    Word opens and loads the required document, but the fields do not fill. I receive the following error message:

    «Run-time error ‘5941’: The requested member of the collection does not exist»

    Can anyone help, please?

Answers

  • Dave,

    «… in design mode.»  I suspect that you may be confusing formfields with ContentControls.  Formfields are inserted using the Legacy Tools gallery.  This is the bottom right control in the Developer>Controls group.


    Greg Maxey Please visit my website at: http://gregmaxey.mvps.org/word_tips.htm

    • Marked as answer by

      Tuesday, May 24, 2011 12:53 PM

Hello I am having trouble with trying to auto fill a word document with data that is calculated from my MS Access form.
I have been following along with this Youtube video: https://www.youtube.com/watch?v=k176qcg-YCo and when I run the code it opens word but it gets stuck in a loop, I believe. The function is called when the button is clicked, the code is provided below. Any help is highly appreciated!

Function fillwordform()
Dim appword As Word.Application
Dim doc As Word.Document
Dim Path As String

On Error Resume Next
Error.Clear

Set appword = GetObject(, "word.application")
If Err.Number <> 0 Then
Set appword = New Word.Application
appword.Visible = True
End If
Path = "C:UsersJayDocumentsMonthly Update.docx"
Set doc = appword.Documents.Open(Path, , True)
With doc
    .FormFields("ItmRec").Result = Me.NVCItmRcv

appword.Visible = True
appword.Activate
End With

Set doc = Nothing
Set appword = Nothing

End Function

The «ItmRec» is the name of the text box im trying to fill in Word and the «Me.NVCItmRcv» is the name of the box that I want to pull the number from and put in the text box. If you need anymore details or anything please let me know! Again highly appreciate any help!

  • #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

fmackay


  • #1

Hi,

I am trying to fill fields on a Word form from an Access db — I found
this page: http://msdn2.microsoft.com/en-us/library/aa140082(office.
10).aspx
and used this code — successfully. But I have now moved onto a machine
with slightly newer versions of Access and VB, and now get error 91 —
object variable or with block variable not set at the line
Set doc = .Documents.Open(DOC_PATH & DOC_NAME, , True)

The machine where the code worked has Access 2002 SP2 and VB 6.3.8863,
the one I’m using now where the code breaks has Access 2002 SP3 and VB
6.4.8869; they probably have slightly different versions of Word, too,
but both Word 10.

The relevant code is:

Const DOC_PATH As String = «<path>»
Const DOC_NAME As String = «<filename>»

Dim appWord As Word.Application
Dim doc As Word.Document
Dim rst As ADODB.Recordset

On Error Resume Next

Set appWord = GetObject(, «Word.application»)

If Err = 429 Then
Set appWord = New Word.Application
Err = 0
End If

With appWord

On Error GoTo ErrorHandler

Set doc = .Documents.Open(DOC_PATH & DOC_NAME, , True)

Set rst = New ADODB.Recordset

Any ideas?

Many thanks,

Finlay Mackay

Advertisements

Perry


  • #2

Go into VBE and check menu: Tools | References
whether there are libraries reported «MISSING» in the references.
Write them down somewhere … (or make a screendump)
Uncheck these missing references, validate the dialog and retry.

If this doesn’t work, bring up the very same reference dialog, and from the
note that you made (or the screendump), look for a more recent version.

Kindly repost if this doesn’t work.

Krgrds,
Perry

fmackay


  • #3

Go into VBE and check menu: Tools | References
whether there are libraries reported «MISSING» in the references.
Write them down somewhere … (or make a screendump)
Uncheck these missing references, validate the dialog and retry.

If this doesn’t work, bring up the very same reference dialog, and from the
note that you made (or the screendump), look for a more recent version.

Kindly repost if this doesn’t work.

Hi,

There are no missing libraries, and the same ones are checked on both
machines. Although I suppose I can’t assume the libs are identical
despite them having the same names; I can see 6 different libs all
calling themselves «Visual Basic for Applications» after all (it
appears I am using the same one of these on both machines though)

cheers,

Finlay

Perry


  • #4

Ok, let’s bring in some phasing and see what problems

If you were to skip using the active instance of Word (the GetObject
instantiating) and use
a brand new instance of Word

Replace this

Set appWord = GetObject(, «Word.application»)
If Err = 429 Then
Set appWord = New Word.Application
Err = 0
End If
With appWord
On Error GoTo ErrorHandler
Set doc = .Documents.Open(DOC_PATH & DOC_NAME, , True)

by
Set appWord = New Word.Application
With appWord
On Error GoTo ErrorHandler
Set doc = .Documents.Open(DOC_PATH & DOC_NAME, , True)
‘…etc
End With

Is wdApp instantiated and can you get object variable «doc» instantiated as
well …?

fmackay


  • #5

Ok, let’s bring in some phasing and see what problems

If you were to skip using the active instance of Word (the GetObject
instantiating) and use
a brand new instance of Word

Replace this

by
Set appWord = New Word.Application
With appWord
On Error GoTo ErrorHandler
Set doc = .Documents.Open(DOC_PATH & DOC_NAME, , True)
‘…etc
End With

I tried this already, «Set appWord = New Word.Application» does start
a new WINWORD.EXE process but I can’t seem to do anything with it, eg
if I follow that line with «appWord.Visible = True» I don’t get a Word
window appearing.

Is wdApp instantiated and can you get object variable «doc» instantiated as
well …?

Not quite sure what you mean here, I’m afraid I’m complete beginner
with VB

cheers

Finlay

Perry


  • #6

I tried this already, «Set appWord = New Word.Application» does start

a new WINWORD.EXE process but I can’t seem to do anything with it, eg
if I follow that line with «appWord.Visible = True» I don’t get a Word
window appearing.

That’s strange.

Let’s see whether yr system allows you to do something completely basic as
in:

sub testingword()
Dim wdapp as new word.application
dim doc as word.document
wdapp.visible = true
set doc = wdapp.documents.add
end sub

Do you see the newly created document?

Advertisements

fmackay


  • #7

That’s strange.

Let’s see whether yr system allows you to do something completely basic as
in:

sub testingword()
Dim wdapp as new word.application
dim doc as word.document
wdapp.visible = true
set doc = wdapp.documents.add
end sub

Do you see the newly created document?

This breaks at line «wdapp.visible=true» with error 80040155
«automation error — interface not recognised».

Dim wdapp As Word.Application
Set wdapp = New Word.Application

breaks at the second line with the same error, while

Dim wdapp As Object
Set wdapp = CreateObject(«Word.Application»)

gives error 424 «object required»

Trying Excel instead of Word doesn’t work either — I think there’s
something wrong with the office installation on this machine and I
probably need to call our IT dept in.

Many thanks for your help up to this point,

Finlay

Advertisements

Perry


  • #8

Your MS Office installation got corrupt.
I would advise a full re-installation.

If it concerns an enterprise rollout of Office, you will need to talk to the
IT ops department for this.


Krgrds,
Perry

System:
Vista/Office Ultimate
VS2005/VSTO2005 SE

  • Home
  • Forum
  • Access Forums
  • Programming
  • Fill in Word Text Form Fields from multiple Access forms

  1. Fill in Word Text Form Fields from multiple Access forms

    Hello,

    I’m currently trying to fill Text Form Fields in Word from Access data.
    This works as long as I use the data of the form where the command button is located. In other words as long as I refer to the data with «Me!…»

    However, I also need to include data from other forms. I thought this would be very simple but the values aren’t copied. In the example below, the last line that starts with «.FormFields» — .FormFields(«Uparam_pH»).Result = Form!Dataanalyse_urineparam!pH — doesn’t seem to work.

    Anyone have an idea on what I might need to add to my code to make it work?

    Thanks in advance

    Private Sub Command457_Click()

    ‘Print to word’.
    Set appWord = CreateObject(«Word.Application»)
    ‘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(«H:DRAFT BL — UR — VITR.docx», , True)
    With doc
    .FormFields(«Geg_Verslagnr»).Result = Me!Dossier_Nummer
    .FormFields(«Geg_Notitienr»).Result = Me!Notitie_Nummer
    .FormFields(«Geg_TitelMag»).Result = Me!Magistraten_Aanspreektitel
    .FormFields(«Geg_NaamMag»).Result = Me!Onderzoeksrechter_aanstelling
    .FormFields(«Geg_FunctieMag»).Result = Me!Functie
    .FormFields(«Geg_Rechtsgebied»).Result = Me!Magistraten_Rechtsgebied
    .FormFields(«Geg_AdresMag»).Result = Me!Magistraten_Adres
    .FormFields(«Geg_TijdAfname»).Result = Me!Tijdstip_afname
    .FormFields(«Geg_NaamSlachtoffer»).Result = Me!Naam
    .FormFields(«Geg_Opdracht»).Result = Me!Opdracht
    .FormFields(«Geg_Prelev»).Result = Me!Prevelementen
    .FormFields(«Geg_TitelGenees»).Result = Me!Wetsgeneesheren_Aanspreektitel
    .FormFields(«Geg_NaamGenees»).Result = Me!Wetsgeneesheer
    .FormFields(«Geg_InstituutGenees»).Result = Me!Institituut
    .FormFields(«Geg_DatumOntv»).Result = Me!Datum_Ontvangst
    .FormFields(«Geg_Koerier»).Result = Me!Koerier
    .FormFields(«Geg_Levering»).Result = Me!Opgehaald_geleverd
    .FormFields(«Geg_Startanalyse»).Result = Me!Startdatum_analyse
    .FormFields(«Geg_Eindanalyse»).Result = Me!Einddatum_analyse
    .FormFields(«Uparam_pH»).Result = Form!Dataanalyse_urineparam!pH
    .Visible = True
    .Activate
    End With
    Set doc = Nothing
    Set appWord = Nothing
    Exit Sub
    errHandler:
    MsgBox Err.Number & «: » & Err.Description

    End Sub


  2. First question, in this kind of problem, would be is the Dataanalyse_urineparam form Open and Visible when this occurs, as it has to be?

    But I suspect that your problem is here:

    Form!Dataanalyse_urineparam!pH

    Can’t check it right now, but I believe the correct syntax is

    Forms!Dataanalyse_urineparam!pH

    Linq ;0)>

    The problem with making anything foolproof…is that fools are so darn ingenious!

    All posts/responses based on Access 2003/2007


  3. Yep, sorry for that missing -s- (schoolboy error). It is however not the only issue…

    I indeed figured that the form would have to be open and I tried including the following code, but still it doesn’t work


    .FormFields(«Geg_Eindanalyse»).Result = Me!Einddatum_analyse
    DoCmd.OpenForm «Dataanalyse_urineparam», acNormal, «», «», , acNormal
    .FormFields(«Uparam_pH»).Result = Forms!Dataanalyse_urineparam!pH
    DoCmd.Close acForm, «Dataanalyse_urineparam»
    .Visible = True

    Is there some other code I need to use to open the form and make it visible?


  4. The item in red is not valid for this parameter

    DoCmd.OpenForm «Dataanalyse_urineparam», acNormal, «», «», , acNormal

    It should be

    DoCmd.OpenForm «Dataanalyse_urineparam», acNormal, «», «», , acWindowNormal

    Also, if the no item is needed, for a gieven parameter, as above, you can simply leave it blank…no need for te Zero-Length Strings («»)

    Linq ;0)>

    The problem with making anything foolproof…is that fools are so darn ingenious!

    All posts/responses based on Access 2003/2007


  5. I tried the suggested adjustment, but it still doesn’t work.

    I’m sure it has to do with the inability of my current code to get the data from a different form, because when I move the information to the form where the command button is everything goes right.

    Like this:
    .FormFields(«Uparam_pH»).Result = Me!pH

    Moving everything to a single form, however, isn’t an option because I have > 300 different items that need to be copied to Word, and a single form is limited to 255 different items.

    Any other suggestions on what adaptations can be made to get that data from that form?

    Thanks for the help so far Linq


  6. I got it to work

    I use this code

    .FormFields(«Uparam_pH»).Result = Forms(«Dataanalyse_urineparam»).pH

    Does anyone know why this works and the version with the exclamation marks doesn’t?


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

Similar Threads

  1. Replies: 1

    Last Post: 01-10-2012, 09:47 PM

  2. Replies: 2

    Last Post: 01-10-2012, 08:22 PM

  3. Replies: 1

    Last Post: 10-04-2011, 12:10 AM

  4. Replies: 7

    Last Post: 09-13-2010, 02:47 PM

  5. Replies: 3

    Last Post: 08-16-2010, 12:13 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
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules

Понравилась статья? Поделить с друзьями:
  • 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