我有一个excel工作簿,其中包含链接到excel表的数据透视表和图表。我想创建一个按钮,按下该按钮时,删除表中的任何数据,并将其替换为访问数据库中已保存查询的更新数据。我写了下面的代码,但是我得到了一个"无效的程序调用或参数"我运行程序时出错。有谁知道我哪里出错了?
'button on excel form runs procedure to remove current data in table then
'import data from query in MS access database
Sub ImportData()
Call CleanTheTable("MMPres_MainData", "MainData")
Call ImportAccessData("qry_MMPres_Main", "MMPres_MainData", "MainData"
End Sub
'procedure finds database file and imports query into excel table
Sub ImportAccessData(qry As String, sht As String, tbl As String)
On Error GoTo ErrorHandler
Const dbLoc As String = "D:\AccessPractice\CTDB\CardiothoracicDB_v2_Current.accdb"
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim bk As Workbook
Dim Wsht As Worksheet
Set bk = ActiveWorkbook
Set Wsht = bk.Worksheets(sht)
Set db = DBEngine.OpenDatabase(dbLoc)
Set rs = db.OpenRecordset(qry, dbOpenSnapshot)
Wsht.ListObjects(tbl).Range("A1").CopyFromRecordset (rs)
rs.Close
Set rs = Nothing
db.Close
Set db = Nothing
Set Wsht = Nothing
Set bk = Nothing
Exit Sub
ErrorHandler:
Application.StatusBar = ""
MsgBox ("Error: " & Err.Number & " " & Err.Description)
rs.Close
Set rs = Nothing
db.Close
Set db = Nothing
Set Wsht = Nothing
Set bk = Nothing
End Sub
答案 0 :(得分:0)
假设您已为DAO
设置了必要的库引用,您得到的错误就在这一行:
Wsht.ListObjects(tbl).Range("A1").CopyFromRecordset (rs)
将其更改为:
Wsht.ListObjects(tbl).Range(2, 1).CopyFromRecordset rs
也可能:
Wsht.ListObjects(tbl).HeaderRowRange.Offset(1).CopyFromRecordset rs
总结:
1-删除(rs)
2-不要覆盖表格的标题(第1行),从第二行开始复制记录集。
3- Range
的方法ListObject
有点令人困惑,它会返回表格的整个范围,但无法直接输入" A1- style" 引用,它更像工作表的Cells
方法。