You are on page 1of 0

User may download or copy the content and other downloadable items displayed on this Website/PDF for personal

use only, provided that User maintains all copyright and other notices contained in such Content. Copying any
Content for other than personal, noncommercial use is expressly prohibited without the prior written permission
from the owner of www.Access-Freak.com, or the copyright holder identified in the individual Content's copyright
notice. If you are an owner of intellectual property who believes their intellectual property has been improperly
posted or distributed via this website, please notify the webmaster.
The content is provided "AS IS" with no warranties, and confers no rights.
The material in this website/PDF could include technical inaccuracies or other errors. Your use and browsing of the
content is at your risk. The webmaster of www.Access-Freak.com shall not be liable for any direct, incidental,
consequential, indirect or punitive damages arising out of your access to, or use of, the website/PDF.
The webmaster does not warrant that the functional aspects of the Website/PDF will be uninterrupted or error free,
or that the website or the server that makes this content available are free of viruses or other harmful components.
The owner of www.Access-Freak.com reserves the right to make changes to this website/PDF at any time without
notice.
..:: Access-Freak :: Getting started with Microsoft(R) Access 2007 (Step by Step Tutorials/Samples...)
Microsoft Access 2007 Working with the Attachment DataType
Download Tutorial 07 (432 kb zipped)
(Click link or right click--Save Target As...)

In this tutorial you will find:
..:: Access-Freak :: Getting started with Microsoft(R) Access 2007 (Step by Step Tutorials/Samples...)
An introduction of the Attachment DataType

How to work with it manually

How to work with it programmatically


In this tutorial we will look in detail at the new Attachment DataType introduced in Access 2007. We will go through examples demonstrating the usage of the new DataType
and illustrate why it might benefit developers. Furthermore, we will work with manual as well as programmatical implementations of the Attachment DataType.
General Information about the Attachment DataType:
As discussed in some of the earlier tutorials Access 2007 implements a new, very useful DataType. The Attachment DataType is a multi-valued field that replaces the OLE
Object DataType in the new ACCDB file format. Keep in mind that such complex data is only available in the ACCDB file format and not in the prior MDB formats.
The Attachment DataType works as a multi-valued field which you might think breaks normalization rules. Microsoft ensures us that the data is stored in a relational
manner at the most basic level within Access itself.
The main purpose of the new DataType is to eliminate the bloating issues the OLE Object DataType exposed when embedding external files within your application. In all
versions prior to Access 2007 it was almost always suggested to link to external files with a Text DataType. Using a Text DataType field which holds the full string directory
path and file name of the external file at the Table level would enable you to work around the bloating issue and still utilize external files within your application. However,
one of the drawbacks of this set up is to always depend on an external folder holding your files which itself always needs to be moved along side the application.
The Attachment DataType can eliminate this set up by allowing you to directly embed files within your application. If the files are not already compressed Access will store
them in a compressed manner for you to keep the ACCDB file size as small as possible.
Though the 2GB file size limit still might stir you in a direction of a set up mentioned earlier with storing the files externally and linking to them. Another alternative would be
to create an ACCDB file solely for holding your files in a table utilizing the Attachment DataType and then linking to that ACCDB file from your application file. One scenario
where either of those methods might be more suitable could be the plan to utilize an extremely large amount of files within your application or the file size of individual files
being somewhat large.
Manual usage of the Attachment DataType:
Lets start using the Attachment DataType. Create a new Table in your ACCDB file and switch to Design View. Add an Attachment DataType field to the design. Your Table
might look similar to what is shown in Picture 7.1:
..:: Access-Freak :: Getting started with Microsoft(R) Access 2007 (Step by Step Tutorials/Samples...)
Picture 7.1: Table Design including Attachment Field
We can now switch to Datasheet View and just add a couple of records including several attachments. I will just use sample images provided by Windows in the My Pictures/
Sample Pictures directory. Double left clicking on the Attachment field will invoke the Attachments dialog which will allow you to Add images to the multi-valued field.
You should also see further options to individually save the attachments back to a file or do so with all of them as well as opening and removing them from the field (see
Picture 7.2).
..:: Access-Freak :: Getting started with Microsoft(R) Access 2007 (Step by Step Tutorials/Samples...)
Picture 7.2: Attachments Dialog with Different Choices
The Attachments dialog will also be available at the Form/Report level if you want to allow the user to interact with the field values.
Now that we have set up a sample Table holding sample data we can keep moving. Lets create a form based on this Table to display the images we stored internally. If you
just click the Form Ribbon button of the Forms group behind the Create Ribbon tab while having the newly created Table selected in the Navigation Pane you might see
something similar as shown in Picture 7.3:
..:: Access-Freak :: Getting started with Microsoft(R) Access 2007 (Step by Step Tutorials/Samples...)
Picture 7.3: Auto Form Created
If you double left click on the image displayed you should receive the earlier discussed Attachment dialog which allows you to interact with the attachments. Single left
clicking on the image invokes a little navigation bar at the top of the control which allows you to navigate through the attachment values or launch the Attachment dialog
(see Picture 7.4).
..:: Access-Freak :: Getting started with Microsoft(R) Access 2007 (Step by Step Tutorials/Samples...)
Picture 7.4: Browse through Attachment Values
So what if you wanted to actually display all attachments that one particular record holds on your Report. We can achieve that as well. First lets create a Query. Click the
Query Design button in the Create Ribbon Tab (under the Other group). In the Show Table dialog pick the Table you have created that holds your attachments. Now you
should see in the Field selection area of the Table you picked that the Attachment DataType is actually split up in three different parts (see Picture 7.5).

Picture 7.5: Attachment DataType Consisting of Three Parts
..:: Access-Freak :: Getting started with Microsoft(R) Access 2007 (Step by Step Tutorials/Samples...)
It consists of the FileData, FileName and FileType. The FileData is the actual binary data that Access stores internally. The FileName is the name of the original document
and the FileType holds the extension of the original document. In my case the FileType is JPG since Ive loaded specific Windows sample images into the attachment field.
Select the ID, Attachment FileData and any other Field you might want to display on your Form/Report. If you now run the Query you should see a separate Record for each
attachment value the multi-valued field holds (see Picture 7.6).
Picture 7.6: One Record for each Multi-Valued Field Value
You can now create a Report with specific grouping which will show you all values returned by the FileData field per record.
In case you have decided to not utilize the Attachment DataType field (for one of the reasons mentioned earlier) and to use a Text DataType field instead to store the full
paths/file names to external images. You might find it interesting that the Image Control now supports a Control Source property like any other control. This means you can
bind it at the Form/Report level to your Text DataType Table Field and it should display the external images correctly without storing them internally and without one single
line of code.
Programmatical usage of the Attachment DataType:
Now that we have looked at some manual usages of the new DataType lets go through some programmatical samples to interact with the Attachment DataType. You might
not want your user to rely on the Attachment dialog that appears after double left clicking on an attachment control at the Form/Report level. There are several methods of
the Data Access Objects library (DAO) that you can use to interact with your attachments in the multi-valued field.
The LoadFromFile method can import a file from you local hard-drive into an attachment field within your application. The SaveToFile method does the complete opposite by
allowing you to save an internally stored attachment to a file on your hard-drive. Lets first look at an example utilizing the LoadFromFile method.
To stick with out prior example lets assume we have several images in an attachment field which you display on a Form. You might want to allow the users to import
additional images to the record field. For simplicity I will hard-code the path to the external file being imported. If you want to implement a browse feature then check the
code provided at: http://www.mvps.org/access/api/api0001.htm.
The function wrapped around the API call utilized in that code will return the full string path and file name to the file selected. You can store that in a variable and pass it
along to the LoadFromFile method instead of using a hard-coded value as described in Code Example 7.1:
On Error GoTo Err_AddImage
..:: Access-Freak :: Getting started with Microsoft(R) Access 2007 (Step by Step Tutorials/Samples...)
Dim db As DAO.Database
Dim rsParent As DAO.Recordset2
Dim rsChild As DAO.Recordset2
Set db = CurrentDb
Set rsParent = Me.Recordset
rsParent.Edit
Set rsChild = rsParent.Fields("AttachmentTest").Value
rsChild.AddNew
rsChild.Fields("FileData").LoadFromFile ("c:\Sunset.jpg")
rsChild.Update
rsParent.Update
Exit_AddImage:
Set rsChild = Nothing
Set rsParent = Nothing
Exit Sub
Err_AddImage:
If Err = 3820 Then
MsgBox ("File already part of the multi-valued field!")
Resume Next
Else
MsgBox "Some Other Error occured!", Err.Number, Err.Description
Resume Exit_AddImage
End If
Code Example 7.1: Programmatically Adding a New File to an Attachment Field
You can add the code to the on click event of a command button which is on the same Form that houses the attachment control that is bound to your Table attachment field.
The only requirement is that the file does not already exist in current record of the multi-valued field. If it does and you try to execute the code you will receive a Runtime
Error 3820. The error handling code included in code sample 7.1 should eliminate this problem.
Now to reverse the action we just took we can re-save our internal file back to some local directory. If you want to include the ability for the user to browse to a directory and
specify a new file name you can implement the earlier mentioned API call. In this small sample I will again just save the file to a predefined hard-coded location on my local
drive (see Code Example 7.2).
On Error GoTo Err_SaveImage
Dim db As DAO.Database
Dim rsParent As DAO.Recordset2
Dim rsChild As DAO.Recordset2
..:: Access-Freak :: Getting started with Microsoft(R) Access 2007 (Step by Step Tutorials/Samples...)
Set db = CurrentDb
Set rsParent = Me.Recordset
rsParent.OpenRecordset
Set rsChild = rsParent.Fields("AttachmentTest").Value
rsChild.OpenRecordset
rsChild.Fields("FileData").SaveToFile ("c:\")
Exit_SaveImage:
Set rsChild = Nothing
Set rsParent = Nothing
Exit Sub
Err_SaveImage:
If Err = 3839 Then
MsgBox ("File Already Exists in the Directory!")
Resume Next
Else
MsgBox "Some Other Error occured!", Err.Number, Err.Description
Resume Exit_SaveImage
End If
Code Example 7.2: Saving an Internal Attachment Back to a File
If the file already exists in the specified directory you will receive a Runtime Error 3839 which the error handling code should trap. The file will be saved to the exact same
file name it used to have when it was embedded into the attachment field.
Removing an attachment from your attachment field with code can be as simple as utilizing the DAO Delete method with the RecordSet you have opened based on the multi-
valued field. You can easily adjust the Code Examples 7.2 or 7.3 to implement a delete feature:

Set rsChild = rsJob.Fields("AttachmentTest").Value
rsChild.Delete
Me.Requery

Requiring the current Form object ensures that the changes are being immediately reflected on the Form.
We can now further utilize the code example which saves an attachment back to a file. What if you wanted to email and internal attachment to someone from within Access?
Unfortunately the build in SendObject method does not support any way to interact with the new DataType. Additionally since the SendObject method only allows internal
database objects to be attached to an email we will have to use a more flexible method of sending an email. If Microsoft Outlook is your default email client you can use
the automation code shown in Code Example 7.3:
..:: Access-Freak :: Getting started with Microsoft(R) Access 2007 (Step by Step Tutorials/Samples...)
Sub SendEmail(Optional AttachmentPath)
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Set objOutlook = CreateObject("Outlook.Application")
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
With objOutlookMsg
Set objOutlookRecip = .recipients.Add("YourRecipient")
objOutlookRecip.Type = olTo
.Subject = "Test Email Subject"
.body = "Test Email Body"
Set objOutlookAttach = .Attachments.Add(AttachmentPath)
.Display
End With
Set objOutlookMsg = Nothing
Set objOutlook = Nothing
End Sub
Code Example 7.3: Automating MicrosoftOutlook
Code Example 7.3 uses early binding so you would be required to set a reference (VBA Editor--Tools--References) to the appropriate Microsoft Outlook 12.0 Object
Library (12.0 if you are using Outlook 2007).
Using Code Example 7.2 in combination with Code Example 7.3 would allow you to create an email using an attachment displayed on your current form. You could
execute the procedures behind the on click event of a button as shown in Code Example 7.4:
Call SaveAttachToFile
Call SendEmail("c:\" & Me.AttachmentTest.FileName)
Kill ("c:\" & Me.AttachmentTest.FileName)
Code Example 7.4: Creating an Email with an Internal Attachment
As you can see we are utilizing the FileName property of the attachment control to refer to the name of the file we saved with the SaveAttachToFile procedure. After the
..:: Access-Freak :: Getting started with Microsoft(R) Access 2007 (Step by Step Tutorials/Samples...)
email has been created through automation we can go ahead and delete the file from your local directory.
This finishes our little introduction to the new Attachment DataType. We have looked at manual as well as programmatical examples of how to interact with the DataType.
Hopefully this tutorial will enable you to fully use all the capabilities of this new feature and spice up your applications a little.
Print... Back to Top Exit

You might also like