Docmd.Close没有关闭访问表单

时间:2015-10-13 06:46:37

标签: vba ms-access access-vba

我在访问时遇到vb问题。有一个主要形式(比如它是parentForm),它有两个触发两种不同形式的按钮(比如childForm1和childForm2)。两个子表单都对其Load事件执行检查。如果条件失败,则childForm必须关闭。问题是在childForm1中,代码工作正常,在childForm2中出现问题完全错误。

似乎完全忽略了关闭事件。在onLoad事件之后,该过程被执行到onCurrent事件,这不应该发生!下面是childForm2的onLoad事件的代码。

Private Sub Form_Load()
On Error Resume Next

Dim db As Database
Dim rst As Recordset
Dim stDocName As String

stDocName = "childForm2"
closeEvent = False
Set db = CurrentDb

 If a<> 0 And b<> 0 Then
    Set rst = db.OpenRecordset("SELECT * FROM tbl1 WHERE Cust Like '*" & a & "*' AND Cust2 Like '*" & b & "*';")
    If (rst.EOF Or rst.BOF) And IsLoaded(stDocName) Then
       MsgBox ("No record found!")
       rst.Close
       SetWarnings = True
       closeEvent = True
       Me.SetFocus
       DoCmd.Close acForm, stDocName, acSaveNo
    End If
ElseIf a = 0 And b <> 0 Then
    Set rst = db.OpenRecordset("SELECT * FROM tbl1 WHERE Cust2 Like '*" & b & "*';")
    If (rst.EOF Or rst.BOF) Then
       MsgBox ("No record found!")
       rst.Close
       DoCmd.Close acForm, stDocName
    End If
End If
db.Close
End Sub

此外,我尝试在表单必须关闭时使用全局布尔变量(代码中的 closeEvent ),该变量初始化为False并获得True。在onCurrent事件中检查此变量以关闭表单。但是,当我调试代码时,从onLoad传递给OnCurrent事件时,变量似乎失去了它的(True)值!

任何建议都非常感激。

提前致谢, 玛利亚

1 个答案:

答案 0 :(得分:2)

使用Form_Open事件代替Form_Load事件。

然后,使用内置的Cancel参数取消表单的开头,而不是关闭表单(= Docmd.Close)。

Private Sub Form_Open(Cancel As Integer)

   If **condition not met** then
      Cancel = True  'this stops the form from opening
   End If

End Sub