Ms access 使用函数和查询从Access保存附件

Ms access 使用函数和查询从Access保存附件,ms-access,vba,Ms Access,Vba,我有一个MS Access数据库,其中有一个公共函数和一个查询。我希望函数循环遍历“附件”列中的每个字段,然后保存该字段中的所有附件。我需要用“SEDOL”列和相应的行值作为文件名的第一部分进行保存,但它在下面代码中的“Set rsA2=fld2.value”行中不断出现错误。SEDOL列是常用的文本字段列。代码在没有SEDOL保存名称部分的情况下工作。我想要一些关于如何让它工作的建议。谢谢 Public Function SaveAttachments(strPath As String, O

我有一个MS Access数据库,其中有一个公共函数和一个查询。我希望函数循环遍历“附件”列中的每个字段,然后保存该字段中的所有附件。我需要用“SEDOL”列和相应的行值作为文件名的第一部分进行保存,但它在下面代码中的“Set rsA2=fld2.value”行中不断出现错误。SEDOL列是常用的文本字段列。代码在没有SEDOL保存名称部分的情况下工作。我想要一些关于如何让它工作的建议。谢谢

Public Function SaveAttachments(strPath As String, Optional strPattern As String = "*.*") As Long

Dim dbs As DAO.Database
Dim rst As DAO.Recordset2
Dim rst2 As DAO.Recordset2
Dim rsA As DAO.Recordset2
Dim rsA2 As DAO.Recordset2
Dim fld As DAO.Field2
Dim fld2 As DAO.Field2
Dim strFullPath As String

'Get the database, recordset, and attachment field
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("Core Securities")
Set fld = rst("Attachments")
Set fld2 = rst("SEDOL")
'Navigate through the table
Do While Not rst.EOF

'Get the recordset for the Attachments field
Set rsA = fld.Value
'BUGS IN NEXT LINE
Set rsA2 = fld2.Value
'Save all attachments in the field (works without rsA2)
Do While Not rsA.EOF
    If rsA("FileName") Like strPattern Then
        strFullPath = strPath & "\" & rsA2("SEDOL") & " - " & rsA("FileName")

    'Make sure the file does not exist and save
    If Dir(strFullPath) = "" Then
        rsA("FileData").SaveToFile strFullPath
    End If

    'Increment the number of files saved
    SaveAttachments = SaveAttachments + 1
    End If

    'Next attachment
    rsA.MoveNext
Loop
rsA.Close

'Next record
rst.MoveNext
Loop

rst.Close
dbs.Close

Set fld = Nothing
Set rsA = Nothing
Set rst = Nothing
Set dbs = Nothing

End Function

由于
SEDOL
列只是一个字符串,因此不能将记录集分配给它的值

只需参考其价值:

Public函数SaveAttachments(strPath作为字符串,可选strPattern作为字符串=“**”)长度为
Dim数据库作为DAO.Database
将rst设置为DAO.Recordset2
将rsA设置为DAO.Recordset2
将strFullPath设置为字符串
'获取数据库、记录集和附件字段
设置dbs=CurrentDb
Set rst=dbs.OpenRecordset(“核心证券”)
'在表格中导航
不使用rst.EOF时执行此操作
'获取附件字段的记录集
设置rsA=rst(“附件”).值
'在字段中保存所有附件(不带rsA2)
不要使用rsA.EOF
如果rsA(“文件名”)像strPattern那么
strFullPath=strPath&“\”rst(“SEDOL”).Value&“-”rsA(“文件名”)
'确保文件不存在并保存
如果Dir(strFullPath)=“”,则
rsA(“文件数据”).SaveToFile strFullPath
如果结束
'增加保存的文件数
SaveAttachments=SaveAttachments+1
如果结束
“下一个附件
rsA.MoveNext
环
rsA.Close
“下一个记录
rst.MoveNext
环
rst.关闭
星展银行,结束
设置rsA=Nothing
设置rst=无
设置dbs=Nothing
端函数
我还删除了许多奇怪的东西,这些东西可能是不必要的,也可能是导致童车行为的积极因素