使用VBA将选定列从Access表导入Excel

我正试图从访问表中导入选定的数据。 这个表有4列,我只想要列2和3.在Excel中,并希望他们列出的顺序:列3,列2(相反,他们是如何在Access中)。 此外,我想根据Excel Spread工作表中引用的date(我在代码中称为RpDate)select行(从Access表)。 在Access中,“Date”是第一列。 我需要一些帮助。 谢谢。

Sub ADOImportFromAccessTable() Dim DBFullName As String Dim TableName As String Dim TargetRange As Range Dim RpDate As Range DBFullName = "C:\Documents\Database.mdb" TableName = "DataTable" TargetRange = Range("C5") RpDate = Range("B2").Value Dim cn As ADODB.Connection, rs As ADODB.Recordset, intColIndex As Integer Set TargetRange = TargetRange.Cells(1, 1) ' open the database Set cn = New ADODB.Connection cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & _ "C:\Documents\Database.mdb" & ";" Set rs = New ADODB.Recordset With rs ' open the recordset .Open TableName, cn, adOpenStatic, adLockOptimistic, adCmdTable ' all records .Open "SELECT * FROM " & TableName & _ " WHERE [Date] = RpDate, cn, , , adCmdText" ' filter rows based on date rs.Open , TargetRange End With rs.Close Set rs = Nothing cn.Close Set cn = Nothing End Sub 

尝试这个

 Sub ADOImportFromAccessTable() Dim DBFullName As String Dim TableName As String Dim TargetRange As Range Dim RpDate As Range DBFullName = "C:\Documents\Database.mdb" TableName = "DataTable" Set TargetRange = Range("C5") RpDate = Range("B2").Value Dim cn As ADODB.Connection, rs As ADODB.Recordset, intColIndex As Integer Set TargetRange = TargetRange.Cells(1, 1) ' open the database Set cn = New ADODB.Connection cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & _ "C:\Documents\Database.mdb" & ";" Set rs = New ADODB.Recordset With rs ' open the recordset .Open TableName, cn, adOpenStatic, adLockOptimistic, adCmdTable ' all records .Open "SELECT Time, Tank FROM " & TableName & " WHERE [Date] = " & RpDate & " ORDER BY Tank, Time", cn, , , adCmdText ' filter rows based on date End With rs.Close Set rs = Nothing cn.Close Set cn = Nothing End Sub 

这不是SQL注入的教训,而是一个开始