The second half of my code (a loop) needs to highlight cells if they are not equal to another worksheet. I am getting a error on the varSheetB line under the "else" section of the loop. I believe I am using the wrong syntax to tell it to highlight those cells.
This should be an easy fix. Can someone please provide the correct syntax for telling it to highlight the cells under the "else" portion of the loop?
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
' Cells are identical.
' Do nothing
Else
' Cells are different.
' Highlight different cells yellow.
varSheetB.Range.(iRow & iCol).Interior.ColorIndex = 36
End If
Next iCol
Next iRow
End Sub
Edit: Adding the full code.
Option Explicit
Sub Compare()
Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
strRangeToCheck = "A12:G150"
Debug.Print Now
varSheetA = Worksheets("Main").Range(strRangeToCheck)
varSheetB = Worksheets("Discrepancy Compare").Range(strRangeToCheck) ' or whatever your other sheet is.
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
' Cells are identical.
' Do nothing.
Else
' Cells are different.
' Highlight different cells yellow.
varSheetB.Range.(iRow & iCol).Interior.ColorIndex = 36
End If
Next iCol
Next iRow
End Sub
Range is not Range.()
it is Range()
.
But, range will expect a Character string for the column and you are passing a number.
In this instance use Cells() which will allow the use of a number for the column:
varSheetB.Cells(iRow, iCol).Interior.ColorIndex = 36
But you need to ensure the iRow
and iCol
do not start at 0, depending on your setup and how the arrays were filled you may start at 0.
Also, unless you start loading the array from A1 the column and Rows will be off.
Now Tested
Option Explicit
Sub Compare()
Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
strRangeToCheck = "A12:G150"
varSheetA = Worksheets("Main").Range(strRangeToCheck)
varSheetB = Worksheets("Discrepancy Compare").Range(strRangeToCheck) ' or whatever your other sheet is.
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
' Cells are different.
' Highlight different cells yellow.
Worksheets("Discrepancy Compare").Cells(iRow + 11, iCol).Interior.ColorIndex = 36
End If
Next iCol
Next iRow
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.