For loops in Stata are a fantastic feature to save code lines while doing repetitive tasks. They can also be immensely useful for complicated tables or advanced cleaning/variable prep.
But if you make some kind of coding mistake in the loop, it can be difficult to troubleshoot: Stata throws an error but doesn't say which line in the loop gave that error. There's an incredibly simple (but for some reason not well-known) command that fixes this. Just type the following in the command window:
set trace on
That's it! After entering this command Stata will show all explicit steps in the loops, and you'll be able to see which line threw an error. It will even fill in the values of the current run of the loop, so even if the error only happens on some runs of the loop you'll know exactly which one it is.
Once you're done troubleshooting be sure to turn it off again: all the extra lines that are displayed in the display window slow Stata down quite a bit. It's also easy:
set trace off