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

时间:2014-09-22 22:49:15

标签: sql excel vba access-vba

我正在尝试从访问表中导入所选数据。这个表有4列,我只想要列2和3.在Excel中,并希望它们按顺序列出:第3列,第2列(与它们在Access中的方式相反)。另外,我想根据Excel Spread表中引用的日期(在代码中称为RpDate)选择行(来自Access表)。在Access中,“日期”是第一列。我需要一些帮助。感谢。

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

1 个答案:

答案 0 :(得分:1)

试试这个

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注入的教授,但它是一个开始