执行代码时的运行时错误91

时间:2014-04-28 08:12:26

标签: vb6

在VB6中执行以下代码时,我收到'运行时错误91对象变量或未设置块变量'。我做错了什么?

Private Sub btn_Test_Click()
    Dim dt As ADODB.Recordset
    Dim sql As String
    sql = "select * from Reg_User"
    Set dt = myconn.getdatatab(sql)      ' here i am getting error
End Sub

班级代码是

Private provider As String
Private dt As ADODB.Recordset
Private Const DEF_LOCKTYPE = adLockReadOnly
Private Const DEF_CURSORTYPE = adOpenKeyset

Public Function getdatatab(sql As String) As ADODB.Recordset
    Dim cnnmain As ADODB.Connection

    cnnmain.Open "Driver=SQL Server;uid=sa;pwd=abcd;Database=Test;Server=pos001-pc\SQLEXPRESS2;"

    Set dt = New ADODB.Recordset
    Set dt.ActiveConnection = cnnmain
    dt.Open sql, , DEF_CURSORTYPE, DEF_LOCKTYPE
    If dt.EOF And dt.BOF Then
        Set getdatatab = dt
    Else
        dt.MoveFirst
        Set getdatatab = dt
    End If
    cnnmain.Close

End Function

1 个答案:

答案 0 :(得分:0)

[提供正确代码后的编辑]

在使用对象变量之前,必须实例化一个类。看起来你曾尝试使用cnnmain而没有实例化它。

代码片段:

Public Function getdatatab(sql As String) As ADODB.Recordset
    Dim cnnmain As ADODB.Connection

    cnnmain.Open "Driver=SQL Server;uid=sa;pwd=abcd;Database=Test;Server=pos001-pc\SQLEXPRESS2;"  ' <====== ERROR OCCURS HERE
    ...
End Function

......应该是:

Public Function getdatatab(sql As String) As ADODB.Recordset
    Dim cnnmain As ADODB.Connection

    Set cnnmain = New ADODB.Connection
    cnnmain.Open "Driver=SQL Server;uid=sa;pwd=abcd;Database=Test;Server=pos001-pc\SQLEXPRESS2;"  ' <====== ERROR OCCURS HERE
    ...
End Function