I'm going to translate the sentences the way the sentence is structured in Korean, so it might not make sense in English at first, but it should help get the point across.
필통에 볼펜이 없어요 = In the pencil case, the ballpoint does not exist
The subject is something that is located in the pencil case (필통에). One might also write 필통에(는) 볼펜이 없어요. So the location of the 에 is in the front as most subjects do.
책은 책상 위에 있어요 = The book is on top of the desk.
The subject is the book (책), noted by the 은 marker. In this case, -에 is simply describing something that is located on the desk (책상 위에), so it's placed next to 책상.
The easiest rule of thumb is that if you're describing a place, put the noun with the 에 in front as the subject. In other cases, 에 would become a location marker.
In both of your examples above, switching around the 에 wouldn't make sense, but consider this example:
근처에 고양이 있다 => Nearby, the cat exists
고양이는 근처에 있다 => The cat exists nearby
Both sentences can be translated to "There's a cat nearby" in English, but from the way each sentence is made, you can perhaps see the different emphasis. Hope this helps.