Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Object reference in Visual Basic (VBA)

Tags:

excel

vba

How do I pass a form's TextBox object to the a method?

The following code is issuing an exception.

Private Sub DoSmthWithTextBox(ByRef txtBox as TextBox)
    txtBox.BackColor = vbRed
End Sub

Private Sub TextBox1_Change()
    DoSmthWithTextBox Me.TextBox1
End Sub

The problem appears when DoSmthWithTextBox Me.TextBox1 passes the String from TextBox1 instead of the object reference.

How do I pass the TextBox object to the DoSmthWithTextBox method?

like image 252
Jox Avatar asked Dec 17 '08 11:12

Jox


People also ask

Does VBA pass object reference?

In VBA all objects are passed by reference although there is a difference. ByRef - the address of the object is passed. ByVal - a copy of the address to the object is passed.

Can you pass an object by reference?

A mutable object's value can be changed when it is passed to a method. An immutable object's value cannot be changed, even if it is passed a new value. “Passing by value” refers to passing a copy of the value. “Passing by reference” refers to passing the real reference of the variable in memory.

How do you pass parameters in VBA?

You can pass an argument by value if you include the ByVal keyword in the procedure's declaration. Arguments passed by value consume from 2–16 bytes within the procedure, depending on the argument's data type. Larger data types take slightly longer to pass by value than smaller ones.


1 Answers

Rewrite for Excel:

Private Sub DoSmthWithTextBox(txtBox As MSForms.TextBox)
    txtBox.BackColor = vbRed
End Sub

As far as I know, this is because Excel has an object textbox that is a shape, whereas userforms use the ActiveX control textbox, so you need an explicit reference to the MSForms library.

like image 133
Fionnuala Avatar answered Sep 29 '22 19:09

Fionnuala