VBA excel中的运行时错误91用于ADODB.Recordset
在我尝试在我的Excel应用程序中发送一个sql语句后,我得到了运行时错误91。 这是下面的代码:
'Module Consts: Public rst1 As New ADODB.Recordset 'defined in a constants module 'Module Conn: Public Sub GetDynSQLQuery(ByVal strQuery$, ByVal rs As ADODB.Recordset) Set rs = Nothing If cn = "" Then Call ConnectToDb 'Sub set the variable "cn" with connectionstring to db and open the connection With rs .Source = strQuery 'Here comes the error .ActiveConnection = cn .CursorType = adOpenForwardOnly .LockType = adLockReadOnly .Open End With End Sub 'Form1: strSql = "SELECT * FROM tbl1" Call GetDynSQLQuery(strSql, rst1)
错误信息:
对象variables或With块variables未设置
我做错了什么我看不到。
你在子文件中做的第一件事是你清空你刚刚通过的参数(使用Set rs = Nothing
),然后再使用rs
。
所以除了rs
是一个类似Public的variables,并且它被填充到ConnectToDb
,
在使用之前它仍然是空的,错误的错误!
首先,尝试删除Set rs = Nothing
,如果不够用,则需要查看ConnectToDb
!
其次,你修改里面的logging集,但你尝试在外面使用它。
而这里的问题是使用了ByVal
,它传递了对象引用的副本,所以你不能修改初始对象,因为RecordSet在Sub!之外是空的。 ;)
并且,当OPtestingrst1.RecordCount > 0
是错误的( rst1.RecordCount
等于-1)时,
他通过将.CursorType
设置为adOpenKeySet
而不是adOpenForwardOnly
来修复它
Public Sub GetDynSQLQuery(ByVal strQuery$, rs As ADODB.Recordset) 'Sub set the variable "cn" with connectionstring to db and open the connection If cn = vbNullString Then Call ConnectToDb With rs .Source = strQuery 'No more error!^^ .ActiveConnection = cn .CursorType = adOpenKeySet .LockType = adLockReadOnly .Open End With End Sub