Shawn V. Wilson
Shawn V. Wilson

Reputation: 1111

What's another programmatic method to remove attachment(s) on a Access Form's Attachment Control?

My Access form has an attachment control, and I want to give the users the ability to overwrite one of a record's files with another copy from their drive.

Here's a snippet from my code:

Dim cdb As DAO.Database, rstMain As DAO.Recordset, rstAttach As DAO.Recordset2
Dim fldAttach As DAO.Field2

' *Snip*

Set rstAttach = rstMain(strAttachFielD).Value

rstAttach.AddNew
Set fldAttach = rstAttach.Fields("FileData")

   '----------------------------------------------
   '  Here goes "blnFileExists" code that determines whether 
   '  "Myfile.txt" is already in the attachment
   '----------------------------------------------

   If blnFileExists Then
       ' *** Delete "MyFile.txt" from the Attachment
   End If

  fldAttach.LoadFromFile "MyFile.txt"

Another poster on SO asked basically the same question here. The answer includes this:

Private Sub DeleteCurrentAttachment()

    Dim Records     As DAO.Recordset
    Dim Attachments As DAO.Recordset2

    Set Records = Me.RecordsetClone
    Records.Bookmark = Me.Bookmark

    Set Attachments = Records!YourAttachmentFieldName.Value
    While Not Attachments.EOF
        Attachments.Delete
        Attachments.MoveNext
    Wend
    Attachments.Close

End Sub

My problem is that I'm not sure how to apply that answer to my code. Wouldn't Attachments.Delete remove all the attachments, not just one?

Honestly, most of what I know about attachment controls and multi-value fields in VBA is from here in SO. From Googling, the main thing I've learned is that I ought to be using hyperlinks instead. (My client wants both options, so I have to make this work.)

Upvotes: 0

Views: 232

Answers (1)

Erik A
Erik A

Reputation: 32682

Attachments.Delete on the attachments subrecordset only deletes this subrecord, so not all attachments, just one.

You can check the filename in the loop, and only delete a specific one.

While Not Attachments.EOF
    If Attachments.FileName = "MyFile.txt"
        Attachments.Delete
    End If
    Attachments.MoveNext
Wend

Upvotes: 2

Related Questions