John Bergqvist
John Bergqvist

Reputation: 1003

MS-Access VBA - Trying to extract each file in a table's attachments to disk?

I'm trying to extract all the attachments contained within each record in a table:

As each record may have multiple attachments, I would like to loop through each record, creating a folder on disk with that record's primary key, and then dump each attachment belonging to that record, in that folder. This is the code I have so far (Partly taken from here: https://msdn.microsoft.com/en-us/library/office/ff835669.aspx) but it's saying EOF doesn't exist for my 'Attachments' collection.

Dim database As DAO.database
Dim table As DAO.Recordset
Dim PONum As String
Dim folder As String
Set database = CurrentDb
Set table = database.OpenRecordset("Purchasing")
With table ' For each record in table
   Do Until .EOF 'exit with loop at end of table
   Attachments = table.Fields("Attachments").Value 'get list of attachments
   PKey = table.Fields("PKey").Value ' get record key
   folder = "C:\" & PKey & "\" 'initialise folder name to create
   If Len(Dir(folder, vbDirectory)) = 0 Then ' if folder does not exist then create it
        MkDir (folder)
   End If
   '  Loop through each of the record's attachments'
   While Not Attachments.EOF 'exit while loop at end of record's attachments
        '  Save current attachment to disk in the above-defined folder.
        Attachments.Fields("FileData").SaveToFile _
              folder
        Attachments.MoveNext 'move to next attachment
   Wend
   .MoveNext 'move to next record
Loop
End With

Upvotes: 6

Views: 2825

Answers (1)

John Bergqvist
John Bergqvist

Reputation: 1003

Solved it. I was missing the "Set" before I initialised my Attachments object:

Set Attachments = table.Fields("Attachments").Value 'get list of attachment

Upvotes: 4

Related Questions