VBA 访问检查父表单是否存在

VBA Access check if Parent form exists

在 MS Acces 中,我从另一个对话框窗体打开一个对话框窗体。

因此 formA,打开 formB。但是他们的用户可以独立打开 formB,我想避免在这种情况下出现错误。

我考虑过检查 formB 的现有父级。

但是当我这样做时,我仍然得到错误 2452:您输入的表达式对父项无效 属性。

我试过了:

If Not IsError(Me.Parent) Then
    Me.Parent.cboTraining.Requery
End If

If Not IsNull(Me.Parent) Then
    Me.Parent.cboTraining.Requery
End If

要查找任何独立的打开表单,试试这个:

Sub test()
Dim i
For i = 0 To Forms.Count - 1
    Debug.Print Forms.Item(i).Name
    If Forms.Item(i).Name Like "formA" Then MsgBox "It's Open"
Next i
End Sub

您可以使用以下方法测试表单是否打开:

If Not CurrentProject.AllForms("someFormName").IsLoaded Then

或者,当您从 formA 打开 formB 时,您可以提供一个 openArg,这很容易测试。

这是另一个例子。

Const conObjStateClosed = 0
Const conDesignView = 0

If SysCmd(acSysCmdGetObjectState, acForm, strFormName) <> conObjStateClosed Then
    If Forms(strFormName).CurrentView <> conDesignView Then
        MC_FormIsLoaded = True
    End If
End Ifere

我的子表单有时会被多个表单调用,所以我基于捕获错误的简单想法向我的 ss_utilities 模块添加了一个通用函数:

Public Function hasParent(ByRef p_form As Form) As Boolean
'credit idea from https://access-programmers.co.uk/forums/showthread.php?t=157642
On Error GoTo hasParent_error
    hasParent = TypeName(p_form.Parent.Name) = "String"
    Exit Function
hasParent_error:
    hasParent = False
End Function

所以原始问题的代码是:

If ss_utilities.hasParent(Me) Then
    Me.Parent.cboTraining.Requery
End If

这种方法类似于上面的方法:

Public Function hasParent(F As Object) As Boolean
'Inspired from: https://access-programmers.co.uk/forums/showthread.php?t=293282   @Sep 10th, 2019
   Dim bHasParent As Boolean
   On Error GoTo noParents

   bHasParent = Not (F.Parent Is Nothing)
   hasParent = True
   Exit Function

noParents:
   hasParent = False
End Function

旨在更通用,并且可以从两个 subforms/subreports 调用,如下所示:

If hasParent(Me) Then
   msgbox "Has Parent :)"
   Me.Parent.text1 = "Yes"
else 
   msgbox "NO PARENTS .. :("
endif

这是我的解决方案。

Public Function CheckParentFormExists(P_Form As Form) As Boolean
On Error GoTo Err_Hendler
    Dim P_ParentForm As String
    P_ParentForm = P_Form.Parent.Name
    CheckParentFormExists = True
    
Exit_1:
    Exit Function
Err_Hendler:
    If Err.Number = 2452 Then
        CheckParentFormExists = False
        GoTo Exit_1
    Else
        Debug.Print Err.Number & Err.Description
    End If
End Function

调用示例:

if CheckParentFormExists(me) then
    ....
Else

End if