【VBA】プロパティクラス

プロパティクラスの定義

ClsPeron

Private myName As String
Private myAge As String

'コンストラクタ
Private Sub Class_Initialize()
    myName = "名前"
    myAge = "0"
End Sub


'名前を取得
Public Property Get Name() As String
    Name = myName
End Property

'名前をセット
Public Property Let Name(Name As String)
    myName = Name
End Property

'年齢を取得
Public Property Get Age() As String
    Age = myAge
End Property

'年齢をセット
Public Property Let Age(Age As String)
    myAge = Age
End Property


'メソッド
Public Function FirstName() As String
    FirstName = Left(myName, 2)
End Function

使用方法

Sub test()
    Dim person As ClsPeron: Set person = New ClsPeron
    
    '値をセット
    person .Name = "高橋 直樹"

    '値を取得
    Debug.Print person Name

    'メソッド
    Debug.Print person .FirstName
    
End Sub