如果第一个单元格的内容为真,则比较两个不同工作表中的行内容

时间:2014-10-08 16:37:26

标签: excel vba excel-vba

我要做的是编写一个宏来比较sheet1和sheet2中的行并突出显示差异。你可以在下面看到宏。

我的问题是,如果在第一张表中添加或删除了一行或更多行,则所有其他行向上/向下移动,这导致在第二张表中标记了大量单元格。

由于我在列AI中有一个标识符,尝试实现一个额外的行,它首先在表1中查找相同的标识符,一旦找到,比较表1和表2的行,它们具有相同的标识符,然后标记潜在的差异。

由于我的所有想法到目前为止都失败了,或者文件很慢,我希望你能帮助我。 非常感谢你!

Sub comparing()
Dim sh1 As Worksheet, sh2 As Worksheet
Dim rCount As Long, cCount As Long
Set sh1 = Worksheets(ActiveWorkbook.Worksheets.Count() - 1)
Set sh2 = Worksheets(ActiveWorkbook.Worksheets.Count)
rCount = sh1.Cells(Rows.Count, 1).End(xlUp).Row
cCount = sh1.Cells(1, Columns.Count).End(xlToLeft).Column
Dim r As Long, c As Integer
For r = 1 To rCount
    For c = 1 To cCount
        If sh1.Cells(r, c) <> sh2.Cells(r, c) Then
           sh2.Cells(r, c).Interior.ColorIndex = 6
        End If
    Next c
Next r
Worksheets(Worksheets.Count).Select

End Sub

1 个答案:

答案 0 :(得分:0)

我还没有对此进行全面测试,但您可以使用第一个for循环中的工作表函数match在第二个工作表中找到相应的行:

Sub comparing()
    Dim sh1 As Worksheet, sh2 As Worksheet
    Dim rCount As Long, cCount As Long
    Set sh1 = Worksheets(ActiveWorkbook.Worksheets.Count() - 1)
    Set sh2 = Worksheets(ActiveWorkbook.Worksheets.Count)
    rCount = sh1.Cells(Rows.Count, 1).End(xlUp).row
    cCount = sh1.Cells(1, Columns.Count).End(xlToLeft).Column
    Dim r As Long, c As Integer, sh2Row As Long
    For r = 1 To rCount
        'Find the matching row in Sheet2 by using the value in Column A from both sheets
        sh2Row = Application.WorksheetFunction.Match(sh1.Cells(r, 1).Value, sh2.Range("A:A"))
        For c = 1 To cCount
            If sh1.Cells(r, c) <> sh2.Cells(sh2Row, c) Then
               sh2.Cells(sh2Row, c).Interior.ColorIndex = 6
            End If
        Next c
    Next r
    Worksheets(Worksheets.Count).Select
End Sub