Please according to the following settings:
1. First turn on the MacBook, find the "System Preferences Button" in the dock bar of the Apple computer desktop and click to open it.
2. Then, select the Energy Saver option in the System Preferences window and click Open.
3. Finally, under the "Power Adapter" tab, check the "When the display is off, prevent the computer from automatically going to sleep" option, the MacBook can continue to work with the external keyboard and display after closing the lid, and the problem has been solved.
If your Mac system is Ventura 13.3, please follow the steps to set.
How to continue external display after laptop lid is closed