简体   繁体   中英

Check if a field does not have focus in Access 2013

I have two comboboxes that need to be filled in before the rest of the form. I'd like to show an error message if the user moves to a third box while one of the first two boxes is still empty.

I tried using the following in Form_Current but it shows the error if I move from Combo1 to Combo2. It should only show if I move to an object that is not one of the two.

If Me.ActiveControl<>Combo1 And Me.ActiveControl<>Combo2 And (IsNull(Combo1.Value) Or IsNull(Combo2.Value) Then
    ' Error
    Else
    ' No Error
End If

EDIT: Here is my working code.

Dim frm As Form
Dim ctl As Control

'loop through all controls in form
For Each ctl In frm.Controls
    'only combo boxes
    If ctl.ControlType = acComboBox Then
        'ensure both boxes are filled in
        If Not IsNull(Combo1.Value) And _
        Not IsNull(Combo2.Value) Then
            'enable controls on form
            ctl.Enabled = True
        Else
            'disable controls on form
            ctl.Enabled = False
        End If
    End If
Next

您可以为将所有其他字段的Enabled属性设置为No的窗体做一个On Current宏,除非前两个字段具有有效的条目。

Try this:

If Me.ActiveControl.Name <> Me!Combo1.Name And _
    Me.ActiveControl.Name <> Me!Combo2.Name Then

    If IsNull(Me!Combo1.Value + Me!Combo2.Value) Then
        ' Error
    Else
        ' No Error
    End If

End If

Form_Current as well as most events will only fire if a record from the current recordset is concerned in some way. So if you comboboxes are not bound to a record then there is no way to detect changes with the record events in the form. Therefore I would suggest using events bound to the comboxes themselves. Either use the Combo_LostFocus() for both comboboxes or if you just have 1 other element use the Combo_GotFocus() or _MouseDown for that one.

A sample solution might look like this: Option Compare Database

Private Function IsValid() As Boolean
  IsValid = False
  If Not IsNull(Me.Combo0.Value + Me.Combo1.Value) Then IsValid = True
End Function

Private Sub Combo0_LostFocus()
  Me.Combo2.Locked = Not IsValid()
End Sub

Private Sub Combo1_LostFocus()
  Me.Combo2.Locked = Not IsValid()
End Sub

Private Sub Combo2_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
  If Not IsValid() Then
    MsgBox "you need to fill in the others first!"
    Me.Combo2.Value = ""
  End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM