Home » excel » excel – UDF to retrieve data from access data base

excel – UDF to retrieve data from access data base

Posted by: admin April 23, 2020 Leave a comment


How do i create a UDF to retrieve data from the access database.

I can retrieve the data via sql query using vba & click button. the data will be in the recordset. I simply paste it to any cell.

Now my question is: How can I create a user defined function to do the same. That is to say, when I enter something like =bdh(pricing date,product tag) into any Excel cell, all the data will be returned and pasted below the cell where I entered the self-defined formula.

If you are familiar with bloomberg API, i want to build a function similar to bdh function.

How to&Answers:

Perhaps you could work around a simpler idea? For example the code snippet below depends on the user selecting two input cells to control the output. You could add a menu item to run the code.

Sub GetMSAccess()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim selrange As Range

    Set selrange = Selection

    strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Z:\Docs\Test.accdb"

    cn.Open strCon

    sSQL = "SELECT var1, var2 FROM table2 " _
    & "WHERE var1='" & selrange.Cells(1, 1).Value _
    & "' AND var2=" & selrange.Cells(1, 2).Value
    rs.Open sSQL, cn

    ActiveCell.Offset(1, 0).CopyFromRecordset rs
End Sub

For example

select cells