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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With