Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Pass Form Controls to Function

Tags:

excel

vba

All,

I have been struggling with this for a while: is it possible to pass an object to a function?

Here is what I am trying to accomplish:

  1. Get the name of which control was pressed on a form (as object?)
  2. Send the control's name to function "MyFunction" (as reference?)
  3. Disable that same control on "MyFunction"

Called from form1:

Private Sub button1_Click()
    Dim caller As String
    caller = Form1.ActiveControl.Name

    MyFunction(caller)

End Sub 'I'm able to pass it as a string

button1_Click calls MyFunction and passes caller to it:

Private Sub MyFunction(caller As String)
    caller.Enabled = False
End Sub

I understand this will not work as a string. How could I possibly do it as an actual object? Thank you!

like image 214
Elias Avatar asked Aug 17 '26 19:08

Elias


1 Answers

There is little problem passing an object to a sub:

Private Sub Disable(c As Control)
    MsgBox c.Name
    c.Enabled = False
End Sub

Private Sub CommandButton1_Click()
    Disable CommandButton1
End Sub

Private Sub CommandButton2_Click()
    Disable CommandButton2
End Sub

Private Sub CommandButton3_Click()
    Disable CommandButton3
End Sub

In the above I created a userform with three buttons, they say who they are when clicked and are then disabled.

Note that

Disable CommandButton1

can be replaced by

Disable Me.ActiveControl

or even just

Disable ActiveControl
like image 85
John Coleman Avatar answered Aug 19 '26 14:08

John Coleman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!