MS Access 2007 VBA DAO.关系对象神秘地被取消设置。这是怎么回事?



我得到了这个示例代码:

<!-- 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 :   : 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。关系 R 未设置(或者至少它的所有成员都未设置)。此外,更多的 CurrentDB.Relations("Table1Table2") 和 CurrentDB.Relations(1) 处于相同的状态(所有成员都无效或未设置)。

同时,通过手表检查的CurrentDB.Relations显示所有成员都已设置好,一切似乎都正常。

我知道我的问题不是很具体,但我真的不明白。有什么提示吗?

您使用 CurrentDb 而不是显式变量分配给 R,因此它超出了范围。而是使用:-

dim db as dao.database
set db = currentdb
...
dim r as dao.relation
set r = db.relations (rname)

("name"对于变量来说不是一个好名字,因为它是一个保留字。

最新更新