Link to home
Start Free TrialLog in
Avatar of Patrick O'Dea
Patrick O'DeaFlag for Ireland

asked on

Conditional lock of one field in datasheet

See attached database with a single datasheet form and single table.

I want the "Age" field to be disabled IF the Adult_or_Child="Adult"

The code below does not work properly

Private Sub Form_Current()
If Me.Adult_or_Child = "Adult" Then Me.Age.Enabled = False
End Sub
Database14.accdb
Avatar of DatabaseMX (Joe Anderson - Former Microsoft Access MVP)
DatabaseMX (Joe Anderson - Former Microsoft Access MVP)
Flag of United States of America image

Here you go
Database14_MX01.zip
You can use Conditional Formatting on the Age text box. No code is needed.
No points since I'm sure Joe fixed your problem.  I am just saying in words what he probably did so others do not have to open the database to see the answer AND you understand the process for future reference.

 When you modify a setting, you have to handle both the true and the false conditions.  Otherwise, once the condition is modified, it will not revert to its default setting until the form is closed and reopened.

Private Sub Form_Current()
If Me.Adult_or_Child = "Adult" Then
    Me.Age.Enabled = False
Else
    Me.Age.Enabled = True
End If
End Sub
It's much better to use Conditional Formatting for this than code.
CF works on all rows simultaneously.  Code only works on the row you are in.
ASKER CERTIFIED SOLUTION
Avatar of DatabaseMX (Joe Anderson - Former Microsoft Access MVP)
DatabaseMX (Joe Anderson - Former Microsoft Access MVP)
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I agree that conditional formatting works best in most cases but you can't always use it and in this particular case, code would work fine since enabled is only relevant when for the control where the insertion point is.  It doesn't matter at all whether other controls are enabled or not since focus can only be in one control at a time.  So the point is that the code needs to toggle the enabled setting, it can't just set the property to false and expect it to magically change back to true for the next record.

I was trying to explain in words what was wrong with Patrick's initial effort so he would be able to employ the technique correctly in the future.  It was a teaching moment and I took it.
Avatar of Patrick O'Dea

ASKER

Thanks gents, magnificent as always.

I had never spotted the "Enable" / "Disable" button on conditional formats.
Ladies and Gents :-)
You are welcome
I'm the lady and you are welcome:)