尝试这样的事情。
先介绍几个有用的功能:
1) 基于 SELECT 语句(通过参数传递)从 Access 获取记录集。
Option Explicit
Public Function Rst_From_Access(sSQL_Select As String) As ADODB.Recordset
Dim oConn As ADODB.Connection
Dim oRst As ADODB.Recordset
Dim sPath_DB As String
Dim sFile_DB As String
Dim sConn As String
'Instantiate the ADO-objects.
Set oConn = New ADODB.Connection
Set oRst = New ADODB.Recordset
'Set Path and File
sPath_DB = ThisWorkbook.Names("PARAM_PATH_DB").RefersToRange.value
sFile_DB = ThisWorkbook.Names("PARAM_FILE_DB").RefersToRange.value
'Create the connectionstring.
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sPath_DB & sFile_DB & ";"
With oConn
.Open (sConn) 'Open the connection.
.CursorLocation = adUseClient 'Necessary to disconnect the recordset.
End With
With oRst
.Open sSQL_Select, oConn 'Create the recordset.
Set .ActiveConnection = Nothing 'Disconnect the recordset.
End With
Set Rst_From_Access = oRst
End Function
2) ADO 连接:
Public Sub open_ADODB_Connection()
Dim oConn As ADODB.Connection
Dim sPath_DB As String
Dim sFile_DB As String
Dim sConn As String
'Instantiate the ADO-objects.
Set oConn = New ADODB.Connection
'Set Path and File
sPath_DB = ThisWorkbook.Names("PARAM_PATH_DB").RefersToRange.value
sFile_DB = ThisWorkbook.Names("PARAM_FILE_DB").RefersToRange.value
'Create the connectionstring.
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sPath_DB & sFile_DB & ";"
With oConn
.Open (sConn) 'Open the connection.
.CursorLocation = adUseClient 'Necessary to disconnect the recordset.
End With
End Sub
3)调用记录集:
选项显式
Sub Connect_To_DB()
Dim oSheet As Excel.Worksheet
Dim sSQL_Select As String
Dim oRst As ADODB.Recordset
Dim iMax_Col As Integer
Dim lMax_Row as long
Set oSheet = ThisWorkbook.Sheets("Main")
'Get recordset
sSQL_Select = "SELECT * FROM T_TABLE ORDER BY ID;"
Set oRst = Rst_From_Access(sSQL_Select)
iMax_Col = oRst.Fields.Count
oRst.MoveLast
iMax_Row = oRst.RecordCount
With oSheet
.Range(.Cells(1, 1), .Cells(iMax_Row, _
lMax_Col)).CopyFromRecordset oRst
End With
End Sub
当然,你会有重复的ID,会不会有问题?一般来说,我认为最好保留每一行的所有数据。如果它是用于打印目的,那么我会立即从 Access 打印它。