In general, I've been looking for how to properly check that an object is assigned.
In this particular case, it is the parent property.
I have forms that sometimes have a parent, and have slightly different behavior on resizing.
But this code
If (Not Parent Is Nothing) Then
MsgBox "Is Nothing says Parent is Assigned"
Else
MsgBox "Is Nothing says Parent is not Assigned"
End If
If (IsObject(Parent)) Then
MsgBox "IsObject says Parent is Assigned"
Else
MsgBox "IsObject says Parent is not Assigned"
End If
both work fine if there is a parent and both give an error if not.
Run-time error '2452' The expression you entered has an invalid reference to the Parent property.
Is the only hope to catch the error and handle it there?
CodePudding user response:
You can check, if the form is opened as a main form:
If IsFormOpen(Me.Name) Then
MsgBox Me.Name & " has no parent."
Else
MsgBox Me.Name & " has a parent."
End If
' Checks if a form by name is open in the current database.
' Returns True if it does, False if not.
'
' 2011-10-10, Cactus Data ApS, Gustav Brock
'
Public Function IsFormOpen(ByVal FormName As String) As Boolean
Dim Form As Form
For Each Form In Forms
If Form.Name = FormName Then
Exit For
End If
Next
IsFormOpen = Not Form Is Nothing
End Function
CodePudding user response:
If you know the name of form(s) that form could be installed on as subform, can either loop through Forms collection and test if one equals "parent" form name (see @Gustav answer) or use IsLoaded method to test if a specific form is open in Forms collection (If CurrentProject.AllForms("DataBituminous").IsLoaded Then
). Form when used as subform will not be in Forms collection.
If you don't want to hard-code parent form name, then use error handling code to deal with missing parent. Example found at https://www.access-programmers.co.uk/forums/threads/how-to-check-if-a-form-has-a-parent-form.157642/
Private Property Get HasParent As Boolean
On error GoTo handler
HasParent = Typename(Me.Parent.Name) = "String"
Exit Property
handler:
End Property