在MS Access中通过VBA添加附件

时间:2013-01-23 11:41:02

标签: database vba ms-access access-vba

我的一个表格如下

enter image description here

这是MS Access中的一个表单,允许我的用户添加观察。观察可以包括如图所示的附件。我可以单击附件控件并向弹出的弹出窗口添加附件。但是,我所期望的是当我单击上面表格中显示的ADD按钮时,此附件应添加到表格的相应字段中。

此表单上的所有控件均未绑定。

ADD按钮后面的代码如下:

Private Sub cmdAdd_Click()
    Dim db As DAO.Database
    Dim rs As DAO.Recordset

    Set db = CurrentDb
    Set rs = db.OpenRecordset("tblObservation", dbOpenDynaset)

    rs.AddNew

    rs![Artifact] = artifactId
    rs![Observation Text] = txtObservationText.Value

    'rs![Attachments] = ' not able to solve this

    rs.Update
    rs.Close

    Set rs = Nothing
    Set db = Nothing
End Sub

3 个答案:

答案 0 :(得分:1)

就移动性而言,您的要求是有道理的。拿一个,看看这个链接:

http://office.microsoft.com/en-001/access-help/attach-files-and-graphics-to-the-records-in-your-database-HA010341505.aspx

解释得很好。您可以在此帖子上阅读更多内容,因为它与我将文件保存到本地驱动器文件夹时所做的评论一致:

How to auto attach images in Access 2010 using vba/macros?

答案 1 :(得分:0)

您可以使用Microsoft

中的以下参考

相关的代码段是这样的:

'  Instantiate the parent recordset.  
Set rsEmployees = db.OpenRecordset("Employees") 

'… Code to move to desired employee 

' Activate edit mode. 
rsEmployees.Edit 

' Instantiate the child recordset. 
Set rsPictures = rsEmployees.Fields("Pictures").Value  

' Add a new attachment. 
rsPictures.AddNew 
rsPictures.Fields("FileData").LoadFromFile "EmpPhoto39392.jpg" 
rsPictures.Update 

' Update the parent record 
rsEmployees.Update 

答案 2 :(得分:0)

首先,将附件控件绑定到所需表的附件字段

   Private Sub cmdAdd_Click()
           'Me.Dirty = False  'fix Error 3188 is Could not update...
            Dim db As DAO.Database
            Dim rs As DAO.Recordset
            Dim rsFiles As DAO.RecordSet2
        
            Set db = CurrentDb
            'Create a DAO Recordset from a table in the current database
            Set rs = db.OpenRecordset("tblObservation")
                           
            rs.AddNew
            rs![Artifact] = artifactId
            rs![Observation Text] = txtObservationText.Value        
    
            Set rsFiles = rs.Fields("Attachments").Value 
            'This is a piece of code to get multiple files
            For i = 0 To AttachmentControl.AttachmentCount-1
                rsFiles.AddNew
                'Attachment control is used as an uploader file 
                rsFiles.Fields("FileData").LoadFromFile  AttachmentControl.FileName(i)
            Next i
        
            rsFiles.Update 
            rsFiles.Close
        
            rs.Update
            rs.Close
        
            Set rs = Nothing
            Set db = Nothing
        End Sub