Roland, is it certain the order of upgrading is random? I have observed that there is a pattern but I can't identify the pattern exactly. It appears to be in the order in which the units were created (newest units first).If you have enough money, then that will be all of them, but if you don't, then some of the units will be selected at random and they will get the upgrade until you run out of money.
It may even be in the same order that units are displayed or listed when a stack of units is selected or when you hover the cursor over a stack. For example, all grenadiers at the same experience level are grouped together in order of their age.
When doing mass upgrades in situations where it will take two or more turns at reduced research to earn enough gold to complete the upgrades, I select what I believe to be the oldest unit of that type that will be upgraded. (using Ruff's Mod Pack or something similar that adds numbers to unit names makes this easier; 1st Infantry of Madrid, for example). As that unit becomes active each turn, I use the Alt key when selecting Upgrade and then select Skip if the unit is still un-upgraded. I repeat until the unit finally gets upgraded. If he was indeed the oldest of the units, he is also the last to be upgraded and I know it is time to notch the research slider back up to complete the process. (hmm, maybe this should be in the hints and tips topic instead).
Thanks Roland, as always, for another complete and thoughtful answer to questions here in this topic.