簡體   English   中英

ADODB連接的有趣問題:從VBA代碼調用時,使用ADODB的UDF可以正常工作,但是從EXCEL單元調用時,它將返回錯誤

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

我的問題是:

  • 從另一個VBA子函數或函數調用該代碼時,它的效果很好。
  • 但是,從一個Excel單元格作為UDF函數調用此函數時,此函數返回以下錯誤:

“參數類型錯誤,超出可接受范圍或彼此沖突。” (錯誤號3001)

我真的不明白,為什么一組代碼在被VBA編輯器調用時不返回錯誤,而在從一個excel單元作為用戶定義函數調用時卻返回此錯誤!

任何幫助表示贊賞。

最好的祝福,

根據定義,UDF需要返回某些內容,而您缺少以下返回類型:

Public Function ODPH(B0 As Range, sqlstr As Variant) As Variant

從另一個宏調用它是可行的,因為VBA(或幾乎所有編程語言)並不真正在乎您是否具有函數的接收變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM