Reputation: 1686
I have a listbox that contains 18 items. The selected item can be deleted from the listbox by clicking a 'Delete' button. How can I prevent a user from deleting certain items that I specify?
Private Sub cmdDelete_Click()
Dim i As Integer
With Me.listbox1
For i = .ListCount - 1 To 0 Step -1
If .Selected(i) = True Then
.RemoveItem i
End If
Next i
End With
End Sub
Upvotes: 0
Views: 853
Reputation: 3680
You could store the values in a table? Then you could have a column in the table which specified whether the field could be deleted or not, which would be easy to build into your VBA.
Edit for further explanation:
Have you listbox be unbound (i.e. no specific field as its datasource).
Create a table which contains columns for an ID (as an autonumber), the values you want to appear in your listbox (as a textbox), and a final column you can tick yes or no on (as a boolean or yes/no field). E.g.
ID Values Allow deletion?
1 Example Yes
2 Another example No
3 Yes another example Yes
In your listbox's rowsource, select that table.
Your delete sub could now run the following code.
dim qry as string
dim strLookup as string
strLookup = dlookup("[Allow deletion]","[Your Table]", YOURSELECTEDFIELDHERE & "=[Values]")
if strLookup = "No" Then
msgbox "You're not allowed to delete this field."
exit sub
else
qry = "DELETE * FROM [Your Table] WHERE [Values] = YOURSELECTEDFIELDHERE"
CurrentDB.Execute qry
Me.YourListBoxName.Requery
end if
This will look for the value you've grabbed from your listbox, match it against the Allow deletions field, delete it if that field is marked as Yes or leave it be if it's marked as No.
If you want to only temporarily delete the field and have it appear next time you load the form - in effect, hide it, you'd have to add a further column to the table called "Show", which would also be a Yes/No field, and set the default to Yes.
You'd then set your rowsource to SELECT * FROM [YOURTABLE] WHERE [Show] = "Yes"
.
Then qry
in the above code should instead be set to:
UPDATE [YOURTABLE] SET [YOURTABLE].[Show] = "No" WHERE ((([YOURTABLE].[Values])=YOURSELECTEDFIELD));
This will then change the value of Show to No, so when the listbox is requeried, it'll no longer appear.
You'll need to run another query to change all of them back to Yes on the form exit.
Upvotes: 2