spacey
maybe
this helps as to the basic structure and where to put the code?
regarding the code itself:
I always stole VBA code from Excel Macros:
Create a table and do with it what you described.
Once you're sure about the correct outcome, do it again in a new table while recording the actions into a macro.
The code of the macro can be viewed, afterwards.
You'd have to amend it to follow your form field names etc. But it could give you a rough guide.
Good Luck!