I have been using ADODB connection from within Excel in order to connect to MySql databases and retrieve values.
The essence of my code is as follows:
Public Function ODPH(B0 As Range, sqlstr As Variant)
Dim oconn As ADODB.Connection
Dim rs As ADODB.Recordset
On Error GoTo error_handler
'Connect to MySql. Assign default values if connection string is missing!
ipDriver = "{MySQL ODBC 5.2 Unicode Driver}"
ipType = "MySql"
If IsEmpty(ipHost) Then ipHost = "HHHH"
If IsEmpty(ipUser) Then ipUser = "UUUU"
If IsEmpty(ipdbName) Then ipdbName = "DDDD"
If IsEmpty(ipPasswd) Then ipPasswd = "PPPP"
strConn = "DRIVER=" & ipDriver & ";" & _
"SERVER=" & ipHost & ";" & _
"DATABASE=" & ipdbName & ";" & _
"USER=" & ipUser & ";" & _
"PASSWORD=" & ipPasswd & ";" & _
"Option=" & ipOption
Set oconn = New ADODB.Connection
oconn.Open strConn
oconn.CursorLocation = adUseClient
'oconn.CursorLocation = adUseServer
Set rs = New ADODB.Recordset
' rs.Open sqlstr, oconn, adLockOptimistic
' rs.Open sqlstr, oconn, adLockReadOnly
rs.Open sqlstr, oconn, adOpenStatic, adLockOptimistic
rs.Open sqlstr, oconn
If rs.EOF Then
'MsgBox "No records returned!"
ODPH = "#No record at db"
Exit Function
Else
'rs.MoveLast
rCount = rs.RecordCount
Select Case rCount
Case Is > 1
ODPH = "#many records from db"
Exit Function
Case Else
Select Case rs.Fields.Count
Case Is > 1
ODPH = "#many columns from db"
Exit Function
Case Else
Select Case IsNull(rs.Fields(0).Value)
Case Is = True
ODPH = "#null at db"
Exit Function
Case Else
aux = rs(0).Value
Select Case IsNumeric(aux)
Case Is = True
ODPH = CDbl(aux)
Exit Function
Case Else
ODPH = aux
Exit Function
End Select
End Select
End Select
End Select
End If
'Error handler
error_handler:
ODPH = Err.Description
Exit Function
End Function
My issue is that:
"Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another." (Error number 3001)
I really could not understand why one set of code returns no error when it is called by VBA editor whereas it returns this error when it is called from one excel cell as a user-defined function!
Any help is appreciated.
Best regards,
By definition, UDF needs to return something and you are missing the return type like:
Public Function ODPH(B0 As Range, sqlstr As Variant) As Variant
Calling it from another macro works, because VBA (or almost all programming languages) don't really care if you have a receiving variable of function.
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.