vba 将文本框控制传递给私有子/函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26763838/
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
Passing text box control to private sub/function
提问by Alex
I have a series of text boxes that I want to evaluate on form load to change some other elements of the form. Rather than processing them line by line I want to create a function. How can I pass the name of the text box to a function. For example:
我有一系列文本框,我想评估表单加载以更改表单的其他一些元素。我想创建一个函数,而不是逐行处理它们。如何将文本框的名称传递给函数。例如:
Private Sub Form_Load()
Call SetIntialToggleValue(MyTextboxName)
End Sub
Private Sub SetIntialToggleValue(ByRef ControlName As Control)
MsgBox ControlName.Value
End Sub
This give me "Object required" error on the MsgBox line. Which makes me think I'm not passing the textbox control properly.
这在 MsgBox 行上给了我“需要对象”错误。这让我觉得我没有正确传递文本框控件。
回答by alrm3000
I would ask for clarification if I had enough rep to comment, but here are some thoughts:
如果我有足够的代表发表评论,我会要求澄清,但这里有一些想法:
If you haven't explicitly declared your variable, MyTextboxName, it will be of type variant. You can't pass a variant to an object parameter. This might be enough:
如果您没有明确声明您的变量 MyTextboxName,它将是类型变体。您不能将变体传递给对象参数。这可能就足够了:
dim MyTextBoxName as Control
But in this case, you wouldn't be working with names at all. If you want to work with names, you have to change your function. Change the signature to take a string and then use the string as the index into the Controls collection (if there is one on Access Forms):
但在这种情况下,您根本不会使用名称。如果要使用名称,则必须更改函数。更改签名以获取一个字符串,然后使用该字符串作为 Controls 集合的索引(如果 Access Forms 上有一个):
Private Sub SetIntialToggleValue(ByRef ControlName As String)
MsgBox Form.Controls(ControlName).Value
End Sub
回答by Wayne G. Dunn
How about something like the following:
怎么样像下面这样:
Option Explicit
Dim ctl as Control
Private Sub Form_Load()
set ctl = Me.MyTextboxName
Call SetIntialToggleValue(ctl)
End Sub
Private Sub SetIntialToggleValue(ByRef ControlName As Control)
MsgBox ControlName.Value
End Sub
回答by Leon Rom
回答by Bobort
Currently, you're not passing in the name of the textbox. You're passing in the textbox object itself. You did reference it as a Control
in your method, but if you're only using textboxes, you could replace Control
with Textbox
. Indeed, Textbox
is its own type.
目前,您没有传入文本框的名称。您正在传入文本框对象本身。您确实Control
在方法中将其引用为 a ,但如果您仅使用文本框,则可以替换Control
为Textbox
. 确实,Textbox
是它自己的类型。