在Excel中从Access运行宏而不打开Access

时间:2016-08-03 14:40:30

标签: excel vba excel-vba ms-access

我有一个excel程序,它将数据写入Access数据库。在这个数据库中,我有一个宏,在运行时,将数据复制到另一个excel文件中。我想编辑原始的excel程序,以便在将数据写入Access数据库后,它将自动运行宏。现在,我设置它,以便它将数据写入数据库,然后打开数据库,运行宏,然后关闭数据库 - 这似乎有点无效。这是访问数据库中的宏:

Sub copy()



Dim strTable As String
Dim strWorksheetPath As String


strWorksheetPath = "FilePath" & "test.xlsx"
strTable = "test"

DoCmd.OutputTo acOutputTable, strTable, acFormatXLSX, strWorksheetPath



End Sub

程序中的相关代码只是打开数据库,调用宏并关闭它。如果有办法绕过这个,没有打开数据库就会很棒。感谢。

即。为了说清楚,我正在寻找一种方法来模仿excel中的上述代码,这样我根本不需要打开访问数据库,即将数据从访问传输到excel工作簿,而不使用访问VBA。

1 个答案:

答案 0 :(得分:2)

我想我理解你所问的是什么,但如果我误解了,请纠正我。

您可以将此代码插入Excel工作簿 - 将所需的引用添加到Microsoft Office 14.0 Access database engine Object Library(在工具|引用下)并更改变量以匹配您的参数。

您还应该添加错误检查

Option Explicit

Public Sub SaveAccessTableToXL()

    ' Under References, Add This
    ' Microsoft Office 14.0 Access database engine Object Library

    Dim db              As DAO.Database
    Dim rs              As DAO.Recordset

    Dim wb              As Workbook
    Dim ws              As Worksheet
    Dim rge             As Range

    Dim strDatabase         As String
    Dim strTable            As String
    Dim strWorksheetPath    As String

    ' These are variables you need to set before running
    strDatabase = "c:\databases\heatlink\linktest.accdb"
    strWorksheetPath = "c:\databases\heatlink\" & "test.xlsx"
    strTable = "tbl_areas"

    ' Create New Workbook
    Set wb = Workbooks.Add()
    Set ws = wb.Sheets("Sheet1")
    Set rge = ws.Range("A1")

    ' Get Table Data from Database
    Set db = DBEngine.OpenDatabase(strDatabase)
    Set rs = db.OpenRecordset(strTable, dbOpenDynaset, dbReadOnly)

    ' Copy Recordset into Worksheet
    rge.CopyFromRecordset rs
    rs.Close

    ' Save Workbook
    wb.SaveAs strWorksheetPath
    wb.Close

    MsgBox "Workbook Created: " & strWorksheetPath
    Set wb = Nothing
    Set ws = Nothing
    Set rge = Nothing

    Set rs = Nothing
    Set db = Nothing
End Sub