vba (错误 91:未设置对象变量或块变量)在 Visual Basic 6.0 中声明和访问全局变量时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9250912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
(Error 91 : object variable or with block variable not set) Error in declaring and accessing global variable in Visual Basic 6.0
提问by Pragya Dalal
I am designing a login form. I have done global declaration in in a module:
我正在设计一个登录表单。我在一个模块中做了全局声明:
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
And in the form's code window :
在表单的代码窗口中:
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
But when I click on Login button the following error occurs : Error 91 : object variable or with block variable not set
但是,当我单击登录按钮时,会发生以下错误: 错误 91:未设置对象变量或块变量
Actually I think (may not be true) it is not able to recognize "db" and "rs" objects, as while debugging "db.open" is highlighted.
实际上我认为(可能不是真的)它无法识别“db”和“rs”对象,因为在调试“db.open”时突出显示。
Can anyone please solve this problem. I would be very thankful. Thanks in advance.
任何人都可以解决这个问题。我会很感激的。提前致谢。
回答by Doug Glancy
I changed the name of your "db" variable to "conn" to emphasize the fact that it's a connection, not a database. Then, you should open the connection when you need it, in the form. You have to specify the database in the form, as you haven't declared a database variable earlier. Probably you should re-think the global ADODB variables and just include them in your form code, but I'm not sure about that.
我将“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