LoginSignup
2
1

More than 1 year has passed since last update.

VBAで差分比較ツールを作ってみた

Posted at

Excelのシートそれぞれのデータで、差分比較をしたい時がある。
一般的にはDiffツールを使うのだが、ルールが厳しくDiff自体が使えない場合もあるらしい。

そこで、差分比較ツールを作ってみた。

差分比較ツール

まず、今回は「同じブック内の別シートで差分比較をする」やり方で書いたが、
これをアレンジすれば別ブック内の別シートで差分比較をすることも可能だろう。

プログラムの流れ

そして流れとしては

①ブックを取得
②差分比較をしたい元シートを取得
③差分比較をしたい別シートを取得
④差分があったらそれを出力するシートを作成
⑤ ②と③のシート内データを1行ずつ比較していく
⑥差分があれば④で作成したシートに出力していく

という流れで行う。

注意点としては、比較元データを基準に比較先データと比較し、比較元にしかないデータを出すということ。
つまり、比較先/比較元関係なく、AとBシート両方で異なるデータを出力するのはまた別のやり方になる。

その上で、コードを書いていく。

実際のコード

Option Explicit
Public Sub MainProc()
    Dim shtMain As Worksheet
    Dim motoName As String
    Dim sakiName As String
    Dim shtMoto As Worksheet
    Dim shtSaki As Worksheet
    Dim shtSabun As Worksheet
    Dim lastRowMoto As Long
    Dim lastRowSaki As Long
    Dim lastCol As Long
    Dim i As Long
    Dim j As Long
    Dim k As Long
    Dim blnSame As Boolean
    Dim blnExist As Boolean
    Dim nowRow As Long
    
    Set shtMain = ThisWorkbook.Sheets("メイン")
    
    '比較元シート(最終行・最終列取得)
    motoName = shtMain.Range("A3")
    Set shtMoto = ThisWorkbook.Sheets(motoName)
    lastRowMoto = shtMoto.Cells(shtMoto.Rows.Count, 1).End(xlUp).Row
    lastCol = shtMoto.Cells(1, shtMoto.Columns.Count).End(xlToLeft).Column
    
    '比較先シート(最終行取得)
    sakiName = shtMain.Range("B3")
    Set shtSaki = ThisWorkbook.Sheets(sakiName)
    lastRowSaki = shtSaki.Cells(shtSaki.Rows.Count, 1).End(xlUp).Row
    
    '差分シート
    Set shtSabun = ThisWorkbook.Sheets("差分")
    
    '差分シートクリア
    shtSabun.Cells.Clear
    
    '比較元シートのヘッダー行を差分シートにコピー
    shtMoto.Range(shtMoto.Cells(1, 1), shtMoto.Cells(1, lastCol)).Copy (shtSabun.Cells(1, 1))
    
    nowRow = 1
    
    '比較元シートと比較先シートを比較し、差分行を差分シートにコピー
    For i = 2 To lastRowMoto
        blnExist = False
        For j = 2 To lastRowSaki
            blnSame = True
            
            For k = 1 To lastCol
                If shtMoto.Cells(i, k) <> shtSaki.Cells(j, k) Then
                    blnSame = False
                    Exit For
                End If
            Next
            
            If blnSame = True Then
                blnExist = True
                Exit For
            End If
        Next
        
        If blnExist = False Then
            nowRow = nowRow + 1
            shtMoto.Range(shtMoto.Cells(i, 1), shtMoto.Cells(i, lastCol)).Copy (shtSabun.Cells(nowRow, 1))
        End If
    Next
    
    MsgBox "完了"
    
End Sub

本来は変数でもっと良い名前があるとは思うが、比較元と比較先がそれぞれ分かるようにとあえて「Moto」「Saki」とつけておいた。

問題点

今は、比較元シートのデータを基準に比較しているため、仮に比較先シートにしかないデータがあったとしても
それは出てこない。
(比較元シートにしかないデータは出てくる)

それはそれで正しいのだが、比較元比較先関係なく、AとBで異なるデータはどちらも出せるようにというのは今後また考えていきたいと思う。

2
1
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
2
1