(错误91:对象变量或未设置块变量)在Visual Basic 6.0中声明和访问全局变量时出错

时间:2012-02-12 17:27:23

标签: visual-studio vba adodb

我正在设计登录表单。我在一个模块中完成了全局声明:

   Global db  As ADODB.Connection
   Global rs  As ADODB.Recordset
   Global tot As Integer

   Public Sub access_connector()
   Set db = New ADODB.Connection
    db.Provider = "Microsoft.jet.oledb.4.0"
    db.CursorLocation = adUseClient
    db.Open App.Path & "\data.mdb"
  End Sub

在表单的代码窗口中:

   Private Sub Command1_Click()
   db.Open
   Set rs = db.Execute("SELECT * FROM Login Where UserName='" _
       & txtusername.Text & "'")
   If txtpassword = "" And txtusername = "" Then
      MsgBox "Login not possible"
   Else
   If Not rs.EOF() Then
      If (rs(1) = txtpassword.Text) Then
          MsgBox "Login Successful"
      Else
          MsgBox "Login not success"
      End If
   Else
      MsgBox "EOF Reached"
  End  If
 End If
 db.Close
 End Sub

但是当我点击“登录”按钮时,会出现以下错误: 错误91:对象变量或未设置块变量

实际上我认为(可能不是)它无法识别“db”和“rs”对象,因为调试“db.open”时会突出显示。

任何人都可以解决这个问题。我会非常感激。提前致谢。

1 个答案:

答案 0 :(得分:2)

我更改了你的" db"变量为" conn"强调它是一个连接,而不是一个数据库。然后,您应该在表单中打开您需要的连接。您必须在表单中指定数据库,因为您之前尚未声明数据库变量。您可能应该重新考虑全局ADODB变量,并将它们包含在您的表单代码中,但我对此并不确定。

Global conn As ADODB.Connection
Global tot As Integer

Public Sub access_connector()
Set conn = New ADODB.Connection
conn.Provider = "Microsoft.jet.oledb.4.0"
conn.CursorLocation = adUseClient
End Sub

Private Sub Command1_Click()
Dim rs As ADODB.Recordset

access_connector
conn.Open App.Path & "\data.mdb"
Set rs = conn.Execute("SELECT * FROM Login Where UserName='" & txtusername.Text & "'")
If txtpassword = "" And txtusername = "" Then
    MsgBox "Login not possible"
Else
    If Not rs.EOF() Then
        If (rs(1) = txtpassword.Text) Then
            MsgBox "Login Successful"
        Else
            MsgBox "Login not success"
        End If
    Else
        MsgBox "EOF Reached"
    End If
End If
conn.Close
End Sub