如何 return 表单最高父级的名称

How to return the name of a form's highest parent

我有子窗体,有时用父窗体打开,有时用父窗体和祖窗体打开。

如何找到子表单当前最高父级的名称?

如果那是您仅有的两种情况,您可以做两件事。检查 Mainform 是否打开或检查 Subform1.

Parent 属性

我建议使用事件,而不是依赖一串对象层次结构。因此 subform 决定需要关闭它并引发 CloseRequested 事件。然后打开的任何表单 subform 都可以对其进行操作。该操作可以是尝试关闭自身(如果它成功那么很好,它是父级)或沿着链传递它。

下面的示例不使用事件,但会在单击子表单上的按钮时关闭 parent-est 表单。

'command button on your subform
Private Sub Command0_Click()
    Dim frm As Form
    Set frm = FindHighestAncestor(Me)
    DoCmd.Close acForm, frm.Name
End Sub

Public Function FindHighestAncestor(frm As Form)
    If IsHighestLevelForm(frm) Then
        Set FindHighestAncestor = frm
    Else
        If TypeOf frm.Parent Is Form Then
            Set FindHighestAncestor = FindHighestAncestor(frm.Parent)
        Else
            Set FindHighestAncestor = frm
        End If
    End If

End Function

Public Function IsHighestLevelForm(frm As Form) As Boolean
    Dim f As Form
    For Each f In Application.Forms
        If f.Name = frm.Name Then
            IsHighestLevelForm = True
            Exit Function
        End If
    Next
    IsHighestLevelForm = False
End Function