比较两个不同工作表中的两列

时间:2017-07-01 12:14:50

标签: excel excel-vba compare vba

我需要比较不同工作表中的两列。

第一张(有500行)

ColumnA(NUMBER)ColumnB(STRING)ColumnC(NUMBER)ColumnD(NUMBER)ColumnE(NUMBER)ColumnF(NUMBER)

第二张

ColumnA(NUMBER)ColumnB(STRING)ColumnC(NUMBER)ColumnD(NUMBER)ColumnE(NUMBER) 没有ColumnF

我想在sheet3中打印出来自第二张表中不存在于第一张表中的SITESID(COLUMNA)。

Option Explicit
Sub Compare()

Dim Row1Crnt As Long
Dim Row2Crnt As Long
Dim Row3Crnt As Long    
Dim Row1Last As Long
Dim Row2Last As Long    

Dim ValueSheet1
Dim ValueSheet2
Dim duplicate As Boolean    
Dim maxColmn As Long
Dim i
maxColmn = 10  ' number of column to compare
For i = 1 To maxColmn

With Sheets("Sheet1")
     Row1Last = .Cells(Rows.Count, i).End(xlUp).Row
End With

With Sheets("Sheet2")
     Row2Last = .Cells(Rows.Count, i).End(xlUp).Row
End With

Row1Crnt = 2
Row2Crnt = 2
Row3Crnt = 2    
maxColmn = 10

Do While Row2Crnt <= Row2Last

duplicate = False
Row1Crnt = 2

With Sheets("Sheet2")
ValueSheet2 = .Cells(Row2Crnt, i).Value
End With
Do While Row1Crnt <= Row1Last

With Sheets("Sheet1")
 ValueSheet1 = .Cells(Row1Crnt, i).Value
End With

If ValueSheet1 = ValueSheet2 Then
   duplicate = True
Exit Do

End If
Row1Crnt = Row1Crnt + 1
Loop

If duplicate = False Then
With Sheets("Sheet3")
   .Cells(Row3Crnt, i).Value = ValueSheet2
    Row3Crnt = Row3Crnt + 1
  End With

End If

Row2Crnt = Row2Crnt + 1
Loop
Next

End Sub

但是我会这样做 第二张表中第一张表中不存在的所有columnA(SITESID)sheet2和ColumnB(NAMES)

1 个答案:

答案 0 :(得分:0)

最快的'检查存在'是application.match。

sub compare
    dim a as long, arr as variant, chk as variant

    with worksheets("sheet1")
        arr = .range(.cells(2, "A"), .cells(.rows.count, "A").end(xlup)).value2
    end with

    with worksheets("sheet3")
        for a = lbound(arr, 1) to ubound(arr, 1)
            if iserror(application.match(arr(a, 1), worksheets("sheet2").columns("A"), 0)) then
                .cells(.rows.count, "A").end(xlup).offset(1, 0) = arr(a, 1)
            end if
        next a
    end with
end sub