How Sub refers to cmdButton that called it

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have 5 command buttons (cmd_Cust, cmd_Agent ...etc) each with code like
this:

Private Sub cmd_Cust_Click()
cmd_Cust.ForeColor = RGB(255, 0, 0)
Call SortCriteria("Cust")
End Sub

Each button calls Sub SortCriteria. Here is my question. The code for Sub
SortCriteria needs to refer to the button that called it. Should I pass the
name of the command button, or is there a better way to do this. Either way,
I'm just not sure of the proper syntax.

thanks in advance--
cinnie
 
cinnie said:
I have 5 command buttons (cmd_Cust, cmd_Agent ...etc) each with code
like this:

Private Sub cmd_Cust_Click()
cmd_Cust.ForeColor = RGB(255, 0, 0)
Call SortCriteria("Cust")
End Sub

Each button calls Sub SortCriteria. Here is my question. The code
for Sub SortCriteria needs to refer to the button that called it.
Should I pass the name of the command button, or is there a better
way to do this. Either way, I'm just not sure of the proper syntax.

You could pass the name of the command button, or a direct object
reference to the button itself; whichever is most convenient. If the
name of the button can always be constructed from the string argument
you're already passing, you could just use that; e.g.,

Private Sub SortCriteria(sCriteria As String)

' ... do something with sCriteria ...

' Do something with the button:
With Me.Controls("cmd_" & sCriteria)
.ForeColor = RGB(255, 0, 0)
End With

End Sub

To pass the name of the button as well as what you're passing now:

Call SortCriteria("Cust", "cmd_Cust")

Private Sub SortCriteria(sCriteria As String, sCtlName As String)

' ... do something with sCriteria ...

' Do something with the button:
With Me.Controls(sCtlName)
.ForeColor = RGB(255, 0, 0)
End With

End Sub


To pass an object reference to the button:

Call SortCriteria("Cust", Me!cmd_Cust)

Private Sub SortCriteria( _
sCriteria As String, _
cmdButton As Access.CommandButton)

' ... do something with sCriteria ...

' Do something with the button:
With cmdButton
.ForeColor = RGB(255, 0, 0)
End With

End Sub
 
If you can assume that the button that called the code has focus (because
the user clicked it), you can determine which button that is from the Name
of the form's ActiveControl.

But that could fail if a) the button's code may SetFocus somewhere else, or
b) you Call cmd_Cust_Click (i.e. if the code is fired in some other way than
clicking the button.) Therefore it would be better to pass the information
to your SortCriteria() function.
 
Back
Top