我正在尝试使用 Excel 查询 MS Access (2007-2010) 数据库并将查询打印到我的电子表格中。
下面的代码仅将字段标题打印到指定的单元格中,并且不打印所选字段中的其他数据。我哪里错了?提示等欢迎。
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