How to write an Excel function which returns a value from an SQL database?

孤者浪人 提交于 2019-12-07 17:26:57

问题


I want to write the following function which should be used in an Excel worksheet:

=GetRecField("Foo Record Key", "FooField1")

...which will connect internally through ODBC to an SQL database, execute there an

SELECT FooField1 FROM MyTable WHERE KEY_FIELD='Foo Record Key';

and will return the resulting value as the result of the function GetRecField. The above SQL is granted to return only one record (IOW KEY_FIELD has an unique constraint).

Of course, the above function can be called multiple times in a worksheet so, please try to avoid a blind QueryTables.Add

TIA.


回答1:


You can write a custom function to do that

  1. Open the VBA editor (ALT-F11)
  2. Open Tools -> References, and make sure the "Microsoft ActiveX Data Objects 2.8 Library" and "Microsoft ActiveX Data Objects Recordset 2.8 Library" are selected
  3. Right click VBAProject, and choose Insert -> Module
  4. Open the module. Now you can create a custom function, like:
    Public Function GetItem(field As String, id As Integer) As String
        Set oConnection = New ADODB.Connection
        Dim oRecordset As ADOR.Recordset
        oConnection.Open "provider=sqloledb;data source=yourserver;" & _
            "Trusted_Connection=yes;initial catalog=yourdatabase;"
        Set oRecordset = oConnection.Execute( & _
            "select " & field & " from table where id = " & id)
        If oRecordset.EOF Then
            GetItem = "n/a"
        Else
            GetItem = oRecordset(field)
        End If
    End Function
  1. You can now call the function from a cell:

    =GetItem("fieldname";2)

The module is required because non-module functions can't be called from inside the spreadhseet.




回答2:


Why not use Excel's built-in database query functionality on a separate sheet (Data menu, Import External Data, New Database Query), then use VLOOKUP to extract values from that sheet?




回答3:


I solved a similar problem in Excel version 1808(?) by saving the database connection in one sheet and using a reference to the desired cell in other sheets.

  1. Data > Get Data > From Database > From SQL Server Database
  2. Enter the Server and Database names.
  3. Open Advanced options and enter the query verbatim, then name it "connection_name".
  4. Now that the query is available, open Data > Queries & Connections.
  5. Right click on the connection and click Load To...
  6. Select an unused location on an unused sheet and put it there.
  7. In the target cell elsewhere in the file, enter =connection_name[[#All,][Column1]].

This certainly seems indirect in that I couldn't find a way to refer to the connection without it appearing in a sheet somewhere. But it worked for me and I wasn't able to find similar instructions elsewhere so I thought it could be informative.



来源:https://stackoverflow.com/questions/836065/how-to-write-an-excel-function-which-returns-a-value-from-an-sql-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!