简体   繁体   中英

Access VBA how to read a txt file from an attachment field

I wrote an R function, which is too long to be stored even in a memo field. There is probably a way of reading it if I store it in a txt file somewhere in my hard drive. But can I save this txt file in an attachment field and read it with vb code? So far the nearest answer I got is as below to print names of the attachment, but not what is in the attachment.

Dim dbs As DAO.Database
Dim rst As DAO.Recordset2
Dim rsA As DAO.Recordset2
Dim fld As DAO.Field2

'Get the database, recordset, and attachment field
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("tblAttachments")
Set fld = rst("Attachments")

'Navigate through the table
Do While Not rst.EOF

'Print the first and last name
Debug.Print rst("FirstName") & " " & rst("LastName")

'Get the recordset for the Attachments field
Set rsA = fld.Value

'Print all attachments in the field
Do While Not rsA.EOF

    Debug.Print , rsA("FileType"), rsA("FileName")

    'Next attachment
    rsA.MoveNext
Loop

'Next record
rst.MoveNext
Loop

I never store files in attachment fields. Instead I will store the absolute path to the file in the table and then use VBA to display or modify the file.

You can use the following code to print the contents of a text file to the console. NOTE: You will need to add the Microsoft Scripting Runtime reference to your project.

    Dim fso As FileSystemObject
    Dim ts As TextStream
    Set fso = CreateObject("Scripting.FileSystemObject")
    ' use path stored in table vvv here
    Set ts = fso.OpenTextFile(path, ForReading, False, 0)

    Do While ts.AtEndOfStream <> True
        debug.print ts.ReadLine
    Loop

    ts.Close

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM