Global Variable in Userform

AndroidDev picture AndroidDev · Dec 27, 2013 · Viewed 46.3k times · Source

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.

In the second one, I have a Label that I need the caption to become the variable 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

Answer

Pankaj Jaju picture Pankaj Jaju · Dec 27, 2013

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

1- In Module1

Public Word As String

2- Create 2 user forms - UserForm1 and UserForm2

2a- In UserForm1

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

2b- In UserForm2

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

3- Then in ThisWorkbook

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

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

enter image description here