vba 用户表单中的全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20800088/
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-08 17:29:02  来源:igfitidea点击:

Global Variable in Userform

vbaglobal-variablesuserform

提问by AndroidDev

I search about this in the forum and found some answers but did not work for me.

我在论坛中搜索了这个并找到了一些答案,但对我不起作用。

I have two UserForms.

我有两个用户窗体。

In the first one, I give a value to a variable called Word.

在第一个中,我为名为 Word 的变量赋值。

In the second one, I have a Label that I need the caption to become the variable Word.

在第二个中,我有一个标签,我需要将标题变成变量 Word。

Example:

例子:

Public Word as String

Private Sub Userform1_Activate
   Word = "Today Is Saturday"
End Sub

Private Sub Userform2_Activate
   Label1.Caption = Word
End Sub

But this does not work. The Label caption gets Zero for value. Could anybody help me on this?

但这不起作用。标签标题的值为零。有人可以帮我吗?

Thanks.

谢谢。

First Form

Private Sub CommandButton5_Click()

Db = "C:\Users\Desktop\db.txt"

Set File1 = CreateObject("Scripting.FileSystemObject")
Set File2 = File1.OpenTextFile(Db, 1)

Do Until File2.AtEndOfStream

If (File2.Readline = TextBox1) Then Exit Do
If File2.AtEndOfStream Then WordNotFound.Show
If File2.AtEndOfStream Then TextBox1.Value = ""
If File2.AtEndOfStream Then Exit Sub

Loop

Word = File2.Readline

MsgBox Word

TextBox1.Value = ""

End Sub

Second Form

第二种形式

Private Sub UserForm_Click()

Label1.Caption = Word

End Sub

回答by Pankaj Jaju

As I said in my comment, that your method should work. Here is the test code that I tried

正如我在评论中所说,你的方法应该有效。这是我试过的测试代码

1- In Module1

1- 输入 Module1

Public Word As String

2- Create 2 user forms - UserForm1and UserForm2

2- 创建 2 个用户表单 -UserForm1UserForm2

2a- In UserForm1

2a- 在 UserForm1 中

Private Sub UserForm_Activate()
    Word = "This is Saturday"
End Sub

2b- In UserForm2

2b- 在 UserForm2 中

Private Sub UserForm_Activate()
    Label1.Caption = Word
End Sub

3- Then in ThisWorkbook

3-然后在 ThisWorkbook

Private Sub Workbook_Open()
    UserForm1.Show
    UserForm2.Show
End Sub

So when you close UserForm1, the UserForm2 would be displayed as below

因此,当您关闭 UserForm1 时,UserForm2 将显示如下

enter image description here

在此处输入图片说明