Kian
Kian

Reputation: 1169

Closing a Userform with Unload Me doesn't work

I need to close an Excel userform using VBA when a user has clicked a submit button and operations have been carried out.

How can I close a Userform from itself?

I have tried this but it returns a 361 error.

Unload Me

Upvotes: 24

Views: 223167

Answers (4)

SamG
SamG

Reputation: 1

It should also be noted that if you have buttons grouped together on your user form that it can link it to a different button in the group despite the one you intended being clicked.

Upvotes: -1

user4059073
user4059073

Reputation: 256

As specified by the top answer, I used the following in the code behind the button control.

Private Sub btnClose_Click()
    Unload Me
End Sub

In doing so, it will not attempt to unload a control, but rather will unload the user form where the button control resides. The "Me" keyword refers to the user form object even when called from a control on the user form. If you are getting errors with this technique, there are a couple of possible reasons.

  1. You could be entering the code in the wrong place (such as a separate module)

  2. You might be using an older version of Office. I'm using Office 2013. I've noticed that VBA changes over time.

From my experience, the use of the the DoCmd.... method is more specific to the macro features in MS Access, but not commonly used in Excel VBA.

Under normal (out of the box) conditions, the code above should work just fine.

Upvotes: 24

SWa
SWa

Reputation: 4363

Without seeing your full code, this is impossible to answer with any certainty. The error usually occurs when you are trying to unload a control rather than the form.

Make sure that you don't have the "me" in brackets.

Also if you can post the full code for the userform it would help massively.

Upvotes: 11

Tomamais
Tomamais

Reputation: 95

Unload Me only works when its called from userform self. If you want to close a form from another module code (or userform), you need to use the Unload function + userformtoclose name.

I hope its helps

Upvotes: 4

Related Questions