■■■■■■■第3章 05■■■■■■■

■■■■p85プロンプト例

あなたは優秀なExcel VBAのプログラマーです。
次の操作をするExcel VBAのプログラムを書いてください。

・シート内にある顧客リストの中で重複データを探す
・顧客リストはA1セルから始っていて、1行目に項目名がある
・項目名は「顧客ID」「名前」「都道府県」「住所」「電話番号」の5つ
・「名前」「都道府県」「住所」「電話番号」がすべて一致したら重複と見なす
・重複データ同士をそれぞれペアにして、「重複データ」シートに出力する
・マクロ名は「重複チェック」とする


■■■■p86コード例

Sub 重複チェック()
    Dim wsSrc As Worksheet
    Dim wsDst As Worksheet
    Dim lastRow As Long
    Dim i As Long, j As Long
    Dim outRow As Long
    Dim key1 As String, key2 As String
    
    ' 元データのシート
    Set wsSrc = ActiveSheet
    
    ' データ最終行
    lastRow = wsSrc.Cells(wsSrc.Rows.Count, "A").End(xlUp).Row
    If lastRow < 2 Then
        MsgBox "データがありません。", vbExclamation
        Exit Sub
    End If
    
    ' 「重複データ」シートを作成（既存なら削除）
    On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets("重複データ").Delete
    Application.DisplayAlerts = True
    On Error GoTo 0
    Set wsDst = Worksheets.Add
    wsDst.Name = "重複データ"
    
    ' 見出し行作成
    wsDst.Range("A1:E1").Value = Array("顧客ID", "名前", "都道府県", "住所", "電話番号")
    wsDst.Range("G1:K1").Value = Array("顧客ID", "名前", "都道府県", "住所", "電話番号")
    wsDst.Range("A1:K1").Font.Bold = True
    outRow = 2
    
    ' 重複チェック（全組み合わせ）
    For i = 2 To lastRow - 1
        key1 = wsSrc.Cells(i, 2).Value & "|" & _
               wsSrc.Cells(i, 3).Value & "|" & _
               wsSrc.Cells(i, 4).Value & "|" & _
               wsSrc.Cells(i, 5).Value
        For j = i + 1 To lastRow
            key2 = wsSrc.Cells(j, 2).Value & "|" & _
                   wsSrc.Cells(j, 3).Value & "|" & _
                   wsSrc.Cells(j, 4).Value & "|" & _
                   wsSrc.Cells(j, 5).Value
            If key1 = key2 Then
                ' ペアで出力
                wsDst.Cells(outRow, 1).Resize(1, 5).Value = wsSrc.Cells(i, 1).Resize(1, 5).Value
                wsDst.Cells(outRow, 7).Resize(1, 5).Value = wsSrc.Cells(j, 1).Resize(1, 5).Value
                outRow = outRow + 1
            End If
        Next j
    Next i
    
    MsgBox "重複チェックが完了しました。", vbInformation
End Sub


■■■■p87プロンプト例

重複データを出力した後、次の操作も加えてください。

・元の顧客リストから重複データを削除する
・削除する前にダイアログボックスを表示し、削除するかどうかをユーザーに確認
　　「はい」と答えたら重複データを削除
　　「いいえ」と答えたら削除せずに終了


■■■■p87コード例（上記プロンプトの出力）

Sub 重複チェック()
    Dim wsSrc As Worksheet
    Dim wsDst As Worksheet
    Dim lastRow As Long
    Dim i As Long, j As Long
    Dim outRow As Long
    Dim key1 As String, key2 As String
    Dim delRows As Collection
    Dim ans As VbMsgBoxResult
    
    ' 元データのシート
    Set wsSrc = ActiveSheet
    
    ' データ最終行
    lastRow = wsSrc.Cells(wsSrc.Rows.Count, "A").End(xlUp).Row
    If lastRow < 2 Then
        MsgBox "データがありません。", vbExclamation
        Exit Sub
    End If
    
    ' 「重複データ」シートを作成（既存なら削除）
    On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets("重複データ").Delete
    Application.DisplayAlerts = True
    On Error GoTo 0
    Set wsDst = Worksheets.Add
    wsDst.Name = "重複データ"
    
    ' 見出し行作成
    wsDst.Range("A1:E1").Value = Array("顧客ID", "名前", "都道府県", "住所", "電話番号")
    wsDst.Range("G1:K1").Value = Array("顧客ID", "名前", "都道府県", "住所", "電話番号")
    wsDst.Range("A1:K1").Font.Bold = True
    outRow = 2
    
    ' 削除対象行リスト
    Set delRows = New Collection
    
    ' 重複チェック（全組み合わせ）
    For i = 2 To lastRow - 1
        key1 = wsSrc.Cells(i, 2).Value & "|" & _
               wsSrc.Cells(i, 3).Value & "|" & _
               wsSrc.Cells(i, 4).Value & "|" & _
               wsSrc.Cells(i, 5).Value
        For j = i + 1 To lastRow
            key2 = wsSrc.Cells(j, 2).Value & "|" & _
                   wsSrc.Cells(j, 3).Value & "|" & _
                   wsSrc.Cells(j, 4).Value & "|" & _
                   wsSrc.Cells(j, 5).Value
            If key1 = key2 Then
                ' ペアで出力
                wsDst.Cells(outRow, 1).Resize(1, 5).Value = wsSrc.Cells(i, 1).Resize(1, 5).Value
                wsDst.Cells(outRow, 7).Resize(1, 5).Value = wsSrc.Cells(j, 1).Resize(1, 5).Value
                outRow = outRow + 1
                
                ' 後の方のデータ(j行)を削除対象に追加
                On Error Resume Next
                delRows.Add j, CStr(j)
                On Error GoTo 0
            End If
        Next j
    Next i
    
    MsgBox "重複チェックが完了しました。", vbInformation
    
    ' 削除対象があれば確認
    If delRows.Count > 0 Then
        ans = MsgBox("重複データを元のリストから削除しますか？", vbYesNo + vbQuestion)
        If ans = vbYes Then
            ' 後ろから削除
            For i = delRows.Count To 1 Step -1
                wsSrc.Rows(delRows(i)).Delete
            Next i
            MsgBox "重複データを削除しました。", vbInformation
        Else
            MsgBox "削除せずに終了しました。", vbInformation
        End If
    Else
        MsgBox "重複データはありませんでした。", vbInformation
    End If
End Sub


■■■■p89プロンプト例

重複データのうち、一部削除されないものがありました。修正してください。

＃＃リストアップされた重複データ
顧客ID	名前	都道府県	住所	電話番号		顧客ID	名前	都道府県	住所	電話番号
A002	中村葵	東京都	大田区大森北X-XX	070-6024-xxxx		A009	中村葵	東京都	大田区大森北X-XX	070-6024-xxxx
A005	山田次郎	千葉県	柏市柏X-XX	090-8104-xxxx		A018	山田次郎	千葉県	柏市柏X-XX	090-8104-xxxx
A027	前田誠一	東京都	世田谷区中町X-X	090-5640-xxxx		A041	前田誠一	東京都	世田谷区中町X-X	090-5640-xxxx
A028	秋山和孝	東京都	板橋区本町X-X	070-3132-xxxx		A039	秋山和孝	東京都	板橋区本町X-X	070-3132-xxxx

＃＃削除されなかったデータ
A041	前田誠一	東京都	世田谷区中町X-X	090-5640-xxxx


■■■■p90コード例

Sub 重複チェック()
    Dim wsSrc As Worksheet, wsDst As Worksheet
    Dim lastRow As Long, i As Long, outRow As Long
    Dim dict As Object, delDict As Object
    Dim key As String, firstRow As Long
    Dim ans As VbMsgBoxResult
    Dim calcMode As Long
    
    ' --- 初期チェック ---
    Set wsSrc = ActiveSheet
    If wsSrc.ProtectContents Then
        MsgBox "実行中のシートは保護されています。保護を解除してから実行してください。", vbExclamation
        Exit Sub
    End If
    
    lastRow = wsSrc.Cells(wsSrc.Rows.Count, "A").End(xlUp).Row
    If lastRow < 2 Then
        MsgBox "データがありません。", vbExclamation
        Exit Sub
    End If
    
    ' --- パフォーマンス設定保存 ---
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    calcMode = Application.Calculation
    Application.Calculation = xlCalculationManual
    
    ' --- 重複出力シート作成（既存なら削除） ---
    On Error Resume Next
    Application.DisplayAlerts = False
    ThisWorkbook.Worksheets("重複データ").Delete
    Application.DisplayAlerts = True
    On Error GoTo 0
    Set wsDst = ThisWorkbook.Worksheets.Add(After:=wsSrc)
    wsDst.Name = "重複データ"
    wsDst.Range("A1:E1").Value = Array("顧客ID", "名前", "都道府県", "住所", "電話番号")
    wsDst.Range("G1:K1").Value = Array("顧客ID", "名前", "都道府県", "住所", "電話番号")
    wsDst.Range("A1:K1").Font.Bold = True
    outRow = 2
    
    ' --- 辞書／削除候補リスト ---
    Set dict = CreateObject("Scripting.Dictionary")
    Set delDict = CreateObject("Scripting.Dictionary")
    
    ' --- 重複判定ループ（正規化して比較） ---
    For i = 2 To lastRow
        Dim nm As String, pref As String, addr As String, tel As String
        nm = NormalizeText(wsSrc.Cells(i, 2).Value)
        pref = NormalizeText(wsSrc.Cells(i, 3).Value)
        addr = NormalizeText(wsSrc.Cells(i, 4).Value)
        tel = NormalizePhone(wsSrc.Cells(i, 5).Value)
        
        key = nm & "|" & pref & "|" & addr & "|" & tel
        If dict.Exists(key) Then
            firstRow = dict(key)
            ' ペアを出力（左：先出、右：重複）
            wsDst.Cells(outRow, 1).Resize(1, 5).Value = wsSrc.Cells(firstRow, 1).Resize(1, 5).Value
            wsDst.Cells(outRow, 7).Resize(1, 5).Value = wsSrc.Cells(i, 1).Resize(1, 5).Value
            outRow = outRow + 1
            ' 削除候補に追加（キーは文字列で一意化）
            If Not delDict.Exists(CStr(i)) Then delDict.Add CStr(i), i
        Else
            dict.Add key, i
        End If
    Next i
    
    MsgBox "重複チェックが完了しました。重複ペアは「重複データ」シートに出力されました。", vbInformation
    
    ' --- 削除確認 ---
    If delDict.Count = 0 Then
        MsgBox "削除対象の重複データは見つかりませんでした。", vbInformation
        GoTo CleanUp
    End If
    
    ans = MsgBox("重複データ " & delDict.Count & " 件を元のリストから削除しますか？" & vbCrLf & "（はい：削除する、いいえ：削除しない）", vbYesNo + vbQuestion, "削除確認")
    If ans <> vbYes Then
        MsgBox "削除は行われませんでした。", vbInformation
        GoTo CleanUp
    End If
    
    ' --- 削除（降順で確実に） ---
    Dim arr() As Long, idx As Long, k As Variant
    ReDim arr(1 To delDict.Count)
    idx = 0
    For Each k In delDict.Keys
        idx = idx + 1
        arr(idx) = delDict(k)
    Next k
    
    ' ArrayList を使ってソート（降順）
    Dim al As Object
    Set al = CreateObject("System.Collections.ArrayList")
    For idx = LBound(arr) To UBound(arr)
        al.Add arr(idx)
    Next
    al.Sort
    al.Reverse
    
    ' 削除実行（失敗行を収集）
    Dim failed As Collection: Set failed = New Collection
    Dim val As Variant
    For Each val In al
        On Error Resume Next
        wsSrc.Rows(val).Delete
        If Err.Number <> 0 Then
            failed.Add val
            Err.Clear
        End If
        On Error GoTo 0
    Next val
    
    If failed.Count = 0 Then
        MsgBox "削除が完了しました。", vbInformation
    Else
        Dim msg As String: msg = "一部の行の削除に失敗しました。シート保護やテーブル（ListObject）が原因の可能性があります。失敗行番号：" & vbCrLf
        For Each k In failed
            msg = msg & k & ", "
        Next
        msg = Left(msg, Len(msg) - 2)
        MsgBox msg, vbExclamation
    End If

CleanUp:
    ' --- 復元 ---
    Application.Calculation = calcMode
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

' ====== ヘルパー関数 ======
' 文字列正規化（前後空白除去・全角→半角・複数空白除去・大文字化）
Private Function NormalizeText(v As Variant) As String
    Dim s As String
    s = CStr(v)
    s = Replace(s, Chr(12288), " ")                 ' 全角スペースを半角に
    s = StrConv(s, vbNarrow)                         ' 全角→半角
    On Error Resume Next
    s = Application.WorksheetFunction.Trim(s)        ' 連続スペースを1つに
    On Error GoTo 0
    s = Trim(s)
    NormalizeText = UCase(s)                         ' 大文字化して比較を安定化
End Function

' 電話番号正規化（数字のみ抽出）
Private Function NormalizePhone(v As Variant) As String
    Dim s As String, ch As String, i As Long, outS As String
    s = CStr(v)
    s = Replace(s, Chr(12288), "")   ' 全角スペース除去
    s = StrConv(s, vbNarrow)
    outS = ""
    For i = 1 To Len(s)
        ch = Mid$(s, i, 1)
        If ch >= "0" And ch <= "9" Then outS = outS & ch
    Next i
    NormalizePhone = outS
End Function
