VBA根据数据库条目中的相应数据将图像添加到MS数据库

时间:2017-08-13 17:57:13

标签: vba ms-access

这是另一个已经解决的问题的一部分,在此粘贴链接以方便将来遇到的人。 感谢Erik_von_Asmuth先前的帮助。 Using VBA to import a large number of attachment into Microsoft Access

我认为可能有用的代码概念:

Sub MacroInsertImageToDatabase()

Dim I As Integer 'number of row in file_paths.txt
Dim J As Integer 'number of entries in the database

For J = 1 To 100

For I = 1 To 100
'Lets say there are 100 lines in file_paths.txt. Something like:
'C:\image_folder/image1.jpg
'C:\image_folder/image2.jpg
'all the way to
'C:\image_folder/image100.jpg

    If (string of file_name in column 2 in the database) = (current row in file_paths.txt we are looking at)
    Then 'That means there is a match!
        [Attach the image from as given from file_paths.txt(we ar looking at) into the 3rd row of the database(we are looking at)]
        [also escape this loop through file_paths.txt so we can move onto the next entry in the database to repeat this If statement]
    Else 'current row in file_paths.txt we are looking at is NOT what we
        [move in the the next "I" iteration to look at the next row in file_paths.txt]

Next I 'successfull attached the image to the correponse entry in the database as per string in the 2nd column (file_name)


Next J 'now move on to the next row (entry) in the database, the "J" loop

End Sub

或者我应该利用MS Access的功能,我正在阅读有关“数据库表关系”的文档。有一张桌子只有附件。有另一个表与相应的文件名(和其他数据)。然后使用MS Access的关系功能将它们链接在一起。

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码根据file_name

中设置的位置向表格添加附件
Public Sub MacroInsertImageToDatabase()    
    Dim db As DAO.Database
    Dim rsEmployees As DAO.Recordset, rsPictures As DAO.Recordset, ws As DAO.Workspace
    'Initialize database, workspace and recordset
    Set db = CurrentDb()
    set ws = DBEngine.Workspaces(0)
    Set rsEmployees = db.OpenRecordset("Table1", dbOpenDynaset)   

    Do While Not rsEmployees.EOF
        'Open the attachment recordset for the current record
        Set rsPictures = rsEmployees.Fields("attachment_column").Value
        'If there are no attachments yet
        If rsPictures.BOF Then
            'Edit the record
            rsEmployees.Edit
            'Begin a separate transaction for inserting the picture
            ws.BeginTrans
            'Load the picture
            rsPictures.AddNew
            rsPictures.Fields("FileData").LoadFromFile rsEmployees.Fields("file_name")
            'Update the pictures recordset and commit the transaction to avoid troubles with nested transactions
            rsPictures.Update
            ws.CommitTrans
            rsPictures.Close
            'Then update the record (if anything has changed inside it, which it actually hasn't)
            rsEmployees.Update
        End If
        rsEmployees.MoveNext
    Loop
    rsEmployees.Close
End Sub