首页 > 解决方案 > 参考父属性

问题描述

我有一个在某些情况下没有父母的表格。
然后它无法打开。
所以我把它包装在一个“如果”中
它仍然无法打开。

Private Sub Form_Open(Cancel As Integer)
    If Not Parent Is Nothing Then  << Error
        Me!Button1.Enabled = Not (Nz(Parent!Lock, 0))
        Me!Button2.Enabled = Not (Nz(Parent!Lock, 0))
    End If
End Sub

给出“运行时错误'2452':您输入的表达式对父属性的引用无效。”
但是如果我声明变量,那么原始代码将不起作用。

标签: ms-access

解决方案


这是一个棘手的问题,就好像表单没有父级一样,对属性的任何访问(即使测试它是否为空)都会触发错误。

最简单的解决方法是使用错误捕获进行测试:

Public Function HasParent(obj As Object) As Boolean
    On Error GoTo ExitFunction
    If Not obj.Parent Is Nothing Then
        HasParent = True
    End If
ExitFunction:
End Function

Private Sub Form_Open(Cancel As Integer)
    If HasParent(Me) Then 
        Me!Button1.Enabled = Not (Nz(Parent!Lock, 0))
        Me!Button2.Enabled = Not (Nz(Parent!Lock, 0))
    End If
End Sub

推荐阅读