The gemara cites a machlokes beis shamai and beis hillel about activities that are violations of ממצוא חפצך such as making shidduchim and teaching a profession and therefore may not be able to be done on shabbos. R. Moshe (Hea'ros in Dibros) explains that really everyone holds that חפציך are forbidden, but חפצי שמים - mitzvah type activities are permitted. However, these activities are types of things that one would do even if there was no mitzvah element to them at all. Everyone wants to marry off their children and give them an education despite the mitzvah element. It is different than other mitzvah type of activities that one is really doing for the mitzvah, just that they sometimes need a שלא לשמה motivation to do the mitzvah. Therefore, Beis Shamai holds that these activities are considered חפצך which is assur, and Beis Hillel considers them חפצי שמים and are permitted. Based on this approach, both visiting the sick and comforting mourners qualify as חפצי שמים and should be permitted. That is why Rashi needs to create another rationale to forbid those activities, due to the fact that they cause pain to the visitor on shabbos.
Why doesn't Beis Shamai agree that one can visit the sick and comfort those mourning on shabbos, and just tell them to overcome the pain that they will feel? Just as we find in the gemara in brachos and succah that one who's ship is sinking is not considered a טרדא to exempt them from Shema because it is a טרדא דרשות so they are obligated to work on overcoming it. Here too, we should consider the feeling of pain with the mourner or sick to be a tza'ar of reshus and tell him to get over it? Rashi seems to understand that the nature of the mitzvah to visit the sick and comfort the mourning is to be מצטער אם המצטערים, to join in the pain and suffering of those who are suffering. Human nature is to get solace and be comforted by seeing others sharing in their pain. Mitzvos where the very nature and obligation of the mitzvah is to be משתתף in the tza'ar, would certainly qualify as a mitzvah. Therefore, Beis Shamai could not say get over it since the would undermine the very nature of these mitzvos. Beis Hillel who holds that one can do these things on shabbos is because we consider them to be important acts of chessed so that יצא הפסדו בשכרו, the loss of minor violations of shabbos will be compensated by the gain of the chessed that is done. That is the implication of the gemara 12b בקושי התירו לנחם אבלים ולבקר חולים בשבת. Based on this we learn that one who visits the sick or comforts the mourning and doesn't show that they are mitz'taer with the one suffering, hasn't really fulfilled the mitzvah.