VBA(Visual Basic for Applications)は、Excelなどのアプリケーションを自動化するための強力なツールです。本記事では、VBAを使って入力規則を設定し、無効なデータを簡単にクリアする方法を紹介します。これにより、データの整合性を保ちつつ、作業効率を向上させることができます。
Sub SetValidationAndClearInvalidCells()
Dim ws As Worksheet
Dim cell As Range
Dim rng As Range
' 作業シートを設定
Set ws = ThisWorkbook.Sheets("Sheet1") ' シート名を変更してください
Set rng = ws.Range("A1:A10") ' 入力規則を設定する範囲
' 入力規則を設定(例: リスト形式)
With rng.Validation
.Delete ' 既存の入力規則を削除
.Add Type:=xlValidateList, _
AlertStyle:=xlValidAlertStop, _
Formula1:="Option1,Option2,Option3" ' 許可する値のリストを設定
.IgnoreBlank = True
.InCellDropdown = True
.ShowInput = True
.ShowError = True
End With
' 入力規則に合わないセルの値をクリア
For Each cell In rng
If Not IsEmpty(cell.Value) Then
If Not IsError(Application.Match(cell.Value, Split("Option1,Option2,Option3", ","), 0)) Then
' 値がリスト内に存在する場合は何もしない
Else
cell.ClearContents ' 値をクリア
End If
End If
Next cell
End Sub
コードの解説
シートと範囲の設定: 作業するシートとセル範囲を指定します。
入力規則の設定: リスト形式の入力規則を設定します。
無効なセルのクリア: 値がリストに存在しない場合、セルの値をクリアします。
実行前
実行後
入力規則が設定され、入力規則にあっていないものはクリアされます
数値の範囲の場合
' 入力規則に合わないセルの値をクリア
Dim cell As Range
Dim rng As Range
Set rng = targetCell ' 対象セルを設定
For Each cell In rng
If Not IsEmpty(cell.value) Then
If Not IsNumeric(cell.value) Or cell.value < minValue Or cell.value > maxValue Then
cell.ClearContents ' 値をクリア
End If
End If
Next cell
入力文字数の範囲指定の場合
' 入力規則に合わないセルの値をクリア
Dim cell As Range
Set cell = targetCell ' 対象セルを設定
If Not IsEmpty(cell.value) Then
Dim strLength As Long
strLength = Len(cell.value)
If strLength < minLength Or strLength > maxLength Then
cell.ClearContents ' 値をクリア
End If
End If
日付の範囲の場合
Dim cell As Range
Set cell = targetCell ' 対象セルを設定
If Not IsEmpty(cell.value) Then
If Not IsDate(cell.value) Or cell.value < startDate Or cell.value > endDate Then
cell.ClearContents ' 値をクリア
End If
End If
コメント