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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/374324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 10:07:53  来源:igfitidea点击:

Passing Object reference in Visual Basic (VBA)

excelvbaexcel-vba

提问by Jox

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

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

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.TextBox1passes the Stringfrom TextBox1instead of the object reference.

DoSmthWithTextBox Me.TextBox1传递StringfromTextBox1而不是对象引用时会出现问题。

How do I pass the TextBoxobject to the DoSmthWithTextBoxmethod?

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

回答by Fionnuala

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 有一个对象文本框是一个形状,而用户窗体使用 ActiveX 控件文本框,因此您需要显式引用 MSForms 库。