Ihidan
Ihidan

Reputation: 568

Public and Static Variables

I am trying to run a code to check if the user is logged in on a server. If the user is logged then the public variable loggedIn = true. This value should be preserved so the user could use my user defined function.

Pseudo code:

Public loggedIn as boolean

Sub check_if_is_logged()

  'Code to check if the user is logged
  'if logged then loggedIn = true

end sub

function user_defined()

  'check to see if it is logged
  if loggedIn = false then 
Exit Function

end function

But every time I run the code the values goes back to false and I can't use the function. Is there a way to declare a public and static variable at the same time?

Upvotes: 1

Views: 164

Answers (1)

David Zemens
David Zemens

Reputation: 53623

The function user_defined will always return False regardless of whether the variable loggedIn is True or False, unless the function declares a return value. So, this will give the appearance that the loggedIn public variable is not persisting as desired/expected. I suspect if you debug your code and step through it, you will observe that to be the case: loggedIn correctly is True, but the user_defined function is not returning the value correctly.

This apparently works for me

Public loggedIn As Boolean

Sub check_if_is_logged()

    loggedIn = True

End Sub

Function user_defined()
    Dim ret As Boolean

    If loggedIn Then ret = True

    user_defined = ret
End Function

In the loggedIn procedure I simply assume the user is logged in (of course you would have logic that determines whether True or False).

Then, if I query the user_defined function, by doing ?user_defined in the immediate window, the result is True.

The value of loggedIn does not revert back to False.

If you observe something different, then check your logic which could be mistaken, or perhaps you are doing something to End runtime which would clear out the public variables.

NOTE: This will not persist through an End statement (although it should persist through End Sub, End Function, End Type, End Enum, etc.). This will also not persist beyond closing the workbook/etc. You would need to save the value to a Name in the workbook, or to the CustomDocumentProperties collection.

Upvotes: 1

Related Questions