访问VBA如何从附件字段读取txt文件

时间:2019-04-11 10:23:19

标签: access-vba

我编写了一个R函数,该函数太长了,即使在memo字段中也无法存储。如果将其存储在硬盘驱动器中的txt文件中,则可能有一种读取方法。但是我可以将这个txt文件保存在附件字​​段中,并用vb代码阅读吗?到目前为止,我得到的最接近的答案如下所示,以打印附件的名称,而不是附件中的内容。

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

1 个答案:

答案 0 :(得分:0)

我从不将文件存储在附件字段中。相反,我将文件的绝对路径存储在表中,然后使用VBA显示或修改文件。

您可以使用以下代码将文本文件的内容打印到控制台。注意:您需要将Microsoft脚本运行时引用添加到您的项目中。

    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
相关问题