0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AグループとBグループにあるものとないものを可視化

Posted at

動機

AにあってBにないもの、BにあってAにないものを可視化したい

Aグループ Bグループ
いちご いちご
みかん みかん
りんご なし
めろん りんご
もも めろん
すいか とうもろこし
とうもろこし なす

よくするのは

各列をソート

Aグループ Bグループ
いちご いちご
すいか とうもろこし
とうもろこし なし
なす なす
みかん みかん
めろん めろん
もも りんご

おなじものが、同じ行になるように、セルを挿入する

Aグループ Bグループ
いちご いちご
すいか
とうもろこし とうもろこし
なし
なす なす
みかん みかん
めろん めろん
もも

うーん

マクロつくってみた

A列を選択して、マクロ実行
B列を選択
出力先を選択

重複を避けて項目を並び替えて、AとBそれぞれにあり(1)なし(0)を示してくれる

くだもの A B
いちご 1 1
すいか 1 0
とうもろこし 1 1
なし 0 1
なす 1 1
みかん 1 1
めろん 1 1
もも 1 0

タイトル行は出力されません


Sub Diff2Lines()
    Dim range1 As Range, range2 As Range, rangeDiff As Range

    Set range1 = Selection
    If range1.columns.Count > 1 Then
        MsgBox "2列以上は選択できません"
        Exit Sub
    End If

    Set range2 = Application.InputBox(prompt:="", title:="2列目を指定する", Type:=8)
    If range2.columns.Count > 1 Then
        MsgBox "2列以上は選択できません"
        Exit Sub
    End If

    Set rangeDiff = Application.InputBox(prompt:="", title:="出力先を指定する", Type:=8)

    If WorksheetFunction.CountA(rangeDiff.Resize(range1.Rows.Count + range2.Rows.Count, 3)) <> 0 Then
        MsgBox "比較結果出力先が空欄でありません"
        Exit Sub
    End If

    Dim r(1 To 2) As Variant
    r(1) = range1
    r(2) = range2

    Dim dic(1 To 2) As Object, dicDiff As Object
    Set dic(1) = CreateObject("Scripting.Dictionary")
    Set dic(2) = CreateObject("Scripting.Dictionary")
    Set dicDiff = CreateObject("Scripting.Dictionary")

    Dim i As Long
    Dim c As Long
    Dim v As String
    For c = 1 To 2
      For i = 1 To UBound(r(c))
          v = r(c)(i, 1)
          If Not dicDiff.Exists(v) Then
              dicDiff.Add v, v
          End If
          If Not dic(c).Exists(v) Then
            dic(c).Add v, v
          End If
      Next
    Next

    Dim allKeys As Variant  '
    allKeys = dicDiff.Keys

    Dim diffArrayList As Object
    Set diffArrayList = CreateObject("System.Collections.ArrayList")

    For i = 0 To UBound(allKeys)
        diffArrayList.Add (allKeys(i))
    Next
    diffArrayList.Sort

    Dim outValue As Variant
    outValue = rangeDiff.Resize(UBound(allKeys) + 1, 3)
    For i = 0 To UBound(allKeys)
        outValue(i + 1, 1) = diffArrayList(i)
        outValue(i + 1, 2) = IIf(dic(1).Exists(diffArrayList(i)), 1, 0)
        outValue(i + 1, 3) = IIf(dic(2).Exists(diffArrayList(i)), 1, 0)
    Next
    rangeDiff.Resize(UBound(allKeys) + 1, 3) = outValue
End Sub

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?