5

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?

0

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for knowing the difference. ;-) Can you write a short explanation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.