VBA UserForms are a key tool for managing user interactions. When UserForms are well designed, they guide users through the options and settings without any help file or guidance. However, from my own UserForm development, I know one of the most overlooked aspects is how to close VBA UserForms. Is it best to hide or unload the form? Does it matter either way?
This post covers key considerations to ensure the closure process achieves the desired outcome.
Download the example file: Click the link below to download the example file used for this post:
Basic VBA code
To start, let’s look at the basic VBA code for opening and closing UserForms. In this post, the UserForm is called myUserForm, which looks like this.
The UserForm has three elements:
- Text box: named txtTextBox
- Hide button: named cmdHide
- Unload button: named cmdUnload
Display a UserForm
The code to display a UserForm is usually stored outside of the UserForm in a standard module. The following code displays a UserForm.
Sub OpenUserForm()
'Show a userform
myUserForm.Show
End Sub
Hide a UserForm
To hide a UserForm using a button, the code may be contained within the UserForm itself, or in a separate module.
Code contained within the UserForm
The code below shows an example where the code is contained within the UserForm. Me. refers to the UserForm object.
Private Sub cmdHide_Click()
'Hide the UserForm using code within the UserFrom module
Me.Hide
End Sub
Code contained within a standard code module
Where the code is contained within another module, we must refer to the name of the UserForm, as shown by the code below.
Sub hideMyForm() myUserForm.Hide End Sub
When using the hide code outside of the UserForm, we need to call the code from the button.
Private Sub cmdHide_Click()
'Call the code contained within a standard module
Call hideMyForm
End Sub
Unload a UserForm
Another way to close a UserForm is to unload it. Like the examples above, the code can be referenced from within or outside the UserForm code module.
Code contained within the UserForm
The code is an example where the code is contained within the UserForm.
Private Sub cmdUnload_Click()
'Unload the UserForm using code within the UserForm module
Unload Me
End Sub
Code contained within a standard code module
The example below is where the code is contained within a standard code module
Sub unloadMyForm()
'Unload the UserForm using code within a standard module
Unload myUserForm
End Sub
When using the unhide code outside of the UserForm, we need to call the code from the UserForm.
Private Sub cmdUnload_Click()
'Call the code contained within a standard module
Call unloadMyForm
End Sub
Close button
The simplest option to close a UserForm is the standard [X] close button. It is convenient because it is always at the top of the window where the user expects it. By default, it doesn’t require any code to work as it’s part of the Windows framework.
The close button is equivalent to the unload method to close the VBA UserFrom.
Assigning the Esc key
The Esc key is commonly used within interface design to close a window. We can use this on our UserForm too, though the option to apply the setting is in a strange place.
Select a button on the UserForm and set the Cancel property to True.
When the UserForm is displayed, pressing the Esc key triggers the button with the Cancel property. Therefore, the Esc key can be assigned to a button with hide or unload.
As there is an option to hide or unload, which should we choose? Does it matter? YES, it definitely does matter.
The two options differ in their approach; they achieve slightly different things.
Unload
Unload closes the form completely; it no longer exists in memory. It will be as if the initialize event had never triggered, so if we refer to any of the objects on the UserForm, they will have no value.
Hide
Hide makes a UserForm invisible. It is still there; we just can’t see it. As it still exists, we can still reference objects on the form to retrieve their values.
For example, if there is text in a text box, we can obtain that value after the form has closed. The code below displays a message box with the text from the UserForm.
Sub displayTextFromClosedUserForm()
'Display the text contained within the UserFrom text box
'If UserFrom not loaded, it will display nothing
'If UserForm hidden, will display the value
MsgBox myUserForm.txtTextBox
End Sub
Note: As the form remains open, it continues to hold the memory.
Preloading the UserForm
What if we want to reference an object on a UserForm before we display it? The initialize event has not been executed, and the form does not exist in memory. To get around this issue, we use the load command to create the UserForm, but not display it.
Sub LoadUserForm()
'Load the UserForm without displaying
Load myUserForm
End Sub
By using this method, the initialize event triggers, but not the activate event. The activate event only triggers only when the UserForm is displayed.
To guarantee the UserForm is always in memory, load the form during the workbook open event.
How to close using the X button
By default, the [X] close button unloads the UserForm. Which is a problem if we want to hide it. But we can hijack the [X] button control to achieve the same as the hide command.
The UserForm has an event called QueryClose. Using this event, we can cancel the unload action, then hide the UserForm.
Enter the following code in the UserFrom code module
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
'Capture the [X] button click
If CloseMode = vbFormControlMenu Then
'Stop the default unload close
Cancel = True
'Force the Hide close
Me.Hide
End If
End Sub
Once we’ve canceled the unload action, we can now refer to the elements on the UserForm, just like the normal hide.
How did the user close the form?
As there are multiple ways to close a UserForm, it may be helpful to know which option the user selected. For example, did they click “OK” or “Cancel”?
In this situation, an easy option is to use a public variable. We can assign the value to the variable as part of the close procedure.
The public variable can then be accessed by any module.
Related Posts:
- Resize a UserForm with VBA or Windows API
- Hide or disable a VBA UserForm [X] close button
- Private vs Public Subs, Variables & Functions in VBA
About the author
Hey, I’m Mark, and I run Excel Off The Grid.
My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.
In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).
Do you need help adapting this post to your needs?
I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.
But, if you’re still struggling you should:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
- Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.
What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts:
When we make a UserForm, it takes data as input from users. But the data provided to the form does not close itself, so it can mislead the user to input data again. So, we use two different commands to close a userform when we give the input. They use the “Unload Me” method to close a UserForm, or we can use a UserForm.Hide method.
Table of contents
- Excel VBA Close Userform
- How to Close UserForm in Excel VBA?
- #1 – Close Userform Using “Unload Me” Statement in VBA
- #2 – Close UserForm Using Hide Method in Excel VBA
- Difference Between Unload & Hide in Excel VBA
- Recommended Articles
- How to Close UserForm in Excel VBA?
UserForms are vital while getting inputs from the user as part of the VBA project. We usually design the UserForm before we present it in front of the user. Once designing the VBA UserForm completes, we need to show up the same in front of the user and require VBA coding. Similarly, to close the UserForm requires VBA coding knowledge.
This article will show you how to close the UserForm in VBA coding.
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Close UserForm (wallstreetmojo.com)
How to Close UserForm in Excel VBA?
We must keep showing the UserForm in front of the user completing the purpose of the UserForm. So, we must close the UserForm. We can close the userform by using the “Unload Me” and “UserForm.Hide” statements. Even though both are slightly different, they will eventually serve our purpose.
You can download this VBA Close UserForm Excel Template here – VBA Close UserForm Excel Template
#1 – Close Userform Using “Unload Me” Statement in VBA
For example, look at the below image of the UserForm.
We have named the UserForm “MyUserForm.”
If we run the UserForm, we will see the UserForm like below.
We need to fill in the required details. Once we fill in the information, if we click on the “Submit” button, it will capture the same data to the worksheet, which is visible on the left side.
Clicking the “Submit” button captured the data we had entered in the UserForm.
If you notice, we have one more button called “Cancel.” What does this do?
Before we display the UserForm, we need to configure this button. So, we will go back to the basic visual editor to configure this button.
Now, we will double-click on the “Cancel” button. It will open up the automatic VBA subprocedureSUB in VBA is a procedure which contains all the code which automatically gives the statement of end sub and the middle portion is used for coding. Sub statement can be both public and private and the name of the subprocedure is mandatory in VBA.read more like the one below.
In this procedure, we need to write the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more about what should happen if we click the “Cancel” button. When we click on this “Cancel” button, it should close the UserForm we are working on now.
So, write the code as “Unload Me.”
Code:
Private Sub CancelButton_Click() Unload Me End Sub
“Unload Me” is the word we use to close the UserForm we are working on. Here the UserForm recognizes the word “Me” as the UserForm itself.
“Unload Me” can be used only on that UserForm procedure. We cannot call this statement in other modules. If called, it will show the error message as “Invalid use of Me Keyword.”
Let us run the code using the F5 key or manually now. First, we will see a blank UserForm.
Fill in the data and click on “Submit.”
Once we click the “Submit” button, it will store the values to the mentioned cells.
If the data entry is complete, we need to close the UserForm. Isn’t it?
So, click on the “Cancel” button to close the UserForm. It will close the UserForm.
#2 – Close UserForm Using Hide Method in Excel VBA
We can also close UserForm using the “Hide” method in VBA. Once again, we will double-click the “Cancel” button to see the private subprocedure.
Since we have already written the code to close the UserForm, we can see the existing code in VBA. So, now we will delete this.
We need to call the UserForm by its name to use the “Hide” method. In this case, our UserForm name is “MyUserForm.”
After mentioning the UserForm by its name, if we put a dot (.), we can see all the properties and methods of this UserForm. Now, we will select the “Hide” method.
Let us run the UserForm one more time. We will see a blank UserForm. Fill in the details first.
Now, without a click on the “Submit” button, we will click the “Cancel” button, which will hide the UserForm.
Difference Between Unload & Hide in Excel VBA
It would help if you had a question about the difference between “Unload” and “Hide,” where both serve a similar purpose. There is a difference between these two. Now first, we will use the “Unload Me” statement. Look at the below image.
We have entered the data in the user form but have not yet submitted it. Therefore, if we click on “Cancel,” it will unload the UserForm.
We will run the code through excel shortcut keyAn Excel shortcut is a technique of performing a manual task in a quicker way.read more F5 or manually. It will display a blank UserForm.
Even though we had entered the data correctly by mistake, we clicked on the “Cancel” button. When the new UserForm appeared, we filled the data from scratch.
Now, we will use the “Hide” method.
No, we will click on the “Cancel” button. It will hide the visible UserForm. But, when we re-run the macro, it will come back with the data we have already entered on the UserForm.
Like this, we can use the “Unload” statement and “Hide” method to close the UserForm in Excel VBA.
Recommended Articles
This article has been a guide to VBA Close UserForm. Here, we learn how to close UserForm using the “Unload Me” statement and “Userform.Hide” method in Excel VBA with simple to advanced examples. Below are some useful Excel articles related to VBA: –
- FileDialog in VBA
- VBA InStr
- Use of COUNTIF in VBA
- Call Sub in VBA
- Excel VBA Закрыть UserForm
Excel VBA Закрыть UserForm
Ранее мы обсуждали, как создать пользовательскую форму в VBA. Теперь для получения ввода от пользователя была кнопка для отправки, в которой затем сохранялось значение, указанное пользователем в листе Excel. Но что после придания значения, форма все еще там. Или что делать, если пользователь не хочет предоставлять какие-либо данные и закрывать форму пользователя. Мы не обсуждали, как мы закроем пользовательскую форму для пользователя. Аналогично кнопке отправки для отправки данных у нас была другая кнопка, которая была для отмены, которая используется для скрытия пользовательской формы. Кнопка отмены также имеет свой собственный код, чтобы скрыть пользовательскую форму от пользователя. Теперь есть два метода, с помощью которых мы можем скрыть пользовательскую форму. Они заключаются в следующем:
- Первый метод — когда мы используем метод Unload Me. Этот метод выгружает пользовательскую форму и исчезает с дисплея.
- Другой метод, когда мы используем метод Useform.Hide. Этот метод скрывает пользовательскую форму от дисплея.
Рекомендуется использовать второй метод, чтобы закрыть пользовательскую форму, так как первый метод полностью выгружает пользовательскую форму, и любые введенные пользователем данные будут полностью потеряны. Но когда мы используем второй метод сокрытия пользовательской формы, тогда последняя запись, сделанная пользователем в пользовательской форме, все еще присутствует.
Как закрыть UserForm в Excel VBA?
Мы узнаем о том, как закрыть UserForm в Excel VBA с его различием, и на нескольких примерах, но сначала давайте изучим способ закрытия пользовательской формы в VBA.
Есть два способа закрыть пользовательскую форму в VBA:
- Выгрузить меня
- Спрятать
Вы можете скачать этот шаблон VBA Закрыть UserForm Excel здесь — VBA Закрыть шаблон UserForm Excel
Excel VBA Закрыть UserForm — Пример # 1
Во-первых, давайте попробуем метод закрытия UserForm, используя опцию Unload Me. У нас была пользовательская форма в нашей предыдущей статье, которая выглядит как приведенная ниже.
Для кнопки отправки у нас был наш код, в котором были сохранены данные, введенные пользователем в Excel. Теперь дважды нажмите на кнопку отмены, которая откроет код для того же, как показано ниже,
Код:
Частный Sub CommandButton2_Click () End Sub
Кнопка «Отмена» была второй командной кнопкой, которую мы предоставили пользовательской форме. Теперь напишите оператор кода как Unload me в разделе, как показано на рисунке ниже.
Код:
Приватный саб CommandButton2_Click () Unload Me End Sub
Мы можем видеть, что Me является оператором Object of Unload. Теперь давайте запустим пользовательскую форму, нажав клавишу F5, чтобы отобразить ее.
Нажмите кнопку «Отмена», чтобы увидеть, что пользовательская форма исчезает, и она возвращает нас к исходной пользовательской форме окна проекта.
Excel VBA Закрыть UserForm — Пример № 2
Теперь давайте попробуем второй метод, метод userform.hide, аналогичный описанному выше, во-первых, давайте откроем форму пользователя из формы пользователя в окне проекта.
Теперь дважды нажмите кнопку отмены, которая откроет код просмотра для кнопки отмены.
У нас уже есть оператор Unload Me, присутствующий в кнопке отмены, очистите код и замените его на оператор Userform.Hide .
Код:
Приватный Sub CommandButton2_Click () UserForm1.Hide End Sub
Теперь давайте снова запустим пользовательскую форму, нажав клавишу F5, и отобразим ее на экране.
Когда мы нажимаем кнопку отмены, мы снова перемещаемся в окно проекта пользовательской формы. Теперь всем нам может быть интересно, в чем разница между этими двумя методами, поскольку оба метода полностью закрывают для нас пользовательскую форму, тогда почему второй метод является наиболее рекомендуемым методом для обоих. Мы точно выясним, почему в следующих двух примерах.
Excel VBA Закрыть UserForm — Пример № 3
Теперь давайте перейдем к первому методу Unload Me оператора для кнопки отмены и предоставим некоторые данные для пользовательской формы. Дважды щелкните на кнопке отмены в пользовательской форме, чтобы открыть код представления для командной кнопки и заменить код оператором Unload Me, как показано ниже.
Код:
Приватный саб CommandButton2_Click () Unload Me End Sub
Теперь снова запустите пользовательскую форму, нажав клавишу F5, и отобразите ее на экране.
Давайте предоставим некоторые данные для пользовательской формы следующим образом, теперь не нажимайте кнопку отправки, нажмите кнопку «Отмена».
Снова запустите пользовательскую форму, нажав клавишу F5.
Теперь мы можем видеть, что мы потеряли данные, которые мы предоставили пользовательской форме, так как мы не предоставили ее, она не была сохранена на рабочем листе, и мы закрыли пользовательскую форму с помощью оператора Unload Me, который удалил уже заполненные данные.
Excel VBA Закрыть UserForm — Пример № 4
Теперь давайте сделаем то же самое упражнение, но с помощью оператора Userform.Hide,
В командной кнопке отмены замените код, используя метод userform.hide, как показано ниже.
Код:
Приватный Sub CommandButton2_Click () UserForm1.Hide End Sub
Теперь мы снова запустим пользовательскую форму, нажав клавишу F5, и предоставим ей некоторые данные следующим образом.
Теперь давайте нажмем кнопку отмены и снова запустим пользовательскую форму, которая даст нам следующий результат.
Данные даже не теряются, когда мы нажимаем кнопку «Отмена», если мы нажимаем «Отправить», данные сохраняются в Excel следующим образом.
Теперь данные сохранены, пользовательская форма теперь пуста, и мы можем закрыть пользовательскую форму, используя кнопку отмены,
То, что нужно запомнить
- После того, как пользователь введет данные, нам нужно закрыть пользовательскую форму, чтобы она была так же важна, как кнопка отправки.
- Закрыть пользовательская форма находится в командной кнопке пользовательской формы в VBA. Как правило, она называется Отмена или Закрыть.
- Есть два отдельных метода закрытия пользовательской формы, но они в конечном итоге служат той же цели, что и друг друга.
- Метод Userform.Hide наиболее рекомендуется, поскольку даже если пользовательская форма закрыта пользователем перед вводом данных, данные не теряются, и введенная пользователем запись снова отображается, когда пользователь открывает пользовательскую форму.
Рекомендуемые статьи
Это руководство по VBA Close UserForm. Здесь мы обсудим, как закрыть UserForm в Excel, используя оператор Unload Me и метод Userform.Hide в VBA, а также некоторые практические примеры и загружаемый шаблон Excel. Вы также можете просмотреть наши другие предлагаемые статьи —
- Как активировать лист в VBA?
- Оценить формулу в Excel
- Полное руководство по списку VBA
- HYPERLINK Формула в Excel
Уважаемые форумчане! Напомните, плиззз, команды в VBA для сохранения и закрытия userform. Спасибо! |
|
А что значит сохранить? У формы нет такой функции А закрыть можно так Sub Макрос1() метод Hide — просто скрывает формулу от пользователя |
|
{quote}{login=Pavel55}{date=28.04.2008 06:41}{thema=}{post}А что значит сохранить? У формы нет такой функции А закрыть можно так Sub Макрос1() метод Hide — просто скрывает формулу от пользователя Всем спасибо уже сделал так |
|
)) ну, всё правильно) только вы спрашивали о сохранении формы, а сами сохраняете активную книгу ) или нам надо было догадаться ?) |
|
СердЖиГ Гость |
#5 29.04.2008 11:34:08 {quote}{login=Pavel55}{date=28.04.2008 10:07}{thema=}{post})) ну, всё правильно) только вы спрашивали о сохранении формы, а сами сохраняете активную книгу ) или нам надо было догадаться ?){/post}{/quote} Павел, сорри, уже вечер был |
Excel VBA Close UserForm
Earlier we had discussed how to create a UserForm in VBA. Now to get input from the user there was a button for submit, which stored then the value given by the user in an excel sheet. But what after giving the value the form is still there. Or what if the user does not want to give any data and close the userform. We had not discussed how we will close the userform for the user. Similar to submit button to submit the data we had another button which was for cancel which is used to hide the userform. The cancel button also has its own code to hide the userform from the user. Now there are two methods by which we can hide a userform. They are as follows:
- The first method is when we use the Unload Me method. This method unloads the UserForm and it disappears from the display.
- Another method is when we use Useform.Hide method. This method hides the UserForm from the display.
It is recommended to use the second method to close the UserForm as the first method will completely unload the UserForm and any data entered by the user will be completely lost. But when we use the second method of hiding the UserForm, then the last entry done on the userform by the user is still present.
How to Close UserForm in Excel VBA?
We will learn about how to close UserForm in Excel VBA with its difference and by a few examples but first, let us learn the method of closing a userform in VBA.
There are two methods to close userform in VBA:
- Unload Me
- Hide
You can download this VBA Close UserForm Excel Template here – VBA Close UserForm Excel Template
Excel VBA Close UserForm – Example #1
First, let us try the method of closing a UserForm using the Unload Me option. We had a userform in our previous article which looks like the one below.
For the submit button we had our code, which stored the data entered by the user in excel. Now double click on the cancel button which will open the code for the same as follows,
Code:
Private Sub CommandButton2_Click() End Sub
Cancel Button was the second command button we provided to the userform. Now write the code statement as Unload me in the section as shown in the image below.
Code:
Private Sub CommandButton2_Click() Unload Me End Sub
We can see that Me is an Object of Unload statement. Now let us run the userform by pressing the F5 key to display it.
Press Cancel button to see that the userform disappears and it takes us back to the original userform of the project window.
Excel VBA Close UserForm – Example #2
Now let us try the second method which userform.hide method in a similar fashion as above, first, let us open the userform from the userform in the project window.
Now double click the cancel button which will open the view code for the cancel command button.
We already have Unload Me statement present in the cancel command button, clear the code and replace it with the Userform.Hide statement.
Code:
Private Sub CommandButton2_Click() UserForm1.Hide End Sub
Now let us again run the userform by pressing F5 key and display it on the screen.
When we press the cancel button we are again moved to the project window of the userform. Now we all might be wondering that what is the difference between the two methods, as both the methods close the userform for us perfectly then why is the second method most recommended method of both. We will find out exactly why in the next two examples.
Excel VBA Close UserForm – Example #3
Now let us move to the first method Unload Me statement for the cancel button and provide some data to the userform. Double click on the cancel button from the userform to open the view code for the command button and replace the code with the Unload Me statement as follows.
Code:
Private Sub CommandButton2_Click() Unload Me End Sub
Now run the userform again by pressing the F5 key and make it display on the screen.
Let us provide some data to the userform as follows, now don’t press the submit button, press the Cancel button.
Again run the userform by pressing F5 key.
Now we can see that we have lost the data we have provided to the userform since we did not submit it, it was not stored in the worksheet and we closed the userform using the Unload Me statement which removed the data which was already filled.
Excel VBA Close UserForm – Example #4
Now let us do the same exercise but by using Userform.Hide statement,
In the cancel command button replace the code for it using the userform.hide method as shown below.
Code:
Private Sub CommandButton2_Click() UserForm1.Hide End Sub
Now we will again run the userform by pressing the F5 key and provide it with some data as follows.
Now let us press the cancel button, and again run the userform which will give us the following result.
The data is not even lost when we pressed the cancel button if we press submit it will store the data in excel as follows.
Now the data is stored the userform is empty now and we can close the userform using the cancel button,
Things to Remember
- Once the data entry has been done by the user we need to close the userform so it is as important as the submit button.
- Close Userform is in the command button of the userform in VBA, In general, it is named as Cancel or Close.
- There are two separate methods of closing a userform but they eventually serve the same purpose as each other.
- The Userform.Hide method is most recommended as even if the userform is closed by the user before the data entry, the data is not lost and the entry made by the user is again displayed when a user opens the userform.
Recommended Articles
This is a guide to VBA Close UserForm. Here we discuss how to close UserForm in Excel using Unload Me statement and Userform. Hide method in VBA along with some practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Activate Sheet
- VBA IsError
- VBA List Box
- VBA With