VBA Access 检查父表单是否存在

5
在MS Access中,我正在从另一个对话框表单打开一个对话框表单。
所以,formA 打开 formB。但是用户可能会单独打开 formB,我想避免出现错误。
我考虑检查 formB 是否存在父对象。
但是当我这样做时,仍然会出现错误 2452:您输入的表达式具有无效的 Parent 属性。
我尝试过:
If Not IsError(Me.Parent) Then
    Me.Parent.cboTraining.Requery
End If

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

1
一个控件有一个父级,但独立的表单没有。请尝试使用IsLoaded函数。https://msdn.microsoft.com/zh-cn/library/office/ff194656.aspx - Fionnuala
7个回答

5

您可以使用以下代码来测试表单是否已打开:

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

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


2

这是我的解决方案。

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

2
这种方法与上面类似:https://dev59.com/JY7ea4cB1Zd3GeqPGtpQ#53582533
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

旨在更为通用,可以从子表单/子报表中调用,如下所示:
If hasParent(Me) Then
   msgbox "Has Parent :)"
   Me.Parent.text1 = "Yes"
else 
   msgbox "NO PARENTS .. :("
endif

1

我的有时子表单从多个表单中调用,因此我在我的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

0

这里是另一个例子。

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

0

要找到任何独立的开放形式,请尝试以下方法:

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

0

我的简短版本,以及另一个方便的函数:

Public Function HasParent(v As Variant) As Boolean
On Error Resume Next
HasParent = IsSomething(v.Parent)
End Function

Public Function IsSomething(ob As Object) As Boolean
  IsSomething = Not ob Is Nothing
End Function

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接