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.
You can write a custom function to do that
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With