VBA 使用全局变量在 Access 2010 中打开一个表单的多个实例

VBA Using Global Variables to open Multiple instances of a form in Access 2010

我有一个表格 Cases 和显示我见过的患者的会话日期。我正在尝试创建一种方法,通过该方法我可以双击任何客户的姓名,它会打开一个包含更多详细信息的不同表格。我希望能够对多个患者执行此操作,例如,我可以 select 并为我今天要见的客户打开更详细的表格。

显示摘要详细信息的表单称为 CaseAndSessionDetail,更详细的表单称为 ClientDetails

我在 windows 8.1

下使用 Ms-Access 2010 运行

我有一个 written/copied 模块,我认为它应该通过使用全局变量来创建表单集合来做我想做的事:

Option Explicit

'This holds the collection of forms as they are created
Global mcolFormInstances As New Collection

Function OpenFormInstance(FormName As String, WhereCondition As String)
    'Declare for name
    Dim frm As form

    Select Case FormName
    Case "ClientDetails"
        Set frm = New Form_ClientDetails
    Case Else
        Debug.Assert False
    End Select
    If WhereCondition <> "" Then
        frm.Filter = WhereCondition
        frm.FilterOn = True
    End If
    ''make the form visible
    frm.Visible = True
    'Need to add a reference to the form so that it does not
    'immediately close when the for variable goes out of scope
    mcolFormInstances.Add (frm)
End Function

如果您在最后一行 mcolFormInstances.Add(frm) 处设置断点,则该函数可以正常工作,并且 selects 和 opens/display 会形成正确的客户详细信息。如果没有断点,表单将再次关闭(我怀疑是因为变量在函数结束后超出范围。

作为参考,该函数由 "CaseAndSessionDetail"

形式的宏调用
If Not ISNull([Screen].[ActiveControl] Then 
    Function OpenForm("frmContactDetails" = '"& Ltrim([Screen].[ActiveControl]) & "'") 
EndIF

我怀疑我没有正确地将集合对象声明为全局变量。我尝试使用 PublicGlobal 在单独的模块中以两种形式声明它,但尚未成功。

我意识到我可能忽略了一些非常简单的事情,但欢迎任何帮助

您的问题只是这一行的一个晦涩的语法错误:

mcolFormInstances.Add (frm)

参数 frm 周围的括号是 而不是 围绕参数列表 - 这就是 VBE 插入 space 介于 .Add(frm) 之间,当您尝试键入 mcolFormInstances.Add(frm) 时。这些在语义上是完全不同的。在 VBA 语言规范的第 5.6.6 节中描述了在此上下文中用括号包围表达式:

5.6.6 Parenthesized Expressions

A parenthesized expression consists of an expression enclosed in parentheses.

Static semantics. A parenthesized expression is classified as a value expression, and the enclosed expression must able to be evaluated to a simple data value. The declared type of a parenthesized expression is that of the enclosed expression.

 parenthesized-expression = "(" expression ")"

Runtime semantics. A parenthesized expression evaluates to the simple data value of its enclosed expression. The value type of a parenthesized expression is that of the enclosed expression.

这意味着您正在将 运行 时间表达式 frm 作为简单数据类型进行评估,并将 that 存储在 Collection.不管这个值实际上 (我必须检查评估树以确定它的评估结果),你不是增加 frm 上的引用计数,这允许它超出范围并在 OpenFormInstance 退出时被释放。