ACCESS 導出附件
需求:
把登陸窗體中的圖片,替換為數據表中的圖片.
思路:
1.把圖片保存到本地
2.修改圖片控件的圖片路徑
難點:
1.對附件的操作方法不熟練
2.不同的數據庫操作方法有差異
主要用到的方法:
Field2.SaveToFile 方法 (DAO)
效果(左側圖片的變化):
原窗體:

載入表中圖片后的效果:

數據表設計:

實現代碼:
版本一.如果圖片在本地數據庫(不屬于外鏈表)
' 設置登錄界面圖片的子程序 Sub SetLoginPic() ' 定義變量: ' rst - 用于操作tblsystemsetting表的記錄集 ' rsA - 用于操作附件字段的記錄集 ' fld - 用于表示附件字段 ' strFullPath - 存儲臨時文件完整路徑的字符串 Dim rst As DAO.Recordset2 Dim rsA As DAO.Recordset2 Dim fld As DAO.Field2 Dim strFullPath As String ' 打開系統設置表,注意CurrentDB是本地數據. Set rst = CurrentDb.OpenRecordset("tblsystemsetting") ' 獲取附件字段 Set fld = rst("Attachments") ' 檢查記錄集是否為空 If Not rst.EOF Then ' 打開附件字段中的記錄集 Set rsA = fld.value ' 檢查附件記錄集是否為空 If Not rsA.EOF Then ' 構建臨時文件路徑:系統臨時文件夾 + 附件文件名 strFullPath = VBA.Environ("TEMP") & "\" & rsA("FileName") ' 忽略錯誤(如果臨時文件已存在) On Error Resume Next ' 刪除可能已存在的臨時文件 Kill strFullPath ' 將附件中的文件數據保存到臨時文件 rsA("FileData").SaveToFile strFullPath ' 將圖片控件Image57的圖片設置為臨時文件 Me.Image57.Picture = strFullPath End If rsA.Close End If rst.Close ' 釋放對象變量 Set fld = Nothing Set rsA = Nothing Set rst = Nothing End Sub
版本二.圖片在其他數據庫
Sub SetLoginPic(ByVal DBPath As String) Dim rst As DAO.Recordset2 Dim rsA As DAO.Recordset2 Dim fld As DAO.Field2 Dim strFullPath As String Dim dbExternal As DAO.Database Dim strConnect As String ' 關鍵1:構建加密數據庫連接字符串(注意密碼暴露風險) strConnect = ";Database=" & DBPath & ";PWD=數據庫密碼" ' 關鍵2:靜默打開外部數據庫(不顯示獨占/只讀提示) Set dbExternal = DBEngine.Workspaces(0).OpenDatabase("", False, False, strConnect) ' 關鍵3:從外部庫讀取系統設置表 Set rst = dbExternal.OpenRecordset("tblsystemsetting") Set fld = rst("Attachments") If Not rst.EOF Then Set rsA = fld.value If Not rsA.EOF Then ' 關鍵4:將附件圖片提取到臨時目錄 strFullPath = VBA.Environ("TEMP") & "\" & rsA("FileName") On Error Resume Next Kill strFullPath ' 強制覆蓋舊文件 rsA("FileData").SaveToFile strFullPath ' 核心功能:設置窗體圖片 Me.Image57.Picture = strFullPath End If rsA.Close End If ' 關鍵5:必須按順序關閉對象(先記錄集后數據庫) rst.Close dbExternal.Close ' 顯式釋放對象 Set rsA = Nothing Set rst = Nothing Set dbExternal = Nothing End Sub
進階版,可以指定顯示第幾個附件
Dim rst As DAO.Recordset2 Dim rsA As DAO.Recordset2 Dim fld As DAO.Field2 Dim strFullPath As String Dim dbExternal As DAO.Database Dim strConnect As String Dim lngAttIndex As Long ' 構建帶密碼的連接字符串 strConnect = ";Database=" & DBPath & ";PWD=" & GetBDBPW & "" ' 直接打開外部數據庫連接 Set dbExternal = DBEngine.Workspaces(0).OpenDatabase("", False, False, strConnect) Set rst = dbExternal.OpenRecordset("tblsystemsetting") If Not rst.EOF Then ' 獲取附件索引值 lngAttIndex = Nz(rst("AttIndex"), 1) ' 默認為1如果字段為Null Set fld = rst("Attachments") Set rsA = fld.value ' 移動到指定的附件索引 If Not rsA.EOF Then If lngAttIndex > 1 Then rsA.MoveFirst rsA.Move lngAttIndex - 1 End If If Not rsA.EOF Then strFullPath = VBA.Environ("TEMP") & "\" & rsA("FileName") On Error Resume Next Kill strFullPath On Error GoTo 0 rsA("FileData").SaveToFile strFullPath Me.Image57.Picture = strFullPath End If End If rsA.Close End If rst.Close dbExternal.Close Set rsA = Nothing Set rst = Nothing Set dbExternal = Nothing End Sub

浙公網安備 33010602011771號