我有用于比较第一列的VBA代码,并突出显示sheet2的第一列中的单元格,而不是在sheet1中。
我是VBA的新手,并且不擅长编码部分,需要在具有多个电子表格的Excel工作表中工作(这可能从5到10不等)。 sheet1是主工作表,其他工作表应与主工作表进行比较,并突出显示主工作表中不存在的单元格。
Public Sub CompareSheets()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim cell As Range, rng As Range
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
Set rng = ws1.Range("A1:A20")
For Each cell In rng
Celladdress = cell.Address
If cell <> ws2.Range(Celladdress) Then
cell.Interior.Color = vbYellow
ws2.Range(Celladdress).Interior.Color = vbYellow
End If
Next cell
End Sub
答案 0 :(得分:2)
此代码避免逐行比较(根据您的注释)并查找Sheet2,Sheet3,Sheet4等列A中的每个值,以便在Sheet1的A列中找到。它还可以找到大于Sheet1中值的行总数的行。
这并不会迫使细胞变成vbYellow。相反,它使用条件格式在非匹配单元格上显示vbYellow。这些可以像强制vbYellow单元一样进行过滤。这样做的好处是,一旦一个值得到纠正(与Sheet1匹配!A:A),高亮将自动被删除。
Option Explicit
Sub CompareSheets()
Dim lrw1 As Long, lrwn As Long, w As Long
'get the last row of values in master sheet
With Worksheets(1)
lrw1 = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
'the first worksheet (e.g. worksheets(1) ) is the 'master sheet' so we start at 2
For w = 2 To Worksheets.Count
With Worksheets(w)
lrwn = .Cells(.Rows.Count, "A").End(xlUp).Row
With .Range(.Cells(1, "A"), .Cells(Application.Max(lrwn, lrwn), "A"))
.FormatConditions.Delete
With .FormatConditions.Add(Type:=xlExpression, _
Formula1:="=OR(ROW()>" & lrw1 & ", ISNA(MATCH($A1, " & Worksheets(1).Columns("A").Address(external:=True) & ", 0)))")
With .Interior
.PatternColorIndex = xlAutomatic
.Color = vbYellow
End With
.StopIfTrue = True
End With
End With
End With
Next w
End Sub
FWIW,我发现你的叙述有点令人困惑。它要么与提供的代码相矛盾,要么自相矛盾。这个提议的解决方案背后的逻辑很大程度上来自你的评论。