我正在尝试了解如何使用Access 2010中提供的新附件字段。我想将表中的值直接分配给变量。我知道如果我使用中间形式我可以这样做,但这看起来像是草率编码依赖于表格来从表中获取值。有没有办法获取附件字段中的内容并将其直接分配给变量?我有多个实例,这对我来说很方便。第一个例子是我想抓住存储在附件字段中的照片以分配给功能区。第二个例子是将表中的公司徽标加载到变量中,并将其保存在内存中,以便根据需要在整个程序中使用。
到目前为止我的代码是这样的,但它给了我一个类型不匹配的错误:
Dim ParentRS As Recordset, ChildRS As Recordset, Img As Attachment
Set ParentRS = CurrentDb.OpenRecordset("SELECT * FROM LtblImg;", dbOpenSnapshot)
If ParentRS.RecordCount > 0 Then
Set ChildRS = ParentRS("Img").Value
If ChildRS.RecordCount > 0 Then
Set Img = ChildRS("FileData")
End If
ChildRS.Close
End If
ParentRS.Close
答案 0 :(得分:1)
是的,Dim Img As Attachment
看起来很诱人,但Attachment
(实际上是Access.Attachment
)是指可以在表单上使用的附件控件(就像Access.TextBox
)并且似乎不适合您的预期目的。
用于存储此类二进制数据的唯一本机VBA类型是字节值数组,但通常在处理字节数组时,我们逐个循环并逐字节处理它们,这是繁琐且低效的。 / p>
您可以考虑使用二进制ADODB.Stream
对象作为"变量"。您可以创建一个函数来检索附件字节并将其返回到Stream中,如此
Option Compare Database
Option Explicit
Public Function GetLogoAsStream() As ADODB.Stream
Dim cdb As DAO.Database, rstMain As DAO.Recordset, rstAttach As DAO.Recordset2, fldAttach As DAO.Field2
' Project references required for early binding:
' Windows Script Host Object Model
' Microsoft ActiveX Data Objects 2.8 Library
Dim fso As FileSystemObject, tempFileSpec As String
Static strm As ADODB.Stream
If strm Is Nothing Then
Set fso = New FileSystemObject
tempFileSpec = fso.GetSpecialFolder(TemporaryFolder) & "\" & fso.GetTempName
Set fso = Nothing
Set cdb = CurrentDb
Set rstMain = cdb.OpenRecordset( _
"SELECT [AttachmentFiles] " & _
"FROM [AttachmentsTable] " & _
"WHERE [Description]='SO logo'", _
dbOpenSnapshot)
Set rstAttach = rstMain("AttachmentFiles").Value
' make sure we use the correct file extension
tempFileSpec = tempFileSpec & "." & rstAttach.Fields("FileType").Value
Set fldAttach = rstAttach.Fields("FileData")
fldAttach.SaveToFile tempFileSpec
Set fldAttach = Nothing
rstAttach.Close
Set rstAttach = Nothing
rstMain.Close
Set rstMain = Nothing
Set cdb = Nothing
Set strm = New ADODB.Stream
strm.Type = adTypeBinary
strm.Open
strm.LoadFromFile tempFileSpec
Kill tempFileSpec
End If
strm.Position = 0
Set GetLogoAsStream = strm
End Function
然后,如果你有一个像这样的报告,带有一个空的图像控件
和On Load
这样的事件程序从您的"变量"加载图像控件.PictureData
(实际上是一个返回ADODB.Stream的函数)
Private Sub Report_Load()
Me.LogoImage.PictureData = GetLogoAsStream.Read
End Sub
它可以产生类似这样的东西