There are two types of excommunication:
1. ferendae sententiae — a brought judgment, imposed by a decision of Church authority in a particular case
2. latae sententiae — automatic excommunication (wide judgment) which does not require any decision in the particular case. Commit the offense, with knowledge of the law and its penalty, and the excommunication is incurred, according to Canon law.
However, three particular sins — apostasy, heresy, and schism — excommunicate automatically, by the very nature of the offense, regardless of law or judgment. If you commit any of these three sins, knowingly and deliberately, you cut yourself off from the Church.
If the Church lifts a ferendae excommunication, a latae excommunication might remain in effect, as when a schismatic or heretical group continues in those sins.
Everyone who dies in the state of grace will reach Heaven, perhaps after a short or long stay in Purgatory. Everyone who dies in a state of unrepented actual mortal sin is condemned to Hell forever. A person could be excommunicated and still die in the state of grace, due to a sincere but mistaken conscience.