I found basically the same code while googling this issue. Every time I run the code the variable "m_strFieldFileData" is empty. How does this variable become populated?
Here is my code...
Code:
Private Sub cmdattach_Click()Dim claimnum As String, serialno As Double, rs As DAO.Recordset, db As DAO.Database
claimnum = xx
serialno = 1
filepath = SelectFile()
If filepath <> "" Then
Set db = CurrentDb
Set rs = db.OpenRecordset("Picture Table")
With rs
.AddNew
AddAttachment rs, "Attach", filepath
.Fields("Claim Number") = claimnum
.Fields("Serial Number") = serialno
.Update
.Close
End With
End If
End Sub
My 2 public functions...
Code:
Public Function SelectFile() As String Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select file to attach"
If .Show = True Then
SelectFile = .SelectedItems(1)
Else
Exit Function
End If
End With
Set fd = Nothing
End Function
Public Sub AddAttachment(ByRef rstCurrent As DAO.Recordset, ByVal strFieldName As String, ByVal strFilePath As String)
On Error GoTo AddAttachment_Err
Dim rstChild As DAO.Recordset2
Dim fldAttach As DAO.Field2
Set rstChild = rstCurrent.Fields(strFieldName).Value
rstChild.AddNew
Set fldAttach = rstChild.Fields(m_strFieldFileData)
fldAttach.LoadFromFile strFilePath
rstChild.Update
rstChild.Close
Exit Sub
AddAttachment_Err:
' Run-time error '3820': (occurs if the file with the same name is already attached)
If Err.Number <> 3820 Then
modUtility.ErrorMessage
Else
VBA.Interaction.MsgBox "File already attached!", vbInformation + vbOKOnly, modConstant.AppName
End If
Resume AddAttachment_End
AddAttachment_End:
End Sub