VBA allows you to create both read-only properties (i.e., those that can only retrieve data) and write-only properties (i.e., those that can only assign values).
When declaring a read-only property, there is no need to define a Property Let or Property Set procedure. When declaring a write-only property, the Property Get block is omitted.
In the following example, a class Point is created.
- The properties GetX and GetY are read-only properties that allow reading the values of the fields.
- The properties SetX and SetY are write-only properties intended for assigning values to the fields.
Additionally, the class defines a ToString() method for outputting general information about the class instance as a string.
« Read-only » and « Write-only » properties. Class module Point
Private x As Integer
Private y As Integer
Public Property Get GetX() As String
GetX = x
End Property
Public Property Let SetX(ByRef valX As String)
x = valX
End Property
Public Property Get GetY() As String
GetY = y
End Property
Public Property Let SetY(ByRef valY As String)
y = valY
End Property
Public Function ToString() As String
ToString = "(" & x & "," & y & ")"
End Function
« Read-only » and « Write-only » properties. Standard module
Sub DemoOnlyProperties() Dim p As New Point p.SetX = 1 : p.SetY = 4 Debug.Print p.ToString Debug.Print p.GetX & vbTab & p.GetY End Sub