使用Excel中的VBA比较两个电子表格中的行(以及这些行中的单元格),突出显示差异

时间:2016-09-23 15:24:09

标签: excel vba excel-vba

我正在尝试在工作簿中取两张纸并突出显示Sheet2中与Sheet1不同的单元格。这些纸张可以从少量行到数百行。我很乐意回答任何问题,我之前从未使用过VBA,但我有其他语言的经验。

它需要通过Sheet2的行,然后是当前行中的单元格。获取行中的第一个单元格,查看该单元格的内容是否存在于Sheet1中,如果该单元格的内容不存在,则将整行突出显示为新条目。如果内容确实出现在Sheet1中,请浏览每个工作表中显示的条目行的每个单元格,并仅在Sheet2上突出显示更改。

到目前为止我所知道的一切:

Sub DetectChanges()
Rem compares two sheets by row. let sheet1 be the old one and sheet2 be the new one.
Rem *hopefully* highlights any differences. Make column1 unique identifiers
Dim ws1, ws2 As Worksheet
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
For Each rw In ws2.Rows

' check identifier for active row & detect changes
Next

End Sub

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

在OP的澄清之后

编辑

这个(评论过的)代码可以让你以正确的方式:

Option Explicit

Sub DetectChanges()
    Dim ws1 As Worksheet, ws2 As Worksheet '<-- explicitly declare each variable type
    Dim ws1Data As Range, f As Range, cell As Range
    Dim icol As Long

    Set ws1Data = Worksheets("Sheet01").Columns(1).SpecialCells(xlCellTypeConstants) '<-- set a range with Sheet1 cells containing data

    With Worksheets("Sheet02") '<--| reference Sheet2
        For Each cell In Intersect(.UsedRange, .Columns(1)).SpecialCells(xlCellTypeConstants) '<-_| loop through its column "A" non blank cells
            Set f = ws1Data.Find(what:=cell.value, LookIn:=xlValues, LookAt:=xlWhole) '<--| search for current cell value in Sheet1 data
            If f Is Nothing Then '<--| if not found then...
                Intersect(cell.EntireRow, .UsedRange).Interior.ColorIndex = 3 '<--| highlight current cell entire row
            Else
                For icol = 1 To .Range(cell, .Cells(cell.Row, .Columns.Count).End(xlToLeft)).Columns.Count - 1 '<--| loop through Sheet2 current cell row
                    If f.Offset(, icol) <> cell.Offset(, icol) Then '<--| if it doesn't match corresponding cell in Sheet1
                        cell.Offset(, icol).Interior.ColorIndex = 3 '<--| highlight Sheet2 not-matching cell
                        f.Offset(, icol).Interior.ColorIndex = 3 '<--| highlight Sheet1 not-matching cell
                    End If
                Next icol
            End If
        Next cell
    End With
End Sub