我的一个用户有一个Microsoft Access数据库,在表中他有一个附件字段.在他的一个查询中,他想要返回该字段包含的附件数量.我试图让这个工作无济于事.我已经尝试创建一个VBA模块并将其传入该字段,但它对我有误.我已经尝试将参数创建为DAO.Recordset,DAO.Field,Attachment等.
我也试过像[MyField] .AttachmentCount那样查询字段.
我目前没有2007年对我进行测试,但本文解释了如何使用LoadFromFile和SaveToFile访问附件.
看看你是否可以这样访问计数(使用DAO)...显然使用你的表名.
' Instantiate the parent recordset.
Set rsEmployees = db.OpenRecordset("YourTableName")
''' Code would go here to move to the desired record
' Activate edit mode.
rsEmployees.Edit
' Instantiate the child recordset.
Set rsPictures = rsEmployees.Fields("Pictures").Value
Debug.Print rsPictures.RecordCount'' <- SEE IF THIS GIVES YOU THE COUNT
Run Code Online (Sandbox Code Playgroud)
编辑:对不起延迟; 我没有机会看到它.
我认为这应该是一个解决方案.我在Access 2010中进行了测试,但它确实有效.
第1部分 - 创建通用函数以获取任何表中任何字段的附件计数.将此代码放在模块中.
Function AttachmentCount(TableName As String, Field As String, WhereClause As String)
Dim rsRecords As DAO.Recordset, rsAttach As DAO.Recordset
AttachmentCount = 0
Set rsRecords = CurrentDb.OpenRecordset("SELECT * FROM [" & TableName & "] WHERE " & WhereClause, dbOpenDynaset)
If rsRecords.EOF Then Exit Function
Set rsAttach = rsRecords.Fields(Field).Value
If rsAttach.EOF Then Exit Function
rsAttach.MoveLast
rsAttach.MoveFirst
AttachmentCount = rsAttach.RecordCount
End Function
Run Code Online (Sandbox Code Playgroud)
第2部分 - 在Access查询中使用自定义功能.
SELECT Table1.ID, AttachmentCount("Table1","MyAttach","[ID]=" & [ID]) AS [Num Attach]
FROM Table1;
Run Code Online (Sandbox Code Playgroud)
参数1是附件所在的表,参数2是表中附件所在的字段,最后一个参数是表的WHERE子句,用于选择正确的记录.
希望这可以帮助!
UPDATE
这个SQL查询对我有用:
SELECT t.ID, Count(t.MyAttach.FileName) AS [Num Attachments]
FROM Table1 AS t
GROUP BY t.ID;
Run Code Online (Sandbox Code Playgroud)