Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 電腦軟體介紹

VB6 + ADO + OLE 自動化:DBF 資料庫批量匯出 Word 文檔表格完整代碼實現

編輯:電腦軟體介紹

手工從 DBF 資料庫複製數據到 Word 表格極其低錯。利用 VB6、ADO 讀取 DBF、OLE 自動化 Word,一段代碼實現結構固定的資料表批量匯出,適用於定期歸檔、列印輸出等場景。

開發環境

  • VB 6.0、FoxPro 6.0、Word 2003
  • 核心技術:ADO (ActiveX Data Objects)、OLE (Object Linking and Embedding)

核心邏輯與關鍵代碼片段

1. ADO 連接 DBF

Dim cn As New ADODB.Connection
cn.ConnectionTimeout = 15
cn.ConnectionString = "Provider=MSDASQL;" & _
  "Driver={Microsoft Visual Foxpro Driver};" & _
  "SourceType=DBF;" & _
  "SourceDB=" & dbfpath
cn.Open

2. 讀取資料集到陣列

Private rec As Variant
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim sqlstr As String
sqlstr = "select * from " & dbfname
rs.Open sqlstr, cn, adOpenStatic, adLockPessimistic
rec = rs.GetRows(n)  ' rec 為多維陣列存放所有欄位值

3. OLE 啟動 Word 並開啟模板

Private objWD As Word.Application
Set objWD = CreateObject("Word.Application")
objWD.Documents.Open newfile  ' newfile 為模板檔路徑

4. 寫入 Word 表格

ActiveDocument.Tables.Item(i).Cell(j, wordcol).Range.Text = rec(j, i - 1)
' i: 表格索引, j: 列/行, wordcol: 目標欄, rec: 資料陣列

完整代碼下載

所有相關代碼可至 新浪愛問分享頁 下載。

應用價值

固定結構的 DBF→Word 批量匯出,消除人工複製貼上錯誤,大幅提升歸檔列印效率,代碼可直接移植至 VBA 或 VB.NET 微調後使用。
Copyright © Windows教程網 All Rights Reserved