We study a dynamic economy where credit is limited by insufficient collateral and, as a result, investment and output are too low. In this environment, changes in investor sentiment or market expectations can give rise to credit bubbles, that is, expansions in credit that are backed not by expectations of future profits (i.e. fundamental collateral), but instead by expectations of future credit (i.e. bubbly collateral). During a credit bubble, there is more credit available for entrepreneurs: this is the crowding-in effect. But entrepreneurs must also use some of this credit to cancel past credit: this is the crowding-out effect. There is an "optimal" bubble size that trades off these two effects and maximizes long-run output and consumption. The 'equilibrium' bubble size depends on investor sentiment, however, and it typically does not coincide with the 'optimal' bubble size. This provides a new rationale for macroprudential policy. A lender of last resort can replicate the 'optimal' bubble by taxing credit when the "equilibrium" bubble is too high, and subsidizing credit when the 'equilibrium' bubble is too low. This leaning-against-the-wind policy maximizes output and consumption. Moreover, the same conditions that make this policy desirable guarantee that a lender of last resort has the resources to implement it.