【VBA】クラスのプロパティを読み取り専用にするLet と Getの書き方
記事更新日:2022-08-31

更新が
不要の場合の
対応
不要の場合の
対応
- Public Property Let で 上書き禁止の条件追加
- Private Property Let で 外からの使用禁止
外からの更新を1回だけ許可する場合

すでに値が入ってたら、上書きできないようにする
Private id_ As String
Public Property Let ID(ByVal value As String)
If not id_ = “” then
MsgBox "すでに登録済みです", vbCritical, "上書き禁止"
else
id_ = value
End if
End Property
Public Property Get ID() As String
ID = id_
End Property

IDは何度も更新するものじゃないから
外からの更新を禁止する場合

Property Let を Privateにして、クラス内のみで更新する
Private count_ As Long
Private Property Let Count(ByVal value As Long)
count_ = value
End Property
Public Property Get Count() As Long
Count = count_
End Property

たとえば、どんなときだろう
例1:Accessに接続したとき、レコードのカウントを取得する

Accessに接続するクラスの中に記述する
Public Sub OpenRS()
With RS
.Open ThisSQL, CN
If RS Is Nothing Or (.bof And .EOF) Then Call CancelDB
Count = .Fields.count '☆☆ここでフィールドのカウントを取る
End With
End Sub
例2:クラス初期化のとき、今日の日付から文字列を登録する

「◯年◯月」とか、「更新日:◯月◯日」とか
Private yearmonth_ As Long
Private Sub Class_Initialize()
dim d as date: d = Now()
dim v as string: v = Year(Now) & "年" & Month(Now) & "月"
YearMonth = v '☆☆ここで文字列を作る
End Sub
Private Property Let YearMonth(ByVal value As String)
yearmonth_ = value
End Property
Public Property Get YearMonth() As String
YearMonth = yearmonth_
End Property

自動で設定できるなら、外からの更新がいらない

クラスについての記事はこちら
2022-08-31
編集後記:
この記事の内容がベストではないかもしれません。