【问题标题】:Passing forms information in vba在 vba 中传递表单信息
【发布时间】:2018-08-05 06:28:48
【问题描述】:

我有一个子,我在其中定义了 2 个变量,并将其中 1 个字符串分配给我已经创建的表单中的文本框。

Sub test()

   dim x as string
   dim y as string
   x = "hello"
   y = "friends"

   myForm.textbox1.value = x
   myForm.show

End sub

现在表单处于活动状态,并且表单正在征求信息,并根据用户输入执行其他代码,我记得我的字符串 y 是相关的。但我不需要它在文本框中。这是我开始怀疑的地方:有什么方法可以将数据传递给表单,以便表单“可以看到”来自子 test() 的活动,而无需将其分配给表单上的对象?

【问题讨论】:

  • 公共变量?

标签: vba excel


【解决方案1】:

或者你可以使用 UserForm 对象的 Tag 属性

Sub test()

    dim x as string
    dim y as string
    x = "hello"
    y = "friends"

    With myForm
        .Tag = y ‘ “pass” the value of y to the form by storing it into its Tag property
        .textbox1.value = x
        .show
        y = .Tag ‘ assign y the value stored in the form Tag property 
    End With
End sub

这样,在您的用户窗体代码中,您可以按如下方式检索该值:

Dim y As String ‘ being inside the form this is a locally scoped variable
y= Me.Tag ‘ assign “local” y the value stored in Tag property from outside the form
.... ‘ your code
Me.Tag = y ‘ store final value of “local” y to Tag property and make it avalable to the “outer” world

【讨论】:

    【解决方案2】:

    一个公共范围变量将对表单可见。可以为测试子中的变量设置该值。如果您想要在测试子中分配的值,您希望测试子在加载表单之前运行。

    公共/全局变量在子模块之外的模块顶部声明。

    在此处查看讨论:How do I declare a global variable in VBA?

    【讨论】:

      【解决方案3】:

      正如其他答案所建议的那样,您可以使用公共变量,但我也建议您查看一下,也许可以使用公共属性。

      属性不同于公共变量,因为有了属性,您可以在客户端获取或设置值时执行您自己的代码。

      Take a look at this post here on StackOverflow

      【讨论】:

        猜你喜欢
        • 2016-01-17
        • 1970-01-01
        • 2015-09-17
        • 2013-06-01
        • 1970-01-01
        • 2015-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多