Search code examples
databasevbams-accessrecords

Trying to rename an attachment in Access to a field in the table


Currently I have a table where the 'ID' field is automatically generated through a combination of multiple other fields. Example : ID = '2017_FileName_Chancellor' Now I've been trying to figure out a way for me to rename this attachment to that ID (by possibly pressing a button in the form)without manually copy pasting the ID and renaming the attached file as that would be tedious when doing it for thousands of records. Is there anyway for me to do this? I have no knowledge in VBA so I could not tamper with that.

Providing a picture of my table might help https://i.sstatic.net/1GE0L.png


Solution

  • To Change the Name of the Attachment in Access:

    Private Sub Command15_Click()
        Dim NewName As String
        Dim NewNameWithExt As String
    
        NewName = Me.TestID.Value
    
        NewNameWithExt = NewName & ".txt"
    
        DoCmd.RunSQL ("UPDATE TestTable SET TestAttachment.FileName = '" & 
        NewNameWithExt & "' WHERE TestID = " & NewName)
    
    End Sub
    

    To Change the Name of the File on the Desktop:

    Private Sub Command0_Click()
        Dim NewName As String
        Dim OldName As String
        Dim rs As Object
        Dim strSQL As String
    
        Set rs = CreateObject("ADODB.Recordset")
    
        strSQL = "SELECT TestAttachment.FileName FROM TestTable WHERE TestID = 1"
    
        rs.Open strSQL, CurrentProject.Connection, 1, 3
    
        Do Until rs.EOF
            OldName = rs.Fields(0)
            NewName = CurrentDb.TableDefs("TestTable").Fields(0).Name
    
            Name "C:\Users\TestUser\desktop\" & OldName As 
            "C:\Users\TestUser\desktop\" & NewName & ".TXT"
    
            rs.MoveNext
        Loop
    
        rs.Close
        Set rs = Nothing
    
    End Sub