Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Variable in Userform

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
like image 234
AndroidDev Avatar asked Sep 16 '25 18:09

AndroidDev


1 Answers

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

like image 77
Pankaj Jaju Avatar answered Sep 19 '25 20:09

Pankaj Jaju