Option Explicit
Public Sub 商品比較()
Dim sh1 As Worksheet 'Sheet1
Dim sh2 As Worksheet 'Sheet2
Dim sh3 As Worksheet '比較
Dim dic1 As Object 'Sheet1の商品
Dim dic2 As Object 'Sheet2の商品
Dim maxrow1 As Long 'Sheet1の最大行
Dim maxrow2 As Long 'Sheet2の最大行
Dim row1 As Long 'Sheet1の行カウンター
Dim row2 As Long 'Sheet2の行カウンター
Dim row3 As Long: row3 = 2 '比較シートの行カウンター
Dim key As Variant 'キー(商品)
Set dic1 = CreateObject("Scripting.Dictionary") ' 連想配列の定義
Set dic2 = CreateObject("Scripting.Dictionary") ' 連想配列の定義
Set sh1 = Worksheets("Sheet1")
Set sh2 = Worksheets("Sheet2")
Set sh3 = Worksheets("比較")
maxrow1 = sh1.Cells(Rows.Count, "A").End(xlUp).Row 'sheet1 最終行を求める
maxrow2 = sh2.Cells(Rows.Count, "A").End(xlUp).Row 'sheet2 最終行を求める
'比較シートの2行目以降をクリア
sh3.Rows("2:" & Rows.Count).ClearContents
With Sheets("sheet1").Range("a1").CurrentRegion.Offset(1, 0)
.Resize(.Rows.Count - 1).Copy Sheets("比較").Range("a2")
End With
'Sheet2の商品をdic2へ登録
For row2 = 2 To maxrow2
key = sh2.Cells(row2, "A").Value
dic2(key) = row2
Next
'Sheet1の商品がSheet2にあるかチェックする
For row1 = 2 To maxrow1
key = sh1.Cells(row1, "A").Value
If dic2.exists(key) = True Then
'Sheet1の商品がSheet2に存在する場合
sh3.Cells(row3, "D").Resize(, 3).Value = sh1.Cells(row1, "A").Resize(, 3).Value
row3 = row3 + 1
dic2.Remove (key) 'dic2から該当キーを削除
Else
dic1(key) = row1
End If
Next
row3 = row3 + 3
'Sheet1にありSheet2にない商品を出力する
For Each key In dic1.keys
row1 = dic1(key)
sh3.Cells(row3, "D").Resize(, 3).Value = sh1.Cells(row1, "A").Resize(, 3).Value
row3 = row3 + 1
Next
'Sheet2にありSheet1にない商品を出力する
For Each key In dic2.keys
row2 = dic2(key)
sh3.Cells(row3, "D").Resize(, 3).Value = sh2.Cells(row2, "A").Resize(, 3).Value
row3 = row3 + 1
Next
MsgBox ("完了")
End Sub