VB6 內建報表功能弱,Crystal Reports 又過重。利用 Automation (OLE 自動化) 直接駕馭已安裝的 Microsoft Access 應用程式開啟並列印報表,是輕量、高相容的方案。本文提供最小可行程式碼與關鍵注意事項。
rptEmployees)。
' 模組層級變數持有 Application 物件
Dim appAccess As Access.Application
Private Sub Command1_Click()
On Error GoTo ErrHandler
Set appAccess = New Access.Application
' 開啟資料庫 (App.Path 為專案執行目錄)
appAccess.OpenCurrentDatabase App.Path & "\novelty.mdb"
' 開啟報表並預覽/列印
' acViewNormal = 0 (列印), acViewPreview = 1 (預覽), acViewDesign = 2 (設計)
appAccess.DoCmd.OpenReport "rptEmployees", acViewNormal
' 清理
appAccess.CloseCurrentDatabase
Set appAccess = Nothing
Exit Sub
ErrHandler:
MsgBox "錯誤 " & Err.Number & ": " & Err.Description
If Not appAccess Is Nothing Then
On Error Resume Next
appAccess.CloseCurrentDatabase
Set appAccess = Nothing
End If
End Sub
| 常數/方法 | 值/用途 |
|---|---|
acViewNormal | 0 - 直接送印表機 |
acViewPreview | 1 - 開啟預覽視窗 |
DoCmd.OpenReport | 開啟報表,語法:OpenReport(ReportName, View, FilterName, WhereCondition, WindowMode, OpenArgs) |
OpenCurrentDatabase | 開啟 .mdb/.accdb,支援完整路徑 |
| 優點 | 缺點 |
|---|---|
| 零第三方元件相依 | 客戶端必須安裝 Access (授權成本) |
| 報表設計留在 Access 熟悉環境 | Access 版本差異可能導致物件庫不相容 |
| 支援複雜報表 (群組、子報表、條件格式) | 無 Access 環境無法運行 (不適合綠色軟體部署) |
| 程式碼極簡潔 | 自動化過程可見 Access 視窗閃爍,體驗稍差 |
VSPReport、RBuilder 等。App.Path 相對定位,避免硬編碼appAccess 釋放,防止殭屍進程對於已有 Access 基礎設施的企業內部系統,此方案開發效率最高、維護成本最低。