简体   繁体   中英

UDF to retrieve data from access data base

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.

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

选择细胞

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM