"无效的程序呼叫或参数"将访问查询导入excel表时

时间:2017-07-08 03:34:48

标签: excel vba excel-vba ms-access

我有一个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

1 个答案:

答案 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方法。