Sub CheckInputErrors()
Dim lastRow As Long
Dim i As Long
Dim ws As Worksheet
Dim errorCount As Long
Set ws = ThisWorkbook.Sheets("入力シート")
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
errorCount = 0
' チェック前にセルの色をリセット
ws.Range("A2:C" & lastRow).Interior.ColorIndex = xlNone
For i = 2 To lastRow
' 氏名:未入力チェック
If Trim(ws.Cells(i, "A").Value) = "" Then
ws.Cells(i, "A").Interior.Color = RGB(255, 200, 200)
errorCount = errorCount + 1
End If
' 年齢:数値チェック
If Not IsNumeric(ws.Cells(i, "B").Value) Or ws.Cells(i, "B").Value <= 0 Then
ws.Cells(i, "B").Interior.Color = RGB(255, 200, 200)
errorCount = errorCount + 1
End If
' 入社日:日付チェック
If Not IsDate(ws.Cells(i, "C").Value) Then
ws.Cells(i, "C").Interior.Color = RGB(255, 200, 200)
errorCount = errorCount + 1
End If
Next i
' 結果通知
If errorCount > 0 Then
MsgBox errorCount & " 件の入力ミスがあります。赤く表示されたセルを確認してください。", vbExclamation
Else
MsgBox "入力ミスはありません!", vbInformation
End If
End Sub
チェック内容をカスタマイズするには?
チェック項目
方法例
数値が範囲外
If value < 0 Or value > 100 Then...
必須項目の未入力
If Trim(value) = "" Then...
日付が未来
If value > Date Then...
' 例:年齢が18歳未満の場合
If ws.Cells(i, "B").Value < 18 Then
ws.Cells(i, "B").Interior.Color = RGB(255, 255, 100)
errorCount = errorCount + 1
End If
応用:チェック結果を一覧に出力する方法
Dim resultWs As Worksheet
Set resultWs = ThisWorkbook.Sheets("チェック結果")
resultWs.Cells.ClearContents
Dim r As Long: r = 1
' チェックの中で条件に一致したらログに出力
resultWs.Cells(r, 1).Value = "行番号"
resultWs.Cells(r, 2).Value = "エラー内容"
r = r + 1
If Trim(ws.Cells(i, "A").Value) = "" Then
resultWs.Cells(r, 1).Value = i
resultWs.Cells(r, 2).Value = "氏名が未入力"
r = r + 1
End If