我正在尝试在工作簿中获取两张工作表并突出显示 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
感谢您的任何帮助!
最佳答案
已编辑 在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
关于vba - 在 Excel 中使用 VBA 比较两个电子表格中的行(以及这些行中的单元格),突出显示差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39664381/