Search code examples
vbams-access

Concatenate ID field to filename


In MS Access, I want to rename filename of the attachment with ID and filename so that there should be any problem for duplicates. For example, if the id is 1 and filename is ABC then name in the folder should be 1ABC or 1_ABC anything is fine. Currently it is saving as ABC.extension (pdf/docx/txt).


Solution

  • Try this.

    Private Sub Command0_Click()
    
        Dim counter As Long
        counter = SaveAttachments("D:\Test1")
    
        MsgBox counter & " files exported."
    
    End Sub
    

    Public Function SaveAttachments(savePath As String, Optional strPattern As String = "*.*") As Long
    
        Dim r As DAO.Recordset
        Dim r2 As DAO.Recordset2
        Dim strFullPath As String
        Dim counter As Long
        
        Set r = CurrentDb().OpenRecordset("Notices")
    
        Do While Not r.EOF
    
            Set r2 = r("Attachments").Value
    
            Do While Not r2.EOF
    
                If r2("FileName") Like strPattern Then
                    strFullPath = savePath & "\" & r("ID") & "_" & r2("FileName")
    
                    If Dir(strFullPath) = "" Then
                        r2("FileData").SaveToFile strFullPath
                        counter = counter + 1
                    End If
                End If
    
                r2.MoveNext
            Loop
    
            If Not r2 Is Nothing Then r2.Close
            r.MoveNext
        Loop
    
        If Not r Is Nothing Then r.Close
    
        SaveAttachments = counter
    End Function