在Excel中创建一个按钮,该按钮会调用创建的Access查询

时间:2018-08-22 13:38:22

标签: excel vba excel-vba ms-access

是否可以在Excel中创建一个按钮来运行一个已在Access中创建的查询,然后使用查询中的数据更新Excel电子表格?我已经在网上搜索了有关如何执行此操作的指导,但是只找到了在Excel中创建按钮的答案,该答案仅在Excel中运行查询,而不在Access中运行。我假设将通过在VBA中单击进行编码来完成此操作,但是尚未找到执行此操作的任何方法。所以...有可能吗?如果是这样,怎么办?

好的,所以我对这个问题进行了更新,因为我有点同时使用了这两个选项。因此,我首先在标准模块中创建了一个函数(因为稍后我们可以在工作簿的另一张表中使用它,并且我们不想重复工作):

Function GetSqlServerData(sQuery As String, sRange As Range)

    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim sConnString As String

    ' Create the connection string.
    sConnString = "NMS"

    ' Create the Connection and Recordset objects.
    Set conn = New ADODB.Connection
    Set rs = New ADODB.Recordset

    ' Open the connection and execute.
    conn.Open sConnString
    Set rs = conn.Execute(sQuery)

    ' Check we have data.
    If Not rs.EOF Then
        ' Transfer result.
        Sheets(3).Range("A2").CopyFromRecordset rs
    ' Close the recordset
        rs.Close
    Else
        MsgBox "Error: No records returned.", vbCritical
    End If
    ' Clean up
    If CBool(conn.State And adStateOpen) Then conn.Close
    Set conn = Nothing
    Set rs = Nothing

End Function

然后我尝试使用上述功能:

Sub GetPermits()
    Dim sQuery As String
    Dim sRange As Range

    Set sQuery = "Select * From Customer;"
    Set sRange = Sheets(3).Range("A2")

    GetSqlServerData(sQuery, sRange)

End Sub

但是它在实际使用该功能的地方给了我一个错误。我不需要它去一个MsgBox,也不需要它来打印出来,我所要做的就是将数据放入函数调用中提到的工作表中。顺便说一句,该功能需要一些调整,我知道。现在,我只需要用它来叫该死的东西,哈哈。

这是错误消息的屏幕截图:如果看不到它,它会显示“ Compile Error:Expected:=“,并以红色突出显示“ GetSqlServerData(sQuery,sRange)”。因此,它必须与此有关。我只是不知道那是什么。

Screenshot of the error message

3 个答案:

答案 0 :(得分:1)

根据您的要求,您可以在没有VBA的情况下以更快,更可靠的方式获得此表,以使表指向您的查询,并在单击“刷新”时进行更新。

为此,请在Excel中导航至“数据”>“从Access”。

从此处,使用保存的查询导航到数据库,然后当系统要求您选择一个表时,您可以选择查询。

您还可以为Excel编写自己的SQL查询,以代替对数据库执行

您可以编辑连接属性以在打开工作簿时刷新,或例如每60分钟刷新一次,也可以将其全部关闭,并允许用户在Excel本身中单击“刷新”。

或者,您可以设置一个对链接表运行刷新表命令的按钮,这将执行相同的操作

Private Sub CommandButton1_Click()
     ActiveWorkbook.RefreshAll
End Sub

祝你好运。

答案 1 :(得分:0)

As an example for a solution with VBA using ADODB one could use the following function to connect to the database.

Function ConnectToDB(ByVal fileName As String)

Dim conn As New ADODB.Connection

    If Dir(fileName) = "" Then
        MsgBox "Could not find file " & fileName
        Exit Function
    End If

    Dim connectionString As String

    ' https://www.connectionstrings.com/access/
    connectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" _
                       & fileName & ";Persist Security Info=False;"

    conn.Open connectionString

    Set ConnectToDB = conn

End Function

And if you want to copy data from the database one could use the following code. You need to have a sheet with the codename shRepAllRecords

Option Explicit

Sub ReadFromDB()

    ' Get datbase name
    Dim dbName As String
    dbName = <fule filename of the database>

    ' Connect to the databse
    Dim conn As ADODB.Connection
    Set conn = ConnectToDB(dbName)

    ' read the data
    Dim rs As New ADODB.Recordset
    Dim query As String

    ' First example to use an SQL statement
    ' query = "SELECT * From CUSTOMER"

    ' Second example to use a query name defined in the database itself
    query = "qryCustomer"

    rs.Open query, conn

    ' shRepAllRecords is the codename of the sheet where the 
    ' data is written to

    ' Write header
    Dim i As Long
    For i = 0 To rs.Fields.Count - 1
        'shRepAllRecords.Cells(1, i + 1).Value = rs.Fields(i).Name
        shRepAllRecords.Range("A1").Offset(0, i) = rs.Fields(i).Name
    Next i

    ' Write Data
    shRepAllRecords.Range("A2").CopyFromRecordset rs
    shRepAllRecords.Activate


    ' clean up
    conn.Close

End Sub

答案 2 :(得分:0)

所以我终于能够找出问题所在。我没有在函数调用之前放置“ Call”。一旦我做到了,它就接受了。感谢您的协助!最终答案与Storax上面给出的差不多。所以我把答案归功于他。再次感谢!