我得到了这个示例代码:
<!-- language: lang-vb -->
Option Compare Database
Private Function get_relation() As String
get_relation = CurrentDb.Relations(1).name
Debug.Print "Inside get_relation() relation name is " & get_relation
' Inside get_relation() relation name is Table1Table2
Debug.Print "Again, the name is " & CurrentDb.Relations(get_relation).name
' Again, the name is Table1Table2
End Function
Public Sub test()
Dim R As DAO.Relation, name As String
name = get_relation()
Debug.Print "Outside, the name is still " & name
' Outside, the name is still Table1Table2
Set R = CurrentDb.Relations(name)
Debug.Print "Again, the name is " & R.name
' At the line above it throws error!
End Sub
输出为:
Inside get_relation() relation name is Table1Table2
Again, the name is Table1Table2
Outside, the name is still Table1Table2
然后出现错误:
Runtime error '3420':
Object invalid or no longer set.
这是我在 watch 中看到的:
Watch : : Name : "Table1Table2" : String : Playground.test
Watch : - : CurrentDb.Relations(Name) : : Object/Relation : Playground.test
: Attributes : <Object invalid or no longer set.> : Long : Playground.test
: Fields : <Object invalid or no longer set.> : Fields : Playground.test
: ForeignTable : <Object invalid or no longer set.> : String : Playground.test
: Name : <Object invalid or no longer set.> : String : Playground.test
: PartialReplica : <Object invalid or no longer set.> : Boolean : Playground.test
: Properties : <Object invalid or no longer set.> : Properties : Playground.test
: Table : <Object invalid or no longer set.> : String : Playground.test
Watch : - : R : : Relation/Relation : Playground.test
: Attributes : <Object invalid or no longer set.> : Long : Playground.test
: Fields : <Object invalid or no longer set.> : Fields : Playground.test
: ForeignTable : <Object invalid or no longer set.> : String : Playground.test
: Name : <Object invalid or no longer set.> : String : Playground.test
: PartialReplica : <Object invalid or no longer set.> : Boolean : Playground.test
: Properties : <Object invalid or no longer set.> : Properties : Playground.test
: Table : <Object invalid or no longer set.> : String : Playground.test
因此,在某些时候我的 DAO.Relation R 被取消设置(或者至少它的所有成员都被取消设置)。此外,CurrentDB.Relations("Table1Table2") 和 CurrentDB.Relations(1) 处于相同状态(所有成员均无效或未设置)。
同时,通过 watch 检查的 CurrentDB.Relations 显示所有成员均已设置,并且一切似乎都正常。
我知道我的问题不是很具体,但我真的不明白。有什么提示吗?
最佳答案
您使用 CurrentDb 而不是显式变量分配给 R,因此它超出了范围。而是使用:-
dim db as dao.database
set db = currentdb
...
dim r as dao.relation
set r = db.relations (rname)
(“name”不是一个好的变量名称,因为它是保留字。)
关于ms-access - MS Access 2007 VBA DAO.Relation 对象神秘地未设置。这是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13838068/