4 Years
Discussion Span
Last Post by AndreRet

Some more detailed explanation - (thanx Peter Aitken)...

There are three requirements to creating a global property in a code module:

A Private variable to hold the property value
A Property Let procedure for setting the property value (if the variable will hold an object reference, you will use a Property Set procedure instead)
A Property Get procedure for retrieving the property value
The Get and Let procedures must have the same name. This is the property name that you will use in the program.

The following is sample code for a global property that holds a string value:

Private name As String
Public Property Let gName(ByValnewvalue As String)
    name = newvalue
End Property

Public Property Get gName() As String
    gName = name
End Property

Here's how it works. Suppose that code elsewhere in the program sets the property as follows:

gName = "Alice"

This automatically calls the Property Let procedure with the new value (which is "Alice" in this case) passed as its argument. The code in the Property Let procedure assigns this value to the associated Private variable (which is name in this example). When code reads the value of the property, for example:


It calls the Property Get procedure and returns the value of the Private variable name to the program. (Clearly, the Get procedure is really a function).

In this example, there is no extra processing, so the property behaves just like a global variable. You could, however, include value checking. For example, you might do so to store a default name if the program tries to store a blank name. That would require the following change to the Property Set procedure:

Public Property Let gName(ByValnewvalue As String)
    If newvalue = "" Then
        name = "Default name"
        name = newvalue
    End If
End Property

The use of global properties provides you with more control over global data storage than is possible with global variables.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.