OK Button in UserForm

J

Jack_Feeman

I have placed a commandbutton (the system appropriately named it
CommandButton1) on Sheet 1. When clicked it brings up UserForm1. In the
UserForm I placed another CommandButton which the system appropriately named
CommandButton2. I added the following code in the editor:
"Private Sub CommandButton1_Click()
UserForm1.Show
End Sub

Private Sub CommandButton2_Click()
UserForm1.Hide
End Sub"

It works fine. When you click the button on Sheet 1 it opens the UserForm.
Then when you are done referring to the form you click the commanbutton on
the form (appropriately labeled by me as OK) and the UserForm closes.

The problem is when I start repeating this for 10 more buttons on sheet 1
and 10 more userforms all to react the same way. The code for the first 2
look like this:
"
Private Sub CommandButton1_Click()
UserForm1.Show
End Sub

Private Sub CommandButton2_Click()
UserForm1.Hide
End Sub

Private Sub CommandButton3_Click()
UserForm2.Show
End Sub

Private Sub CommandButton4_Click()
UserForm2.Hide
End Sub"

The problem: the first button and form work fine. The second and subsequent
buttons/forms display but do not go away when the form button is pushed only
when the Cancel (Red X) is pushed.

How can I get "all" the form buttons to close the form window as the first
one does?

Thanks Jack
 
B

Bob Phillips

Are you sure about that naming convention. When I create a userform, the
first button I add gets named CommandButton1, regardless of how many buttons
I have on the worksheet, or on other userforms.

--
HTH

Bob Phillips

(replace somewhere in email address with gmail if mailing direct)
 
J

JLGWhiz

To make it work properly, you need to name all of your command buttons and
refer to that name when showing or hiding. Like Bob said, the sequence that
you add the buttons to the form determines the command button number it gets
assigned by the system, but the name you assign won't be confused. Make sure
it is the Name and Not the Caption that you use.
 
J

Jack_Feeman

Thanks, that is the way I started out. I did not renamed any buttons at first
but I noticed that I had duplicate named buttons in the editor (The first
button on the sheet was named CommandBUtton1 by the system and so was the
first button on the first UserForm so I renamed them in properties (not the
button caption) and that is when everything went astray and it became
confusing. Thanks for confirming the way it is supposed to work. I will start
over and stick to your suggestions making sure all buttons no matter where
they reside have unique names.

Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top