我試圖使用Excel查詢MS Access(2007-2010)數據庫並將查詢打印到我的電子表格。獲取Excel VBA MS Access查詢來追加或顯示數組查詢?
以下代碼僅將字段標題打印到指定的單元格中,而不在選定的字段中打印其他數據。我哪裏錯了?提示等歡迎。
Option Explicit
' Add reference to Microsoft ActiveX Data Objects Lib
Public Sub main(): On Error GoTo Err_handler
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
'open DB connection
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Databaselocation
cn.Open
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
'Query Stuff
rs.ActiveConnection = cn
rs.Open "SQL Query here;"
'does something
Dim fld As ADODB.Field
Dim rng As Range
Set rng = [a2]
For Each fld In rs.Fields
rng.Value = fld.Name
Set rng = rng.Offset(0, 2)
Next fld
Set rng = rng.Offset(2, -rs.Fields.Count)
rng.CopyFromRecordset rs
' closes db connection
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
Exit Sub
Err_handler:
MsgBox Err.Description
End Sub
第一條評論:在'Set rng = rng.Offset(0,2)'這一行中,您是否每次打印某個值時都要跳過兩列?第二:CopyFromRecordset「might」只有在工作表處於活動狀態時纔有效 - 如果添加WorkSheet.Activate行,會發生什麼情況?當然,我假設您已確認您的查詢返回有效數據... – Floris 2013-02-26 22:59:10
是的,查詢返回MS訪問中的有效數據。它將返回一個包含字段名稱和一行數據的列。當前的代碼將字段名打印到指定的單元格(A2)。當我將偏移量設置爲(0,0)時,出錯。我希望它只打印查詢中的列。 – Troyd 2013-02-26 23:07:30