ADODB连接有趣的问题:使用ADODB的UDF在从VBA代码调用时工作正常,但从EXCEL单元调用时返回错误

我一直使用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函数时会返回以下错误:

“争论是错误的types,超出了可以接受的范围,或是相互冲突。” (错误号码3001)

我真的不明白为什么一组代码在被VBA编辑器调用时没有返回任何错误,而当它从一个Excel单元格作为一个用户定义的函数调用时,它会返回这个错误!

任何帮助表示赞赏。

最好的祝福,

根据定义,UDF需要返回一些东西,而你却缺less返回types,如:

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

从另一个macros调用它的工作,因为VBA(或几乎所有的编程语言)并不真正关心,如果你有一个函数的接收variables。