在Visual Basic(VBA)中传递对象引用

时间:2021-07-26 16:32:48

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

如何将表单的TextBox对象传递给方法?

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.

当DoSmthWithTextBox Me.TextBox1从TextBox1而不是对象引用传递String时,会出现此问题。

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

如何将TextBox对象传递给DoSmthWithTextBox方法?

1 个解决方案

#1


12  

Rewrite for Excel:

重写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.

据我所知,这是因为Excel有一个形状的对象文本框,而userforms使用ActiveX控件文本框,因此您需要显式引用MSForms库。

#1


12  

Rewrite for Excel:

重写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.

据我所知,这是因为Excel有一个形状的对象文本框,而userforms使用ActiveX控件文本框,因此您需要显式引用MSForms库。