【问题标题】:Is there a built in MS Access VBA Event to simplify Data Verification and SetFocus是否有内置的 MS Access VBA 事件来简化数据验证和 SetFocus
【发布时间】:2018-07-10 16:53:21
【问题描述】:

这里有点菜鸟问题。您如何使用 Access Events 处理数据验证?问题是,当我使用 SetFocus 将光标返回到包含错误数据的字段时,Access 会通过 Tab Order 中下一个控件的 _Exit 和/或 _LostFocus 事件。如果这些包括数据验证过程,则绕过所需的 SetFocus。

使用techturtles answer,我想出了这个“解决方案”(阅读“hack”)。

Private Sub ServicingEmployee_LostFocus() 'Check data validity
    If dataEntryCancelled Then Exit Sub

    Dim cntrl As Control
    Set cntrl = Me.ServicingEmployee
    Dim myResponse As Integer

    If IsNull(cntrl.Value) Then

        myResponse = MsgBox("This field cannot be left blank.", vbOKOnly, "Enter Date Collected")
        dataErrorInPreviousField = True
        **'Next line sets a Public Control**
        Set controlWithDataEntryError = Me.ServicingEmployee
    End If

End Sub

Private Sub Client_GotFocus() '**Check for data Error in previous Control according to Tab Order**
    If dataErrorInPreviousField Then Call dataErrorProc
End Sub

Public Sub dataErrorProc()
    With controlWithDataEntryError
        .SetFocus
        .SelStart = 0
        .SelLength = Len(.Text)
    End With
    dataErrorInPreviousField = False

End Sub

Private Sub Client_Exit(Cancel As Integer) '**Example of Bypassing _Exit Event**
    If dataEntryCancelled Or dataErrorInPreviousField Then Exit Sub
    .
    ...
End Sub    

我的问题是:有没有更简单的方法可以做到这一点?

【问题讨论】:

  • 考虑控件的 BeforeUupdate 事件。而不是 LostFocus。
  • 我同意@HansUp - 控件的BeforeUpdate 更新最适合单个字段验证检查。表单的BeforeUpdate 事件非常适合检查整个表格中必填字段中的空白条目
  • @dbmitch,你之前至少回答了我的一个问题,所以我有一个相关的问题。你熟悉 VB.net 吗?过渡到 VB.net 值得学习曲线吗?我熟悉 Objective C。
  • 我根本不会在 VB.Net 中编码

标签: validation ms-access vba


【解决方案1】:

首先,我强烈建议您在表单验证之外添加表格约束(如果您还没有这样做的话)。假设此表单与 Access 中的表相关联,只需确保 ServicingEmployee 字段(在表中)设置为必需。这样,您就有了另一个级别的验证,以确保该字段具有值。

对于表单验证,您可以使用表单或控件的BeforeUpdate 事件。如果您使用表单的事件,您只需运行一次检查。

我还建议有一个单独的函数(在表单内)来检查有效性。像这样的东西(在这里,我使用一个绑定到员工表的表单,名字和最后一个字段都应该是非空的):

Private Function isFormValid() As Boolean
   ' we start off assuming form is valid
   isFormValid = True

   If IsNull(Me.txtFirstName) Then
      MsgBox "First name cannot be blank", vbOKOnly
      Me.txtFirstName.SetFocus
      isFormValid = False
   ElseIf IsNull(Me.txtLastName) Then
      MsgBox "Last name cannot be blank", vbOKOnly
      Me.txtLastName.SetFocus
      isFormValid = False
   End If
End Function

Private Sub Form_BeforeUpdate(Cancel As Integer)
   If Not isFormValid Then
      Cancel = 1
   End If
End Sub

【讨论】:

    猜你喜欢
    • 2012-08-17
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2012-12-29
    • 1970-01-01
    • 2014-08-18
    • 2021-10-18
    相关资源
    最近更新 更多