
【投稿時のバージョン】
Microsoft365
エクセルのRegexp正規表現を使用したメールチェックできるマクロを作成してみたいと思います。
とはいってもメールの場合は各メーカーのメーラーによってパターンが違いますので完全にわかりませんがある程度は抜き出せるので実行してみたいと思います。
仕事の業務で使ったことがあるので同じシステムを使用してる場合はかなりエラーを判定できます。
A列にメールアドレスをセットするとB列に判定結果が出てオートフィルターされるといったものです。
そのままコピペで使用できます。
メールエラーチェックマクロ使用例
VBAコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | Option Explicit Private Const DATACOL As Integer = 1 Private Const HANTEICOL As Integer = 2 Private Const OFFCOL As Integer = 1 Private Const NG As String = "NG" Private Const TOKUSHU As String = "NG2" Sub mailChk() '参照設定 'Microsoft VBScript Regular Expressions 1.0 Dim fName, f As Variant Dim lastRow As Long Dim e, rng As Range Dim rExp As New RegExp fName = Application.GetOpenFilename() 'キャンセルボタンが押されたときの処理 If VarType(fName) = vbBoolean Then Set rExp = Nothing Exit Sub ElseIf IsArray(fName) Then For Each f In fName Debug.Print f Next Else Debug.Print fName Workbooks.Open fName End If rExp.IgnoreCase = False rExp.Global = True Rows(1).Insert lastRow = Cells(Rows.Count, DATACOL).End(xlUp).Row 'データがA列に存在しないときの処理 If lastRow = 1 Then Rows(1).Delete Set rExp = Nothing MsgBox "A列にデータが存在しません。" Exit Sub End If Range("B:B").ClearContents Set rng = Range(Cells(1, DATACOL), Cells(lastRow, DATACOL)) 'エラー検索 rExp.Pattern = "^.+@.+\..+$" For Each e In rng If rExp.test(e.Value) = False Then e.Offset(, OFFCOL) = NG End If Next rExp.Pattern = "^[^\w]|[^\w]$|\s|@.+\.\.+|_$" For Each e In rng If rExp.test(e.Value) Then e.Offset(, OFFCOL) = TOKUSHU End If Next rExp.Pattern = "^\x20|\x20$" For Each e In rng If rExp.test(e.Value) Then e.Offset(, OFFCOL).ClearContents End If Next Rows(1).Delete Rows("1:1").Select 'オートフィルタ― Selection.AutoFilter Field:= _ HANTEICOL, _ Criteria1:=NG, _ Operator:=xlOr, _ Criteria2:=TOKUSHU Columns(DATACOL).ColumnWidth = 40 Set rng = Nothing Set rExp = Nothing MsgBox "FINISH" End Sub |
実行手順
①参照設定でMicrosoft VBScript Regular Expressionsを追加してください。
②新しいエクセルファイルを作成してA列にメールアドレスをセットし保存します。
③マクロを実行したら結果がB列にNGとNG2と表示されオートフィルターされます。
同じシステムを使用の場合でも完全には判別できませんが大量のデータがある場合はかなり役に立ちます。
【Excel VBA】正規表現でいろいろなパターンを判別 RegExp
【Excel VBA】Like演算子でパターンのサンプル例をご紹介!