You're using a scanner to input into a form? Then you would use code like that in the form BeforeUpdate event (or perhaps BeforeUpdate event for the textbox receiving your scanner input). However, I think I would add Cancel = True after the message box IF using the form BeforeUpdate event.
You substituted your own query name for that code, yes?
I think I'd just use DLookup in the same event to see if the scanned value is already in the table. Not sure I see a need to create a query and a function to run it and do a domain aggregate function call on its results every time something is scanned.
The more we hear silence, the more we begin to think about our value in this universe.
Paraphrase of Professor Brian Cox.