Search code examples
vbaexcelexcel-2010

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

Solution

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