使用宏比较2个excel文件

时间:2016-08-11 12:04:19

标签: excel vba excel-vba macros compare

我只是想知道是否有任何方法可以使用宏来比较两个excels电子表格。我有一块宏基本上可以完成工作,但它逐列检查。因此,如果我在A(1,1)中的sheet1中定义了值,并且A(1,1)中的sheet2中没有相同的值,但该值存在于'compare Sheet Sub CompareTable() Dim tem, tem1 As String Dim text1, text2 As String Dim i As Integer, hang1 As Long, hang2 As Long, lie As Long, maxhang As Long, maxlie As Long Sheets("Sheet1").Select Columns("A:A").Select With Selection.Interior .Pattern = xlNone .TintAndShade = 0 .PatternTintAndShade = 0 End With Range("A1").Select Sheets("Sheet2").Select Dim lastRow As Long With ActiveSheet lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row End With Rows("1:" & lastRow).Select With Selection.Interior .Pattern = xlNone .TintAndShade = 0 .PatternTintAndShade = 0 End With Range("A1").Select maxhang = lastRow ' number of the last row containg data MaxRow = lastRow Dim LastCol As Integer With ActiveSheet LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column End With MaxColumn = LastCol For col = 1 To MaxColumn For hang1 = 2 To maxhang Dim a As Integer a = 0 tem = Sheets(1).Cells(hang1, col) For hang2 = 1 To maxhang tem1 = Sheets(2).Cells(hang2, col) If tem1 = tem Then a = 1 Sheets(2).Cells(hang2, col).Interior.ColorIndex = 6 For lie = 1 To maxlie text1 = Sheets(1).Cells(hang1, lie) text2 = Sheets(2).Cells(hang2, lie) If text1 <> text2 Then Sheets(2).Cells(hang2, lie).Interior.ColorIndex = 8 End If Next End If Next If a = 0 Then Sheets(1).Cells(hang1, 1).Interior.ColorIndex = 5 End If Next Next End Sub 的任何一行中专栏然后它不会提出投诉。

Group.1 T0   T1   T2   T3   T4   T5   T6
1       0.52 0.64 0.65 0.54 0.87 0.65 0.73
2       0.87 0.54 0.65 0.60 0.87 0.65 0.87
3       0.97 0.48 0.65 0.60 0.87 0.36 0.88 
4       0.45 0.67 0.66 0.87 0.87 0.51 0.98
5       0.70 0.99 0.84 0.88 0.87 0.54 0.98
6       0.77 0.80 0.87 NaN  NaN  NaN  1.00

注意:我正在寻找可以给我一个行匹配的任何解决方案,所以如果给定行的任何值与sheet2不匹配,那么它应该突出显示它。< / p>

我也可以选择其他任何替代方案。任何帮助或建议将不胜感激。

感谢您的时间!

1 个答案:

答案 0 :(得分:1)

我不确定这是否是你所期待的。请参阅我的以下代码

Sub CompareTable()

    Dim ws1 As Worksheet
    Dim ws2 As Worksheet

    Dim table1 As Range
    Dim table2 As Range

    Dim table1Rows As Integer
    Dim table1Cols As Integer

    Set ws1 = Worksheets("sheet1")
    Set ws2 = Worksheets("sheet2")
    Set table1 = ws1.Cells
    Set table2 = ws2.Cells

    table1Rows = ws1.UsedRange.Rows.Count
    table1Cols = ws1.UsedRange.Columns.Count

    For i = 1 To table1Rows
        For j = 1 To table1Cols
            If table1(i, j).Value = table2(i, j).Value Then
            Else
            ws1.Cells(i, j).Interior.Color = vbYellow
            End If

        Next

    Next

End Sub

Sheet1表 enter image description here Sheet2表 enter image description here

运行代码后tgisis我的结果

enter image description here