[英]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.