If you have never replaced the button (memory) battery, I'd try that first. That's cheap and easy to replace, might solve the problem.
Also be certain that the main battery(ies) and/or charger are good. BP511As do go bad after a certain number of discharge/recharge cycles. And sometimes chargers can fail.
Also, if not used for quite while, the main batteries can be slow to charge up at first, but might take a full charge and work fine after a half dozen discharge/recharge cycles. I've had this happen a couple times. Old battery that had been sitting for a long, long time appeared to be fully charged (according to the charger) and camera would come on, but might not take even a single pic before dying again. Battery back in the charger, next time the camera stays on a little longer, but still dies rather quickly. Repeated it several more times and saw gradual improvement, until the battery finally took a good, full charge and the camera worked normally. After that, regular recharges kept the camera working normally.
If you rule out any of the batteries as a source of the problem, contact Canon or a local repair tech for a repair quote. But it might be more than the camera is worth, could cost more than a replacement. If you decide it's not worth fixing, your 40D might still have some value to someone as a parts camera or as a trade-in through the Canon Loyalty Program (do a search on that, if interested).