通过连续形式访问循环

时间:2017-07-20 13:36:44

标签: vba ms-access

我正在尝试将VBA添加到命令按钮以查看文本框,如果不为null,则查看组合框。如果该组合框为null,则弹出消息框。由于它是一个连续的形式,并且有几个记录显示,它在第一个记录上工作正常,但它不适用于以下记录。我相信这是因为我需要遍历每条记录。下面是我到目前为止的VBA代码。我非常感谢有关循环的任何帮助,因为我是VBA的新手。

If Not IsNull(Me.Text33.Value) Then
    If IsNull(Me.Combo24.Value) Then
        MsgBox "You must state if the rationale is aligned with procedures for each disputed subcategory."
    Else
     'do nothing
    End If
End If

DoCmd.Save
DoCmd.Close

提前谢谢你,

苏珊

1 个答案:

答案 0 :(得分:1)

由于这是一个连续的表单,您可以克隆表单的记录集并在每个记录中循环。

Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
    rs.MoveLast
    rs.MoveFirst

Dim idx As Integer
For idx = 1 To rs.RecordCount
    If Not IsNull(rs![TextBoxFieldName]) Then If IsNull(rs![ComboBoxFieldName]) Then MsgBox "..."
    rs.MoveNext
Next idx

Set rs = Nothing

With DoCmd
    .Save
    .Close
End With

请注意,如果用于验证目的,无论消息框错误/警告如何,DoCmd操作都将始终执行。

您可以在显示消息框后添加Exit Sub来更改此设置。

修改

Sub Example()

    Dim rs As DAO.Recordset
    Set rs = Me.RecordsetClone
        rs.MoveLast
        rs.MoveFirst

    Dim idx As Integer
    For idx = 1 To rs.RecordCount
        Select Case True
            Case Not IsNull(rs![ComboFieldName]) And IsNull(rs![TextBoxFieldName]):
                MsgBox "You must enter dispute comments for each disputed subcategory."
                GoTo Leave

            Case IsNull(rs![ComboFieldName]) And Not IsNull(rs![TextBoxFieldName]):
                MsgBox "You must state if the rationale is aligned with procedures for each disputed subcategory."
                GoTo Leave

            Case Else:
                'do nothing
        End Select
        rs.MoveNext
    Next idx

    Set rs = Nothing
    With DoCmd
        .Save
        .Close
    End With
    Exit Sub

Leave:
    Set rs = Nothing
End Sub