'******************************************************************************************
'***氏名フィールドによる入力規則(データベースとの整合性を図るため)*********
'******************************************************************************************
Private Sub Worksheet_Change(ByVal Target As Range)
Dim PreviousValue As String
Dim NowValue As String
Dim i As Integer
'もし氏名フィールドを変更したら
If Target.Column = 5 And Target.Row > 8 Then
'もし変更したセルが空白なら
If Cells(Target.Row, 5) = "" Then
'IDが空白なら
If Cells(Target.Row, 1) = "" Then
i = 1
Do While Cells(Target.Row, i) = ""
i = i + 1
If i = 101 Then
Exit Do
Else
End If
Loop
If i <> 101 Then
'今変更された値を代入する
NowValue = Cells(Target.Row, 5)
With Application
.ScreenUpdating = False '出力停止
.EnableEvents = False 'イベント抑制
.Undo
End With
'変更される直前の値を代入する
PreviousValue = Cells(Target.Row, 5)
With Application
.ScreenUpdating = True '出力開始
.EnableEvents = True 'イベント抑制解除
End With
If PreviousValue = "" Then
'空白を空白にしたらスルーする
Else
Cells(Target.Row, 5) = PreviousValue
MsgBox Cells(8, i) & "に" & Cells(Target.Row, i).Value & "が入力されているため," _
& vbCrLf & "氏名の削除はできません。ただし氏名の変更は可能です"
End If
Else
End If
Else
'今変更された値を代入する
NowValue = Cells(Target.Row, 5)
With Application
.ScreenUpdating = False '出力停止
.EnableEvents = False 'イベント抑制
.Undo
End With
'変更される直前の値を代入する
PreviousValue = Cells(Target.Row, 5)
With Application
.ScreenUpdating = True '出力開始
.EnableEvents = True 'イベント抑制解除
End With
If PreviousValue = "" Then
'空白を空白にしたらスルーする
Else
Cells(Target.Row, 5) = PreviousValue
MsgBox "氏名の削除はできません。" & vbCrLf & "ただし氏名の変更は可能です"
End If
End If
Else
'もし1つ上のセルが空白なら
If Cells(Target.Row - 1, 5) = "" Then
With Application
.ScreenUpdating = False '出力停止
End With
'このループでデータをどの行に移動すればいいか判断する
i = Target.Row - 1
Do While Cells(i, 5).Value = ""
i = i - 1
Loop
'データを現在ある最後尾のセルに移動する。
Cells(i + 1, 5) = Cells(Target.Row, 5)
Cells(Target.Row, 5) = ""
Cells(i + 1, 5).Activate
MsgBox "上から詰めて入力して下さい"
'移動してきたデータを出力する
With Application
.ScreenUpdating = True '出力開始
End With
Else
'MsgBox "詰めて入力できているのでOK"
End If
End If
Else
'氏名フィールドが空白なら
If Cells(Target.Row, 5) = "" And Target.Row <> 6 Then
'もし変更したセルが空白なら
If Target.Value = "" Then
'MsgBox "問題ないのでぬけてよし?"
Else
'IDが空白なら
If Cells(Target.Row, 1) = "" Then
Application.EnableEvents = False
Cells(Target.Row, Target.Column) = ""
Application.EnableEvents = True
MsgBox "はじめに氏名を入力しないと" & vbCrLf & "正しくデータが保存されません?"
Cells(Target.Row, 5).Activate
Else
MsgBox "ありえるか?氏名空白,IDあり,他セル入力やろ??"
End If
End If
Else
'MsgBox "氏名があって,他のフィールドを入力したときOK?"
End If
End If
End Sub
'******************************************************************************************
以上です。ここでヒントを得て,
Application.EnableEventsなどのプロパティの存在と機能を
知りました。本当にありがとうございました。