2

我得到了这个示例代码:

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

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

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

4

1 回答 1

2

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

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

(“名称”不是变量的好名称,因为它是保留字。)

于 2012-12-12T12:23:36.873 回答