How to call a command button click event from code

  • Thread starter Thread starter tsison7
  • Start date Start date
T

tsison7

Is it possible to call a command button click event from another form through
VB? If so how?
 
Is it possible to call a command button click event from another form through
VB? If so how?

Yes, if the form is open. If you're going to reuse the code, though, I'd store
it in a Module and call it from two different places (the first form's button
Click event for example).


John W. Vinson [MVP]
 
tsison7 said:
Is it possible to call a command button click event from another form through
VB? If so how?


As long as the forms are open, no problem. The trick is to
understand that Public procedures in a form are methods of
the form. The standard syntax for calling a method of an
object is:
object.method

In the case of a form method you would use:
Forms!formA.commandbuttonname_Click
 
I believe the form does NOT have to be open.

Try this ...

1 Create a new form.

2 Place a command button on the form (name it "cmdMyCommandButton").

3 Put the following code into the command button's Click event -
MsgBox "Here."

(
It should look like this -
Private Sub cmdMyCommandButton_Click()
MsgBox "Here"
End Sub
)

4 Change "Private" to "Public" so it looks like this -
Public Sub cmdMyCommandButton_Click()
MsgBox "Here"
End Sub

5 Save and close the form (name it "Form1").

6 Create a new module and in it a procedure like this -
Public Sub DoIt()
Form_Form1.cmdMyCommandButton_Click
End Sub

7 With the cursor within the procedure, click the "Run Sub" Toolbar icon ...
a "Here" message should display.

Good luck!
 
Try this.

Change the code behind the Click event of your command button from, say,
"Private Sub MyButton_Click()" to "Public Sub MyButton_Click()" then use the
line following to execute the code from, say, a module -
Form_MyForm.MyButton_Click (where "MyForm" is the name of your form)

The form does NOT have to be open.
 
I believe it is NOT necessary that a form be open to use its code.

You call the sub behind the command button with this line -

Form_frmFormName.cmdButton_Click

where frmFormName is the name of the form containing the command button and
cmdButton is the name of the command button.

BUT FIRST YOU MUST change the clcik procedure behind the command button from
"Private Sub cmdButton_Click()" to "Public Sub cmdButton_Click()".
 
Back
Top