top of page
  • John

Working with a UserForm's close button (the 'X' button)

Updated: Jul 29, 2022

The close (or 'X') button appears at the right in the title bar of every UserForm. You can control the behaviour when it is clicked, or you can hide it. Why would you want to do that? Normally, you wouldn't. And shouldn't. Normally the user should be able to close a UserForm whenever they want and your code should handle that outcome. However, just occasionally, it might be essential to ensure that a user has acknowledge some text or made a selection ... an example might be showing the user a licence where you need them to accept or decline the terms.

To control the behaviour of the 'X' button, in the UserForm's code, you need to handle the QueryClose event and test whether the CloseMode property is equal to vbFormControlMenu then carry out the action you want. Note that pressing Alt+F4 or right-clicking the title bar and then selecting 'Close' has the same effect as directly clicking the 'X'. Note these two examples will work with 2007 and earlier versions of Excel, Word, PowerPoint and Outlook.

To make the 'X' do nothing, in the UserForm's code area below the declarations, add



Or to show a dialog (or carry out any action of your choice) when the 'X' is clicked, instead add



​The following code will actually hide the 'X' ... but note that this doesn't prevent the user from pressing Alt+F4 to close a UserForm and so you will still want to consider using one of the above code snippets to handle Alt+F4. Note that as this uses calls to the Windows API that require VBA7, then this will only work with Excel, Word, PowerPoint and Outlook version 2010 onwards.

1. In the UserForm's code in the declarations area, add the Windows API calls and associated constants



2. And in the UserForm's code in the procedures area, add the SetNoX procedure


3. And from the UserForm_Initialize event, call the SetNoX procedure​


4. That's it. The only thing left to do is to display the UserForm (in this example called UserForm1) eg



​This is a UserForm with the 'X' button showing, before the above code was added


UserForm with 'X' showing













And this the same UserForm with the 'X' button removed using the above code


UserForm without 'X' showing


0 comments

Comments


bottom of page