问题
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
- Open the VBA editor (ALT-F11)
- 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
- Right click VBAProject, and choose Insert -> Module
- 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
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.
- Data > Get Data > From Database > From SQL Server Database
- Enter the Server and Database names.
- Open Advanced options and enter the query verbatim, then name it "connection_name".
- Now that the query is available, open Data > Queries & Connections.
- Right click on the connection and click Load To...
- Select an unused location on an unused sheet and put it there.
- 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