Question : Access form - Using Sum function to validate records

I have a subform containing records with a check-box field. I want to ensure that one and only one record  is checked so I've added a SUM(chk_preferred) total in the form header.
When I check a record, the total did not update reliably so I added a me.refresh command in the onclick event.. this now updated the total as required.
However, I now want to validate the total in the before_update event but it seems Access is validating the total's value before it's refreshed.
Can someone please guide me in getting this to work reliably?
Thanks.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
Private Sub chk_preferred_Click()
    Me.Refresh
End Sub

Private Sub Form_BeforeUpdate(Cancel As Integer)
    If txt_sum_preferred = 0 Then
        MsgBox "You must select one supplier price as preferred", vbInformation, "Wait"
        Cancel = True
    ElseIf txt_sum_preferred < -1 Then
        MsgBox "You can only select one supplier price as preferred", vbInformation, "Wait"
        Cancel = True
    End If
End Sub

Answer : Access form - Using Sum function to validate records

» The calculated total is actually on a sub form and I want to test this total value in the before_update event of the parent form.

When you leave the subform, the records displayed therein are saved. Likewise, a parent form is saved before you enter a subform. In other words, preventing the save of the main form when the subform is wrong is just annoying, and doesn't provide any data integrity (the user can cancel the message and the subform will remain wrong).

The easiest solution is to allow not selecting a preferred supplier. In that case, take the cheapest, or a random supplier. For the code, when a supplier is selected as preferred, run an after update event to remove the flag from any other supplier in the list (see below).

It's also easy to prevent the user from un-checking the Preferred flag, i.e. use the “before update” event of the check box and prevent setting it to false if the “old value” is true. You can add a message: “you cannot un-select a preferred supplier, you can however select another”.

Trying to implement the business rule from the start is a pain. You best bet is probably to use the “before update” event of the sub form and simply set the Preferred flag if it's the only record. The first is the preferred supplier, until another is selected. A bit crude, but if you really need it, it makes sense that way.

Does that help?
(°v°)
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
Private Sub Form_AfterUpdate()
    If Not Preferred Then Exit Sub
    With Me.RecordsetClone
        .MoveFirst
        Do Until .EOF
            If !ID <> Me.ID And Preferred Then
                .Edit
                .Preferred = False
                .Update
            End If
            .MoveNext
        Loop
    End With
End Sub
Random Solutions  
 
programming4us programming4us