Announcement

Collapse
No announcement yet.

Unconfigured Ad Widget

Collapse

VBA - Public variable not persisting

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • VBA - Public variable not persisting

    Hi there,

    I'm going absolutely nuts trying to figure out what the problem is with the following. I've declared a public string variable called "password". A form is used to populate this variable. Using a watch I see that the variable persists even after the SetPassword sub finishes. However, on starting the sub Test, the variable is reinitialized. Does anyone know why this is so?

    Thanks for any help!

    Code:
    Public password As String
    Sub GetPassword()
        If password = "" Then frmPassword.Show
    End Sub
    
    'The UserForm calls setPassword and assigns the value from a textbox to the variable
    Sub setPassword(myTextBoxValue As String) 
        password = myTextBoxValue
    End Sub
    
    Sub Test()
        MsgBox password
    End Sub

  • #2
    Re: VBA - Public variable not persisting

    What is the full code of the userform?
    Rory
    Theory is when you know something, but it doesnít work. Practice is when something works, but you donít know why. Programmers combine theory and practice: nothing works and they donít know why

    Comment


    • #3
      Re: VBA - Public variable not persisting

      Here it is...
      Code:
      Private Sub CommandButton1_Click()
          If txtPassword.Value <> "" Then
              Call Telnet.setPassword(txtPassword.Value)
              Unload Me
          End If
      End Sub
      The form consists of a textbox called txtPassword and a button called CommandButton1

      Thanks.

      Comment


      • #4
        Re: VBA - Public variable not persisting

        Have you compiled and saved the workbook?

        I would suggest you change the GetPassword sub to:
        Code:
        Sub GetPassword()
           Dim frm As frmPassword
            If password = "" Then
              Set frm = New frmPassword
              frm.Show
              Set frm = Nothing
           End If
        End Sub
        As a general rule you should avoid using the default instancing of userforms - they are classes and should be treated as such.
        Rory
        Theory is when you know something, but it doesnít work. Practice is when something works, but you donít know why. Programmers combine theory and practice: nothing works and they donít know why

        Comment


        • #5
          Re: VBA - Public variable not persisting

          Hi Rory,

          I shut and opened the workbook and now I have no problems. Grrrr... I can't believe I wasted so much time on this and only had to do that. Thanks for all the help and the tip on calling an instance of the UserForm.

          Comment

          Trending

          Collapse

          There are no results that meet this criteria.

          Working...
          X