Grid-based entity collision issues

Hi all
I’m attempting to implement collisions between multiple entities in a 2D top-down game and I’ve decided to use a grid for this purpose. The grid itself works correctly. The collision detection, well, it sort of works, and it’s something I’ve been scratching my head over. Here’s the code (I’m aware it’s probably quite a mess):

What I’m not really understanding is that I’ll end up with results like this:

Yeah. They sorta… go into each other.
My understanding of detecting collisions is that all i’d have to do is find suitable entities, figure out the distances from their edges and if it is zero or less than their respective velocities then I’d either stop them from moving, OR slow them down in order to touch in the next tick. Is there a better way to do this? Or is there a better way to handle collisions in this manner?