入力値のフォーマットとエラー処理

Private Sub txtDateInput_LostFocus()
    Dim inputValue As String
    Dim formattedValue As String
    Dim yearValue As Integer
    Dim monthValue As Integer
    
    ' テキストボックスから入力値を取得
    inputValue = Me.txtDateInput.Value
    
    ' 入力値が6文字であることを確認
    If Len(inputValue) = 6 Then
        ' 年と月を取得
        yearValue = Val(Left(inputValue, 4))
        monthValue = Val(Right(inputValue, 2))
        
        ' 年月が暦日であるかを判定
        If yearValue >= 1900 And yearValue <= 2099 And monthValue >= 1 And monthValue <= 12 Then
            ' 暦日の場合、背景色を白に設定
            Me.txtDateInput.BackColor = RGB(255, 255, 255)
            
            ' 年と月を"/"で区切り、フォーマット
            formattedValue = Left(inputValue, 4) & "/" & Right(inputValue, 2)
            ' テキストボックスにフォーマットされた値を表示
            Me.txtDateInput.Value = formattedValue
        Else
            ' 暦日でない場合、エラーメッセージと背景色を赤に設定
            ShowErrorMessage()
        End If
    Else
        ' エラーメッセージと背景色を赤に設定
        ShowErrorMessage()
    End If
End Sub

Private Sub ShowErrorMessage()
    MsgBox "正しい形式で入力してください(YYYYMM)", vbExclamation, "エラー"
    Me.txtDateInput.BackColor = RGB(255, 0, 0)
End Sub