我是一个荒谬的SQL新手。我尝试从Excel VBA编写一些代码以访问Access数据库文件,删除表,并根据其中一列的值从另一个表中复制数据以访问该第一个表。
到目前为止,我只是想将一张桌子复制到另一张桌子,我得到424:需要对象。我错过了什么?
Sub Update()
Dim cnnAccess As ADODB.Connection
Dim rstAccess As ADODB.Recordset
Set cnnAccess = New ADODB.Connection
Set rstAccess = New ADODB.Recordset
cnnAccess.ConnectionString = "Driver={Microsoft Access Driver (*.mdb,*.accdb)};Dbq= (path to file)\(nameofDB).accdb;Uid=ID;Pwd=PASSWORD;"
cnnAccess.Open
cnn.Execute "Drop Table tbl_daily" <-- Error hits on this line
cnn.Execute "SELECT * From tbl_TMD where date = 42856 INTO tbl_daily FROM
tbl_TMD"
End Sub
非常感谢任何见解。
答案 0 :(得分:0)
请尝试以下两个脚本。另外,请记住设置对Microsoft DAO x.xx对象库的引用
Sub DAOCopyFromRecordSet(DBFullName As String, TableName As String, _
FieldName As String, TargetRange As Range)
' Example: DAOCopyFromRecordSet "C:\FolderName\DataBaseName.mdb", _
"TableName", "FieldName", Range("C1")
Dim db As Database, rs As Recordset
Dim intColIndex As Integer
Set TargetRange = TargetRange.Cells(1, 1)
Set db = OpenDatabase(DBFullName)
Set rs = db.OpenRecordset(TableName, dbOpenTable) ' all records
'Set rs = db.OpenRecordset("SELECT * FROM " & TableName & _
" WHERE " & FieldName & _
" = 'MyCriteria'", dbReadOnly) ' filter records
' write field names
For intColIndex = 0 To rs.Fields.Count - 1
TargetRange.Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
' write recordset
TargetRange.Offset(1, 0).CopyFromRecordset rs
Set rs = Nothing
db.Close
Set db = Nothing
End Sub
如果您想通过数据导入进行更多控制,可以自定义以下宏:
Sub DAOFromAccessToExcel(DBFullName As String, TableName As String, _
FieldName As String, TargetRange As Range)
' Example: DAOFromAccessToExcel "C:\FolderName\DataBaseName.mdb", _
"TableName", "FieldName", Range("B1")
Dim db As Database, rs As Recordset
Dim lngRowIndex As Long
Set TargetRange = TargetRange.Cells(1, 1)
Set db = OpenDatabase(DBFullName)
Set rs = db.OpenRecordset(TableName, dbOpenTable) ' all records
'Set rs = DB.OpenRecordset("SELECT * FROM " & _
TableName & " WHERE " & FieldName & _
" = 'MyCriteria'", dbReadOnly) ' filter records
lngRowIndex = 0
With rs
If Not .BOF Then .MoveFirst
While Not .EOF
TargetRange.Offset(lngRowIndex, 0).Formula = .Fields(FieldName)
.MoveNext
lngRowIndex = lngRowIndex + 1
Wend
End With
Set rs = Nothing
db.Close
Set db = Nothing
End Sub