我相信这应该可以解决问题。我不是专家,但通过艰难的方式学到了一个简单的教训:您与工作表的互动越少,它的工作速度就越快!
Option Explicit 'Is worth using this option, so you remember declaring your variables
Sub SO()
Dim i As Long, j As Long, k As Long
Dim arrRange1 As Variant, arrRange2 As Variant, arrColor As Variant 'Declare arrays
ReDim arrColor(0) 'Initial redim
Dim lastRow As Long 'Only need to use one variable for this, and reassign as needed through the code
Dim sh1 As Worksheet: Set sh1 = ThisWorkbook.Sheets("RandomSheetName 1") 'Declare sheet 1
Dim sh2 As Worksheet: Set sh2 = ThisWorkbook.Sheets("RandomSheetName 2") 'Declare sheet 2
With sh1
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'Get last row from sheet 1 in column "A"
arrRange1 = .Range(.Cells(8, 4), .Cells(lastRow, 4)) 'Get all values from column "D", starting at row 8
End With
With sh2
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'Get last row from sheet 2 in column "A"
arrRange2 = .Range(.Cells(1, 1), .Cells(lastRow, 1)) 'Get all values from column "A", starting at row 1
End With
For i = LBound(arrRange1) To UBound(arrRange1) 'Loop through first sheet values
If arrRange1(i, 1) <> "" Then 'If not empty, then...
For j = LBound(arrRange2) To UBound(arrRange2) 'Loop through second sheet values
If arrRange1(i, 1) = arrRange2(j, 1) Then 'If match, then...
ReDim Preserve arrColor(k) 'Redim (preserve) the colours array
arrColor(k) = i + 7 'Add the value of i in the colours array (note +7, since yours sheet1 values start at row 8, feel free to amend)
k = k + 1 'Increase the counter for the colours array
Exit For 'As per idea from the accepted response, no point to check the whole sheet2 range if duplicate found already
End If
Next j
End If
Next i
Application.ScreenUpdating = False 'It always helps to turn off the screenupdating when working with the sheets
For i = LBound(arrColor) To UBound(arrColor) 'Loop through the colours array
If arrColor(0) = "" Then Exit For 'If the first element is empty, means no matches... exit here.
sh1.Cells(arrColor(i), 4).Interior.ColorIndex = 4 'Colour the cell as needed using the value we previously stored
Next i
Application.ScreenUpdating = True 'And lets not forget to turn it on again
End Sub
PS:请注意,Rows.Count 的计数来自ActiveSheet,而不是来自Sheet1 或Sheet2。您需要充分参考,即:Sheets(1).Rows.Count
所以这个:
lastRow = Sheets(1).Cells(Rows.Count, "A").End(xlUp).Row
应该是
lastRow = Sheets(1).Cells(Sheets(1).Rows.Count, "A").End(xlUp).Row
或
With Sheets(1)
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
希望这会有所帮助!