Your title asks when should code be broken down into modules, but the code you showed needed breaking down into separate procedures, as suggested by the others.

In my view, modules should be functionally oriented. I tend to have one for my version history, one for general globals, one for application specific globals, one for enums, one for types, one for messages, one for entry points, helper modules for supporting each entry point, and a bunch of utility modules (such as one that has a number of generic range functions, one for generic table functions, etc.). Plus classes and forms of course.

I personally do not worry about having too many modules, I would rather have 100 modules where one may only have one function in it rather than mix up functionality.

I also tend to go for lots of procedures in code modules. I remember Simon Murphy once saying at a conference that he believes no module should have more code than can be seen on a screen without scrolling. I buy into the principle of that, but I find it somewhat hard to stick to it when you add in error handling and/or debug trace code.

I tend to write my functionality all in one procedure to start with, get it working as best I can, and then I go through it and see which parts are doing some discrete action, and drop that into a separate private procedure. I find this is useful in that I concentrate on outcome to start with, but then by breaking it down I review it in a refactoring frame of mind.

I would also add a lot more spacing than your code example.

Works for me.