Code:
'-------------------------------------------------------------------------
' Sub/Func : SaveAttachments
' Purpose : Saves the attachments at the current row of the open Recordset
' Arguments: rstCurrent - The recordset open at the current row to save
' : strFieldName - The name of the attachment field
' : strOutputDir - The folder to put the files in (e.g. "C:\Foo\")
' -------------------------------------------------------------------------
Sub SaveAttachments(ByRef rstCurrent As DAO.Recordset, ByVal strFieldName As String, ByVal strOutputDir As String)
Const CALLER = "SaveAttachments"
On Error GoTo SaveAttachments_ErrorHandler
Dim rstChild As DAO.Recordset2
Dim fldAttach As DAO.Field2
Dim strFilePath As String
If Right(strOutputDir, 1) <> "\" Then strOutputDir = strOutputDir & "\"
Set rstChild = rstCurrent.Fields(strFieldName).Value ' The .Value for a complex field returns the underlying Recordset.
While Not rstChild.EOF ' Loop through all of the attached files in the child Recordset.
strFilePath = strOutputDir & rstChild.Fields(m_strFieldFileName).Value 'Append the name of the attached file to output directory.
If Dir(strFilePath) <> "" Then ' The file already exists--delete it first.
VBA.SetAttr strFilePath, vbNormal ' Remove any flags (e.g. read-only) that would block the kill command.
VBA.Kill strFilePath ' Delete the file.
End If
Set fldAttach = rstChild.Fields(m_strFieldFileData) ' The binary data of the file.
fldAttach.SaveToFile strFilePath
rstChild.MoveNext ' Go to the next row in the child Recordset to get the next attached file.
Wend
rstChild.Close ' cleanup
Exit Sub
SaveAttachments_ErrorHandler:
Debug.Print "Error # " & Err.Number & " in " & CALLER & " : " & Err.Description
MsgBox Err.Description, VbMsgBoxStyle.vbCritical, "Error # " & Err.Number & " in " & CALLER
Debug.Assert False ' always stop here when debugging
Resume Next
End Sub 'SaveAttachments
I assume that I put the code in a button or something? How would I execute it otherwise? I see the arguments for the function, so I was thinking adding text boxes on the form with the info in them (with the proper names) and then putting the code for the above function on a button.
The only other question I had is that... well.. how will I know what extracted attachment corresponds to what record? Since with the test code
Code:
If Dir("C:\Foo\", vbDirectory) = "" Then MkDir "C:\Foo"
SaveAttachments rst, strField, "C:\Foo\"
rst.Close
It seems like it would just lump them all into one directory (and the file names themselves are no indication of the NUMBERONE field unfortunately.
Also does this go through each attachment? It seems like it only goes through the record specified and extracts the attachments.
Thank you very much for that, that looks like just what I needed. I'll try to use it now and post back if I blow something up by accident, otherwise I'll post and mark thread as solved if it works. Thank you again!