Some years ago I wrote a number of functions to read accounting data from my software in Excel. It was moderately useful. It doesn't profess to be best code practice, just what I could do at the time.
Below is an example; all the functions followed the same principle, with more complex Select statements in some cases. I found MS Query very useful in designing those, especially where date ranges are involved.
You can write your own function if you create a DSN to the database and modify the select statement below. This implies that you know the tables and relationships in your database.
This particular function would be called as a UDF, eg
=Accountname(A1,DSNname) - the parameters refer to two other cells
Public Function AccountName(AccountNum As String, Optional DSN As String = "DSNNAME") As String
'
' Function to read accountname from data file
'
Dim oConn As Object
Dim oRS As Object
Dim sSQL As String
Dim myResult
Set oConn = CreateObject("ADODB.Connection")
' Tailor the drivername to suit
oConn.Open "Driver:={Drivername};DSN=" & DSN & ";"
Set oRS = CreateObject("ADODB.Recordset")
With oRS
.CursorLocation = adUseClient
.Cursortype = adOpenStatic
End With
' Tailor this to your software
sSQL = "Select Accounts.AccountName FROM Accounts " & "WHERE (Accounts.AccountNumber = '" & AccountNum & "')"
oRS.Open sSQL, oConn
myResult = oRS.GetRows()
AccountName = myResult(0, 0)
oRS.Close
Set oRS = Nothing
oConn.Close
Set oConn = Nothing
End Function
Bookmarks