我一直在Excel中使用ADODB连接,以便连接到MySql数据库并检索值。
我的代码的本质如下:
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
我的问题是:
“参数类型错误,超出可接受的范围,或彼此冲突。” (错误号3001)
我真的不明白为什么一组代码在被VBA编辑器调用时没有返回错误,而当它从一个excel单元作为用户定义函数调用时会返回此错误!
感谢任何帮助。
致以最诚挚的问候,
答案 0 :(得分:2)
根据定义,UDF需要返回一些内容,并且您缺少返回类型,如:
Public Function ODPH(B0 As Range, sqlstr As Variant) As Variant
从另一个宏调用它是有效的,因为如果你有一个函数的接收变量,VBA(或几乎所有的编程语言)并不在乎。