You have to paint the ceiling before the walls if you intend to paint the whole room. It is preferable to paint extensive areas like walls before heading to repaint the trim. This affords you the opportunity to work quickly while covering exposed areas that can result in occasional errant brushstrokes, roller splatters and over sprays.