Search code examples
vbaexceluserform

VBA Userform not closing on command button click


I am running a Userform in Excel VBA and it seems to work, however, it doesn't seem to close. Basically, once the data is input into the form and a "SUBMIT" button is clicked, I would like the data stored in certain cells and close the form as well as run another sub code.

The following is my VBA code:

Private Sub CommandButton1_Click()
HaulerRatesForm.Label1.Caption = Worksheets("Dashboard").Range("A47").Value
HaulerRatesForm.Label2.Caption = Worksheets("Dashboard").Range("A48").Value
HaulerRatesForm.Label3.Caption = Worksheets("Dashboard").Range("A49").Value
HaulerRatesForm.Label4.Caption = Worksheets("Dashboard").Range("A50").Value

HaulerRatesForm.Show

End Sub

Private Sub UserForm_Initialize()

End Sub

Private Sub CommandButton2_Click()
Worksheets("Dashboard").Cells(47, "H").Value = HaulerRatesForm.TextBox1.Value
Worksheets("Dashboard").Cells(48, "H").Value = HaulerRatesForm.TextBox2.Value
Worksheets("Dashboard").Cells(49, "H").Value = HaulerRatesForm.TextBox3.Value
Worksheets("Dashboard").Cells(50, "H").Value = HaulerRatesForm.TextBox4.Value

Unload Me

Call Dashboardcodes2

End Sub

I can't seem to figure out why Unload Me doesn't seem to close the window. Any ideas as to what I'm doing wrong here?


Solution

  • Thanks to urdearboy, this answered previously seems to answer my question.

    I used the below code by navigating directly to the userform's button by double-clicking on it:

    Private Sub CommandButton2_Click()
    Worksheets("Dashboard").Cells(47, "H").Value = HaulerRatesForm.TextBox1.Value
    Worksheets("Dashboard").Cells(48, "H").Value = HaulerRatesForm.TextBox2.Value
    Worksheets("Dashboard").Cells(49, "H").Value = HaulerRatesForm.TextBox3.Value
    Worksheets("Dashboard").Cells(50, "H").Value = HaulerRatesForm.TextBox4.Value
    
    Unload Me
    
    End Sub
    

    I placed the code in Dashboardcodes2 under Unload Me and everything is now working perfectly.