[英]Interesting issue with ADODB connection: UDF using ADODB works fine when called from VBA code, but it returns error when called from EXCEL cell
我一直在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单元作为用户定义函数调用时却返回此错误!
任何帮助表示赞赏。
最好的祝福,
根据定义,UDF需要返回某些内容,而您缺少以下返回类型:
Public Function ODPH(B0 As Range, sqlstr As Variant) As Variant
从另一个宏调用它是可行的,因为VBA(或几乎所有编程语言)并不真正在乎您是否具有函数的接收变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.