Search code examples
excelvbapropertiesuserformcaption

Private String variable not showing in Text Label vba


I want to pass an argument to a user form. The solution that I tried is to set a home made property of my userform (which name is InformationMissing), setting a private variable. Here's the code of my UserForm

Private msMsg As String

Private Sub CommandButton1_Click()
    MsgBox msMsg
End Sub

Private Sub UserForm_Initialize()
    txtLabel1.Caption = "hello" & msMsg
End Sub

Property Let MyProp(sText As String)
    msMsg = sText
End Property

I'm using this Userform from another sub that sets the MyProp property to a String ("aa" in this case):

Sub ShowFormProp()

    Dim myForm As InformationMissing
    Set myForm = New InformationMissing

    myForm.MyProp = "aa"
    myForm.Show

End Sub

What I want to do here is to have "helloaa" prined in my UserForm but I only get "hello". However, when I click the CommandButton1, I get "aa". This means that the property has correctly been set but is not passed to txtLabel1.

Do you have any ideas?

Thanks in advance


Solution

  • UserForm.Initialize is not the correct place to put txtLabel1.Caption = "hello" & msMsg, if you want the caption to reflect changes to the private string variable. Initialize will always be executed before you can access any of the form's properties.

    In your case a good solution would be to perform the changes you want directly in the property procedure.

    Property Let MyProp(sText As String)
        msMsg = sText
        ' You can also put the caption change in its own sub, if you want more things to happen when you change it
        txtLabel1.Caption = "hello" & msMsg
    End Property
    

    Edit: And to reflect what @LatifaShi said in the comments to your question: You've got a typo in there. msMgs and msMsg are not the same variable. Always use Option Explicit at the beginning of each module to prevent this and and many more problems.