gpt4 book ai didi

mysql - ADODB 连接 : UDF using ADODB works fine when called from VBA code, 的有趣问题,但从 EXCEL 单元格调用时返回错误

转载 作者:行者123 更新时间:2023-11-29 06:36:18 28 4
gpt4 key购买 nike

我一直在 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(或几乎所有编程语言)并不关心您是否有函数的接收变量。

关于mysql - ADODB 连接 : UDF using ADODB works fine when called from VBA code, 的有趣问题,但从 EXCEL 单元格调用时返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24493555/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com