ray88’s diary

お仕事で困ったとき用の自分用の覚書

値一致チェック

■列1の値と列2の値を比較し、列2の中で列1にない値のセルの背景に色を付ける
f:id:ray88:20200202223327p:plain
f:id:ray88:20200202223345p:plain

Sub funcCheckValue(targetColumn1 As Integer, targetColumn2 As Integer, startRow As Integer)
 '-------------------------------------------------------------------------------
 '機能:列1と列2を比較し、列2の中で列1の中にない値に対してセルの背景に色をつける
 '引数1:列1の列
 '引数2:列2の列
 '引数3:値を比較する列の先頭行
 '-----------------------------------------------
     Dim i As Long
     Dim j As Long
     Dim lastRow1 As Long
     Dim lastRow2 As Long
     Dim Hantei As Boolean
     
     '列1の最終行を取得
     lastRow1 = Cells(Rows.Count, targetColumn1).End(xlUp).Row
     '列2の最終行を取得
     lastRow2 = Cells(Rows.Count, targetColumn2).End(xlUp).Row     
     '判定フラグの初期化
     Hantei = False     
     For i = startRow To lastRow2
        For j = startRow To lastRow1
            If Cells(i, targetColumn2) = Cells(j, targetColumn1) Then
                '変数にTrueを格納
                Hantei = True
                Exit For
            End If
        Next j        
        If Hantei Then
            Hantei = False
        Else
            'セルの背景色を変える
            Cells(i, targetColumn2).Interior.ColorIndex = 6
        End If
    Next i    
 End Sub

■上記プロシージャの呼び出し元プロシージャ

Sub test()
    Dim strPath As String
    Dim wb As Workbook
    Dim sheetName As String    
    '対象ブックのパスを設定
    strPath = "C:\Users\デスクトップ\テスト\顧客データ.xlsx"
    '対象シート名を設定
    sheetName = "顧客データ"    
    Set wb = Workbooks.Open(strPath)
    wb.Sheets(sheetName).Activate    
    '呼び出し先プロシージャに引数を渡す
    Call funcCheckValue(2, 4, 3)    
    wb.Save
    wb.Close
End Sub