fork download
  1. Option Explicit
  2. Public Sub 商品比較()
  3. Dim sh1 As Worksheet 'Sheet1
  4. Dim sh2 As Worksheet 'Sheet2
  5. Dim sh3 As Worksheet '比較
  6. Dim dic1 As Object 'Sheet1の商品
  7. Dim dic2 As Object 'Sheet2の商品
  8. Dim maxrow1 As Long 'Sheet1の最大行
  9. Dim maxrow2 As Long 'Sheet2の最大行
  10. Dim row1 As Long 'Sheet1の行カウンター
  11. Dim row2 As Long 'Sheet2の行カウンター
  12. Dim row3 As Long: row3 = 2 '比較シートの行カウンター
  13. Dim key As Variant 'キー(商品)
  14. Set dic1 = CreateObject("Scripting.Dictionary") ' 連想配列の定義
  15. Set dic2 = CreateObject("Scripting.Dictionary") ' 連想配列の定義
  16. Set sh1 = Worksheets("Sheet1")
  17. Set sh2 = Worksheets("Sheet2")
  18. Set sh3 = Worksheets("比較")
  19. maxrow1 = sh1.Cells(Rows.Count, "A").End(xlUp).Row 'sheet1 最終行を求める
  20. maxrow2 = sh2.Cells(Rows.Count, "A").End(xlUp).Row 'sheet2 最終行を求める
  21. '比較シートの2行目以降をクリア
  22. sh3.Rows("2:" & Rows.Count).ClearContents
  23. With Sheets("sheet1").Range("a1").CurrentRegion.Offset(1, 0)
  24. .Resize(.Rows.Count - 1).Copy Sheets("比較").Range("a2")
  25. End With
  26. 'Sheet2の商品をdic2へ登録
  27. For row2 = 2 To maxrow2
  28. key = sh2.Cells(row2, "A").Value
  29. dic2(key) = row2
  30. Next
  31. 'Sheet1の商品がSheet2にあるかチェックする
  32. For row1 = 2 To maxrow1
  33. key = sh1.Cells(row1, "A").Value
  34. If dic2.exists(key) = True Then
  35. 'Sheet1の商品がSheet2に存在する場合
  36. sh3.Cells(row3, "D").Resize(, 3).Value = sh1.Cells(row1, "A").Resize(, 3).Value
  37. row3 = row3 + 1
  38. dic2.Remove (key) 'dic2から該当キーを削除
  39. Else
  40. dic1(key) = row1
  41. End If
  42. Next
  43. row3 = row3 + 3
  44. 'Sheet1にありSheet2にない商品を出力する
  45. For Each key In dic1.keys
  46. row1 = dic1(key)
  47. sh3.Cells(row3, "D").Resize(, 3).Value = sh1.Cells(row1, "A").Resize(, 3).Value
  48. row3 = row3 + 1
  49. Next
  50. 'Sheet2にありSheet1にない商品を出力する
  51. For Each key In dic2.keys
  52. row2 = dic2(key)
  53. sh3.Cells(row3, "D").Resize(, 3).Value = sh2.Cells(row2, "A").Resize(, 3).Value
  54. row3 = row3 + 1
  55. Next
  56. MsgBox ("完了")
  57. End Sub
  58.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty