快速提问,下面是比较程序的代码片段,它检查两个工作表以查找不匹配的数据。我想突出显示或格式化sheet4上的不匹配单元格,但我遇到了语法或逻辑问题。任何指导都将不胜感激。
Option Explicit
Sub compare2WorkSheets()
Dim varSheetA As Variant, varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long, iCol As Long
strRangeToCheck = "A1:AB17000"
Debug.Print Now
varSheetA = Worksheets("Sheet3").Range(strRangeToCheck)
varSheetB = Worksheets("Sheet4").Range(strRangeToCheck)
Debug.Print Now
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
' matching cells no format
Else
' mismatch found,format the Sheet4 cells to yellow
varSheetB(iRow, iCol).Interior.Color = vbYellow '...referencing syntax trouble
End If
Next iCol
Next iRow
End Sub
答案 0 :(得分:1)
另一种方法:
Sub CompareRanges()
Dim rngA As Range, rngB As Range, arr, r As Long, c As Long
Set rngA = Range("A1:D4")
Set rngB = Range("A6:D9")
'will be evaluated as an array formula
arr = ActiveSheet.Evaluate("=IF(" & rngA.Address & "=" & rngB.Address & ",1,0)")
For r = LBound(arr, 1) To UBound(arr, 1)
For c = LBound(arr, 2) To UBound(arr, 2)
If Not IsError(arr(r, c)) Then
rngA(r, c).Interior.Color = IIf(arr(r, c) = 0, vbYellow, vbWhite)
End If
Next c
Next r
End Sub
答案 1 :(得分:0)
这是我在尝试查找和突出显示不匹配时通常使用的不同方法。这应该具有您正在寻找的功能。
Option Explicit
Sub Compare2worksheets()
Dim iCol, iRow As Integer
For iCol = 1 To 27
For iRow = 1 To 17000
If Worksheets("Sheet3").Cells(iRow, iCol) = Worksheets("Sheet4").Cells(iRow, iCol) Then
'Do Nothing
Else
Worksheets("Sheet4").Cells(iRow, iCol).Interior.Color = vbYellow
End If
Next iRow
Next iCol
End Sub