Close excel userform vba excel

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

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.

VBA Close UserForm

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.

VBA Close UserForm Example 1

We have named the UserForm “MyUserForm.”

If we run the UserForm, we will see the UserForm like below.

VBA Close UserForm Example 1-1

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.

VBA Close UserForm Example 1-6

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.

VBA Close UserForm Example 1-7

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.

VBA Close UserForm Example 1-2

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.”

VBA Close UserForm Example 1-3

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.

VBA Close UserForm Example 1-8

Fill in the data and click on “Submit.”

VBA Close UserForm Example 1-4

Once we click the “Submit” button, it will store the values to the mentioned cells.

VBA Close UserForm Example 1-5

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.

VBA Close UserForm Example 1-3

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.”

VBA CUF Example 1-9

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.

VBA CUF Example 2-2

Let us run the UserForm one more time. We will see a blank UserForm. Fill in the details first.

VBA CUF Example 2-3

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.

VBA CUF Example 3

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.

VBA CUF Example 3-1

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.

VBA CUF Example 3-2

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

Return to VBA Code Examples

In this tutorial, you will learn how to initialize, open, and close a Userform using VBA.

For this example, we created a simple Userform called basicUserform shown below with a label, a textbox, and three command buttons.

Basic UserForm in VBA

Open a Userform using VBA

Use the Show Command to open the Userform called basicUserform:

basicUserform.Show

Close a Userform using VBA

You can close a form using the Unload Command:

Unload basicUserform

This will close the UserForm from within running code.

Instead, you can also use the Me keyword to close a form within the form’s code module:

Unload Me

Note: You can only use Unload Me in procedures contained in the Userform Code Module:

Notice in the example above we added “Unload.Me” to the “Click” event of the Cancel button. So when the user clicks the Cancel button, the form will unload.

You can access the UserForm Code Module by double-clicking on the module in the Code Explorer (on the left). Or by right-clicking in the UserForm visual editor.

Initialize a Userform in VBA

When a form is loaded, the “Initialize” event is triggered. You can use this event to change the UserForm appearance such as populating combo boxes or turning controls on/off in your initialization code.

This code will disable the Cancel button when the UserForm is launched:

Private Sub UserForm_Initialize()

cmdCancel.Enabled = False

End Sub

Using the Initialize Event in VBA

Note: This code must be placed in the UserForm code module (see picture above).

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

VBA Close UserForm

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:

  1. The first method is when we use the Unload Me method. This method unloads the UserForm and it disappears from the display.
  2. 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:

  1. Unload Me
  2. 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.

VBA Close UserForm Example 1-1

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

VBA Close UserForm Example 1-2

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

VBA Close UserForm Example 1-3

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.

VBA Close UserForm Example 1-4

Press Cancel button to see that the userform disappears and it takes us back to the original userform of the project window.

Press Cancel button

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.

VBA Close UserForm Example 2-1

Now double click the cancel button which will open the view code for the cancel command button.

VBA Close UserForm Example 2-2

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

UserForm1.Hide

Now let us again run the userform by pressing F5 key and display it on the screen.

VBA Close UserForm Example 2-4

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

Unload Me Statement

Now run the userform again by pressing the F5 key and make it display on the screen.

VBA Close UserForm Example 3-2

Let us provide some data to the userform as follows, now don’t press the submit button, press the Cancel button.

VBA Close UserForm Example 3-3

Again run the userform by pressing F5 key.

VBA Close UserForm Example 3-4

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

Userform.Hide Method

Now we will again run the userform by pressing the F5 key and provide it with some data as follows.

VBA Close UserForm Example 4-2

Now let us press the cancel button, and again run the userform which will give us the following result.

VBA Close UserForm Example 4-3

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.

Submit Button Example 4-4

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 –

  1. VBA Activate Sheet
  2. VBA IsError
  3. VBA List Box
  4. VBA With

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.

Close VBA UserForm example objects

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.

Close VBA UserForm X button

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.

Esc key to close VBA UserForm

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.

Close VBA UserForm X button

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

Headshot Round

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:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. 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.
  4. 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:

  • Excel VBA Закрыть UserForm

Excel VBA Закрыть UserForm

Ранее мы обсуждали, как создать пользовательскую форму в VBA. Теперь для получения ввода от пользователя была кнопка для отправки, в которой затем сохранялось значение, указанное пользователем в листе Excel. Но что после придания значения, форма все еще там. Или что делать, если пользователь не хочет предоставлять какие-либо данные и закрывать форму пользователя. Мы не обсуждали, как мы закроем пользовательскую форму для пользователя. Аналогично кнопке отправки для отправки данных у нас была другая кнопка, которая была для отмены, которая используется для скрытия пользовательской формы. Кнопка отмены также имеет свой собственный код, чтобы скрыть пользовательскую форму от пользователя. Теперь есть два метода, с помощью которых мы можем скрыть пользовательскую форму. Они заключаются в следующем:

  1. Первый метод — когда мы используем метод Unload Me. Этот метод выгружает пользовательскую форму и исчезает с дисплея.
  2. Другой метод, когда мы используем метод Useform.Hide. Этот метод скрывает пользовательскую форму от дисплея.

Рекомендуется использовать второй метод, чтобы закрыть пользовательскую форму, так как первый метод полностью выгружает пользовательскую форму, и любые введенные пользователем данные будут полностью потеряны. Но когда мы используем второй метод сокрытия пользовательской формы, тогда последняя запись, сделанная пользователем в пользовательской форме, все еще присутствует.

Как закрыть UserForm в Excel VBA?

Мы узнаем о том, как закрыть UserForm в Excel VBA с его различием, и на нескольких примерах, но сначала давайте изучим способ закрытия пользовательской формы в VBA.

Есть два способа закрыть пользовательскую форму в VBA:

  1. Выгрузить меня
  2. Спрятать

Вы можете скачать этот шаблон 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. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Как активировать лист в VBA?
  2. Оценить формулу в Excel
  3. Полное руководство по списку VBA
  4. HYPERLINK Формула в Excel

There are two ways to achieve that. Both will only close your form and keep Excel opened.

I’ve asked a question about it a while ago maybe this can help you.


1. Hide Method

Your userForm has a Hide method, you can call it to hide your form.

Example:

Private Sub btnCancel_Click()
    yourFormName.Hide
End Sub

Using the Hide method will only hide the form, it will be totally closed when you close your Excel file.

If you make changes in the form, hide it and then show it again all changes will be kept (ex: change the value of a textbox before hiding it and it will stay the next time you show your form).

The Activate event won’t be triggered next time you show the form since the form was still active but hidden.


2. Unload Method

You can call the Unload method to unload your form.

Example:

Private Sub btnCancel_Click()
    Unload me
End Sub

The form is unloaded from the memory. If you make changes in your form and then unload it, it won’t be kept next time you show your form unlike with the Hide method.

Содержание

  1. VBA Close UserForm | 2 лучших метода закрытия пользовательской формы с примерами
  2. Excel VBA Закрыть пользовательскую форму
  3. Как закрыть UserForm в Excel VBA?
  4. # 1 — Закройте пользовательскую форму с помощью инструкции «Unload Me» в VBA
  5. # 2 — Закройте UserForm с помощью метода Hide в Excel VBA
  6. Разница между выгрузкой и скрытием в Excel VBA
  7. VBA Закрыть UserForm — Лучшие методы закрытия UserForm в Excel VBA
  8. Excel VBA Закрыть UserForm
  9. Как закрыть UserForm в Excel VBA?
  10. Excel VBA Закрыть UserForm — Пример # 1
  11. Excel VBA Закрыть UserForm — Пример № 2
  12. Excel VBA Закрыть UserForm — Пример № 3
  13. Excel VBA Закрыть UserForm — Пример № 4
  14. То, что нужно запомнить
  15. Рекомендуемые статьи

VBA Close UserForm | 2 лучших метода закрытия пользовательской формы с примерами

Когда мы создаем пользовательскую форму, она принимает данные в качестве ввода от пользователей, но данные, предоставленные форме, не закрываются, поэтому это может ввести пользователя в заблуждение, чтобы снова ввести данные, мы используем две разные команды, чтобы закрыть пользовательскую форму, когда ввод было дано, и это метод Unload me, чтобы закрыть пользовательскую форму, или мы можем использовать метод userform.hide.

Excel VBA Закрыть пользовательскую форму

Пользовательские формы жизненно важны при получении входных данных от пользователя в рамках проекта VBA. Обычно мы разрабатываем форму пользователя до того, как представим ее пользователю. После завершения проектирования пользовательской формы VBA нам нужно показать то же самое перед пользователем и потребовать кодирования VBA. Аналогично, чтобы закрыть пользовательскую форму, требуются знания кодирования VBA.

В этой статье мы покажем вам, как закрыть пользовательскую форму в кодировке VBA.

Как закрыть UserForm в Excel VBA?

Как только назначение пользовательской формы выполнено, есть смысл продолжать показывать пользовательскую форму перед пользователем, поэтому нам нужно закрыть пользовательскую форму. Мы можем закрыть пользовательскую форму с помощью операторов «Unload Me» и «UserForm.Hide». Хотя оба они немного отличаются друг от друга, в конечном итоге они послужат нашей цели.

Вы можете скачать этот шаблон VBA Close UserForm Excel здесь — VBA Close UserForm Excel Template

# 1 — Закройте пользовательскую форму с помощью инструкции «Unload Me» в VBA

Например, посмотрите на изображение пользовательской формы ниже.

Я назвал пользовательскую форму «MyUserForm».

Если я запустил пользовательскую форму, мы увидим пользовательскую форму, как показано ниже.

Мне нужно заполнить необходимые данные, после того, как информация будет заполнена, если я нажму кнопку «Отправить», она сохранит те же данные на листе, который виден слева.

После нажатия кнопки отправки он захватил данные, которые я ввел в пользовательскую форму.

Если вы заметили, у нас есть еще одна кнопка под названием «Отмена». Что это значит?

Перед тем как отобразить пользовательскую форму, нам нужно настроить эту кнопку. Теперь я вернусь к визуальному базовому редактору, чтобы настроить эту кнопку.

Теперь я дважды щелкну кнопку «Отмена», и откроется автоматическая подпроцедура VBA, как показано ниже.

В этой процедуре нам нужно написать код VBA о том, что должно произойти, если мы нажмем кнопку «Отмена». Когда мы нажимаем на эту кнопку отмены, она должна закрыть пользовательскую форму, над которой мы сейчас работаем.

Итак, напишите код как «Разгрузите меня».

Код:

«Разгрузить меня» — это слово, которое мы используем, чтобы закрыть пользовательскую форму, над которой мы работаем. Здесь пользовательская форма распознает слово «Я» как саму UserForm.

«Выгрузить меня» можно использовать только в этой процедуре пользовательской формы, мы не можем вызывать этот оператор в других модулях. При вызове отобразится сообщение об ошибке « Недопустимое использование ключевого слова « Я »».

Хорошо, давайте теперь запустим код с помощью клавиши F5 или вручную, мы увидим пустую пользовательскую форму.

Заполните данные и нажмите «Отправить».

После нажатия кнопки отправки значения будут сохранены в указанных ячейках.

Если ввод данных завершен, нам нужно закрыть пользовательскую форму, не так ли?

Итак, нажмите кнопку «Отмена», чтобы закрыть пользовательскую форму, она закроет пользовательскую форму.

# 2 — Закройте UserForm с помощью метода Hide в Excel VBA

Мы также можем закрыть Userform, используя метод «Hide» в VBA. Теперь я еще раз дважды щелкну по кнопке отмены, чтобы увидеть частную подпроцедуру.

Поскольку мы уже написали код для закрытия пользовательской формы, мы можем увидеть существующий код в VBA. Сейчас удалю это.

Чтобы использовать метод Hide, нам нужно вызвать пользовательскую форму по ее имени. В данном случае имя нашей пользовательской формы — «MyUserForm».

После упоминания пользовательской формы по ее имени, если мы поставим точку (.), Мы сможем увидеть все свойства и методы этой пользовательской формы. Теперь выберу метод «Скрыть».

Хорошо, давайте еще раз запустим пользовательскую форму. Мы увидим пустую форму пользователя, сначала заполните данные.

Теперь, не нажимая кнопку «Отправить», я нажимаю кнопку отмены, она скроет пользовательскую форму.

Разница между выгрузкой и скрытием в Excel VBA

У вас должен быть вопрос, в чем разница между Unload & Hide, где оба служат одной цели. Между этими двумя есть разница. Теперь сначала я воспользуюсь оператором Unload Me. Посмотрите на изображение ниже.

Я ввел данные в пользовательскую форму, но еще не отправил их. Если я нажму «Отмена», пользовательская форма будет выгружена.

Теперь я снова запущу код с помощью сочетания клавиш Excel F5 или вручную, он отобразит пустую пользовательскую форму.

Несмотря на то, что я по ошибке ввел данные правильно, я нажал кнопку отмены, но когда новая форма пользователя появится снова, я заполнил данные с нуля.

Теперь воспользуюсь методом «Скрыть».

Нет, я нажму кнопку отмены, она скроет видимую пользовательскую форму. Но когда я повторно запускаю макрос, он вернется с данными, которые я уже ввел в пользовательской форме.

Вот как мы можем использовать оператор «Выгрузить» и метод «Скрыть», чтобы закрыть пользовательские формы в Excel VBA.

Источник

VBA Закрыть UserForm — Лучшие методы закрытия UserForm в Excel VBA

Excel VBA Закрыть UserForm

Ранее мы обсуждали, как создать пользовательскую форму в VBA. Теперь для получения ввода от пользователя была кнопка для отправки, в которой затем сохранялось значение, указанное пользователем в листе Excel. Но что после придания значения, форма все еще там. Или что делать, если пользователь не хочет предоставлять какие-либо данные и закрывать форму пользователя. Мы не обсуждали, как мы закроем пользовательскую форму для пользователя. Аналогично кнопке отправки для отправки данных у нас была другая кнопка, которая была для отмены, которая используется для скрытия пользовательской формы. Кнопка отмены также имеет свой собственный код, чтобы скрыть пользовательскую форму от пользователя. Теперь есть два метода, с помощью которых мы можем скрыть пользовательскую форму. Они заключаются в следующем:

  1. Первый метод — когда мы используем метод Unload Me. Этот метод выгружает пользовательскую форму и исчезает с дисплея.
  2. Другой метод, когда мы используем метод Useform.Hide. Этот метод скрывает пользовательскую форму от дисплея.

Рекомендуется использовать второй метод, чтобы закрыть пользовательскую форму, так как первый метод полностью выгружает пользовательскую форму, и любые введенные пользователем данные будут полностью потеряны. Но когда мы используем второй метод сокрытия пользовательской формы, тогда последняя запись, сделанная пользователем в пользовательской форме, все еще присутствует.

Как закрыть UserForm в Excel VBA?

Мы узнаем о том, как закрыть UserForm в Excel VBA с его различием, и на нескольких примерах, но сначала давайте изучим способ закрытия пользовательской формы в VBA.

Есть два способа закрыть пользовательскую форму в VBA:

  1. Выгрузить меня
  2. Спрятать

Вы можете скачать этот шаблон VBA Закрыть UserForm Excel здесь — VBA Закрыть шаблон UserForm Excel

Excel VBA Закрыть UserForm — Пример # 1

Во-первых, давайте попробуем метод закрытия UserForm, используя опцию Unload Me. У нас была пользовательская форма в нашей предыдущей статье, которая выглядит как приведенная ниже.

Для кнопки отправки у нас был наш код, в котором были сохранены данные, введенные пользователем в Excel. Теперь дважды нажмите на кнопку отмены, которая откроет код для того же, как показано ниже,

Код:

Кнопка «Отмена» была второй командной кнопкой, которую мы предоставили пользовательской форме. Теперь напишите оператор кода как Unload me в разделе, как показано на рисунке ниже.

Код:

Мы можем видеть, что Me является оператором Object of Unload. Теперь давайте запустим пользовательскую форму, нажав клавишу F5, чтобы отобразить ее.

Нажмите кнопку «Отмена», чтобы увидеть, что пользовательская форма исчезает, и она возвращает нас к исходной пользовательской форме окна проекта.

Excel VBA Закрыть UserForm — Пример № 2

Теперь давайте попробуем второй метод, метод userform.hide, аналогичный описанному выше, во-первых, давайте откроем форму пользователя из формы пользователя в окне проекта.

Теперь дважды нажмите кнопку отмены, которая откроет код просмотра для кнопки отмены.

У нас уже есть оператор Unload Me, присутствующий в кнопке отмены, очистите код и замените его на оператор Userform.Hide .

Код:

Теперь давайте снова запустим пользовательскую форму, нажав клавишу F5, и отобразим ее на экране.

Когда мы нажимаем кнопку отмены, мы снова перемещаемся в окно проекта пользовательской формы. Теперь всем нам может быть интересно, в чем разница между этими двумя методами, поскольку оба метода полностью закрывают для нас пользовательскую форму, тогда почему второй метод является наиболее рекомендуемым методом для обоих. Мы точно выясним, почему в следующих двух примерах.

Excel VBA Закрыть UserForm — Пример № 3

Теперь давайте перейдем к первому методу Unload Me оператора для кнопки отмены и предоставим некоторые данные для пользовательской формы. Дважды щелкните на кнопке отмены в пользовательской форме, чтобы открыть код представления для командной кнопки и заменить код оператором Unload Me, как показано ниже.

Код:

Теперь снова запустите пользовательскую форму, нажав клавишу F5, и отобразите ее на экране.

Давайте предоставим некоторые данные для пользовательской формы следующим образом, теперь не нажимайте кнопку отправки, нажмите кнопку «Отмена».

Снова запустите пользовательскую форму, нажав клавишу F5.

Теперь мы можем видеть, что мы потеряли данные, которые мы предоставили пользовательской форме, так как мы не предоставили ее, она не была сохранена на рабочем листе, и мы закрыли пользовательскую форму с помощью оператора Unload Me, который удалил уже заполненные данные.

Excel VBA Закрыть UserForm — Пример № 4

Теперь давайте сделаем то же самое упражнение, но с помощью оператора Userform.Hide,

В командной кнопке отмены замените код, используя метод userform.hide, как показано ниже.

Код:

Теперь мы снова запустим пользовательскую форму, нажав клавишу F5, и предоставим ей некоторые данные следующим образом.

Теперь давайте нажмем кнопку отмены и снова запустим пользовательскую форму, которая даст нам следующий результат.

Данные даже не теряются, когда мы нажимаем кнопку «Отмена», если мы нажимаем «Отправить», данные сохраняются в Excel следующим образом.

Теперь данные сохранены, пользовательская форма теперь пуста, и мы можем закрыть пользовательскую форму, используя кнопку отмены,

То, что нужно запомнить

  • После того, как пользователь введет данные, нам нужно закрыть пользовательскую форму, чтобы она была так же важна, как кнопка отправки.
  • Закрыть пользовательская форма находится в командной кнопке пользовательской формы в VBA. Как правило, она называется Отмена или Закрыть.
  • Есть два отдельных метода закрытия пользовательской формы, но они в конечном итоге служат той же цели, что и друг друга.
  • Метод Userform.Hide наиболее рекомендуется, поскольку даже если пользовательская форма закрыта пользователем перед вводом данных, данные не теряются, и введенная пользователем запись снова отображается, когда пользователь открывает пользовательскую форму.

Рекомендуемые статьи

Это руководство по VBA Close UserForm. Здесь мы обсудим, как закрыть UserForm в Excel, используя оператор Unload Me и метод Userform.Hide в VBA, а также некоторые практические примеры и загружаемый шаблон Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Как активировать лист в VBA?
  2. Оценить формулу в Excel
  3. Полное руководство по списку VBA
  4. HYPERLINK Формула в Excel

Источник

Понравилась статья? Поделить с друзьями:
  • Close excel file with vba
  • Close excel file from vba
  • Close document closes word
  • Close all windows excel
  • Close all excel workbooks vba