我正在尝试从Access表中将数据导入Excel。我收到语法错误当我运行该行时出现此错误:。选择[时间],[坦克],从“UnitOneRouting”,WHERE [Date] =“& RpDate& ORDER BY Tank,Time”,cn ,adOpenStatic,adLockOptimistic,adCmdTable在Access表中有四列(按顺序)Date,Time,Tank,Comments。我只想导入两列,时间和坦克,但顺序坦克,时间;我想根据Excel工作表中给出的日期导入它们。感谢
如何重新排列以下部分以打开表格,选择列(基于日期)并导入数据。
用rs'打开记录集。打开“UnitOneRouting”,cn,adOpenStatic,adLockOptimistic,adCmdTable'根据日期过滤行。选择[Time],[Tank],FROM“UnitOneRouting”,WHERE [Date] =“& ; RpDate& ORDER BY Tank,Time“,cn,adOpenStatic,adLockOptimistic,adCmdTable rs.Open,TargetRange End With
代码在这里开始
Sub ADOImportFromAccessTable()
Dim DBFullName As String
Dim TableName As String
Dim TargetRange As Range
Dim RpDate As Range
DBFullName = "U:\Night Sup\Production Report 2003 New Ver 5-28-10_KA.mdb"
TableName = "UnitOneRouting"
Set TargetRange = Range("C5")
Set RpDate = Range("B2").Cells
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=" & _
"U:\Night Sup\Production Report 2003 New Ver 5-28-10_KA.mdb" & ";"
Set rs = New ADODB.Recordset
With rs
' open the recordset
.Open "UnitOneRouting", cn, adOpenStatic, adLockOptimistic, adCmdTable
' filter rows based on date
.Select [Time], [Tank], FROM "UnitOneRouting", WHERE [Date] = " & RpDate & ORDER BY Tank, Time", cn, adOpenStatic, adLockOptimistic, adCmdTable
rs.Open , TargetRange
End With
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
答案 0 :(得分:0)
编辑:你在这里遇到很多问题:
With rs
' open the recordset
.Open "UnitOneRouting", cn, adOpenStatic, adLockOptimistic, adCmdTable
' filter rows based on date
.Select [Time], [Tank], FROM "UnitOneRouting", WHERE [Date] = " & RpDate & ORDER BY Tank, Time", cn, adOpenStatic, adLockOptimistic, adCmdTable
rs.Open , TargetRange
End With
打开记录集时,应指定SQL语句,而不仅仅是表。这对ADO来说毫无意义。此外,您的SQL语句很糟糕。在SELECT
子句中的最后一个字段后面不应该有逗号,并且在FROM
子句中的表后面没有逗号,并且你的表名不应该有双引号和......其他一些东西关于在嵌入式SQL语句本身中正确封装字符串。请尝试改为:
With rs
' open the recordset
' filter rows based on date
.Open "Select [Time], [Tank] FROM [UnitOneRouting] WHERE [Date] = " & RpDate & " ORDER BY Tank, Time", cn, adOpenStatic, adLockOptimistic, adCmdTable
End With
TargetRange.CopyFromRecordset rs