比较多列VBA EXCEL(嵌套循环)

我有下面的代码,在同一时间比较两个不同的表。

Dim compareRange As Range Dim toCompare As Range Dim rFound As Range Dim cel As Range Set compareRange = Worksheets("sheet2").Range("A1:A" & Lastrow3) Set toCompare = Worksheets("sheet3").Range("A1:A" & Lastrow4) Set rFound = Nothing For Each cel In toCompare Set rFound = compareRange.Find(cel) Z = compareRange.Find(cel).Row If Not rFound Is Nothing Then cel.EntireRow.Interior.Color = vbGreen Set rFound = Nothing End If Next cel 

但是,这只是比较列A的时候,我想同时比较列A的C'd和D,只有当三个匹配时才通过。 工作表具有重复的值,这就是为什么我需要一次比较3个项目,但一些列是相同的。 我必须使用嵌套循环。 任何想法从哪里开始?

我以为我可以做类似的事情

 Set compareRange = Worksheets("sheet2").Range("A1:A, C1:C, D1:D" & Lastrow3) 

但显然我不能

其实你并没有比较你的代码中的其他两列。 尝试下面的代码。

 Sub Demo() Dim compareRange As Range, toCompare As Range Dim lastRow1 As Long, lastRow2 As Long Dim ws1 As Worksheet, ws2 As Worksheet Dim i As Long, j As Long Set ws1 = ThisWorkbook.Worksheets("Sheet2") Set ws2 = ThisWorkbook.Worksheets("Sheet3") lastRow1 = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row lastRow2 = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row Set compareRange = ws1.Range("A1:A" & lastRow1) Set toCompare = ws2.Range("A1:A" & lastRow2) For i = 1 To lastRow2 For j = 1 To lastRow1 If ws2.Cells(i, 1) = ws1.Cells(j, 1) And ws2.Cells(i, 3) = ws1.Cells(j, 3) And ws2.Cells(i, 4) = ws1.Cells(j, 4) Then ws2.Cells(i, 1).Interior.Color = vbGreen Exit For End If Next j Next i End Sub 

如果有什么不清楚,请告诉我。