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

我正在尝试在工作簿中放两张纸,并突出显示与Sheet1不同的Sheet2中的单元格。 这些表可以从less数行到数百行。 我会很乐意回答任何问题,我从来没有使用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 

感谢您的任何帮助!

在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