30-years old kid responding

Have you tried to remove the rows in reverse order? I can imagine when you start removing the rows from the top, the rows further down on are shifted upwards, thus not matching the initial rowcount you queried using selectedRanges().

I suggest reversing both the list iteration (variable i) as well as the row removal code (variable j)