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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:08:22  来源:igfitidea点击:

Passing text box control to private sub/function

vbams-access

提问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

I found the answer here. You can declare:

我在这里找到了答案。您可以声明:

Private Sub SetIntialToggleValue(ByRef ControlName As MSForms.TextBox)

回答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 Controlin your method, but if you're only using textboxes, you could replace Controlwith Textbox. Indeed, Textboxis its own type.

目前,您没有传入文本框的名称。您正在传入文本框对象本身。您确实Control在方法中将其引用为 a ,但如果您仅使用文本框,则可以替换ControlTextbox. 确实,Textbox是它自己的类型。