首页 > 解决方案 > 在 vba 中传递表单信息

问题描述

我有一个子,我在其中定义了 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是相关的。但我不需要它在文本框中。这是我开始怀疑的地方:有没有什么方法可以将数据传递给表单,以便表单“可以看到”来自 sub 的活动,test()而无需将其分配给表单上的对象?

标签: vbaexcel

解决方案


或者您可以使用 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

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

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

推荐阅读