VBA to prevent empty fields in a user-entry form

折月煮酒 提交于 2019-12-11 02:54:15

问题


I am having trouble with VBA coding which I am using to check for blank fields in a pop-up form. The code is supposed to check for blank fields on the form, notify the user if there are blank forms, and if there isn't, add the record. I have a second function which saves the record, then closes the form. Below is the code I am using to check for blanks:

Private Sub Form_BeforeUpdate(Cancel As Integer)

Dim ctrl As Control
Dim strMsg As String

For Each ctrl In Me.Controls

    If ctrl.Tag = "BlkChk" Then
        If IsNull(ctrl) Then
           strMsg = strMsg & "- " & ctrl.Name & vbCrLf
        End If
    End If

Next ctrl

If strMsg <> "" Then
    If vbOK = MsgBox("The following fields require a response:" & vbCrLf & vbCrLf & _
       strMsg & vbCrLf & vbCrLf, _
       vbOKOnly) Then
       Cancel = True

       Me.cboLookup.SetFocus
    End If

End If

End Sub

Here is the code for my 'add record' button:

Private Sub cmdAddRecord_Click()
On Error GoTo cmdAddRecord_Click_Err

    DoCmd.Save
    DoCmd.Close , ""

cmdAddRecord_Click_Exit:
    Exit Sub

cmdAddRecord_Click_Err:
    MsgBox Error$
    Resume cmdAddRecord_Click_Exit

End Sub

The first bit of code works fine, but when I click my 'add record' button, and execute my second bit of code, it will notify the user twice, then close the form without saving, regardless if all blanks are filled in or not. I've went through several examples online about how other people have set it up to see if I could implement their ideas, but it's just not working for me. I think it might have something to do with the 'add record' code, but I can't seem to figure it out. How should I approach this problem? should I restructure my coding or should I combine it all into a single On_Click() command?


回答1:


You're not using the MsgBox() method correctly. Try this:

If strMsg <> "" Then
   MsgBox "The following fields require a response:" & vbCrLf & vbCrLf & _
       strMsg & vbCrLf & vbCrLf, vbOKOnly

   Me.cboLookup.SetFocus
   Cancel = True

End If


来源:https://stackoverflow.com/questions/25854654/vba-to-prevent-empty-fields-in-a-user-entry-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!