Excel-VBA:循环以突出显示单元格

时间:2018-05-14 19:03:25

标签: excel excel-vba vba

我的代码的后半部分(循环)需要突出显示单元格,如果它们不等于另一个工作表。我在" else"下的varSheetB行上收到错误循环的一部分。我相信我使用错误的语法告诉它突出显示那些单元格。

这应该是一个简单的解决方案。有人可以提供正确的语法,告诉它突出显示"否则"循环的一部分?

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

编辑:添加完整代码。

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

3 个答案:

答案 0 :(得分:1)

范围不是Range.() Range()

但是,range会期望列的字符串,并且您传递的是数字。

在这种情况下,使用Cells(),它允许使用列的数字:

varSheetB.Cells(iRow, iCol).Interior.ColorIndex = 36

但您需要确保iRowiCol不从0开始,具体取决于您的设置以及阵列的填充方式,您可以从0开始。

此外,除非您开始从A1加载数组,否则列将关闭。

答案 1 :(得分:1)

现在已经过测试

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

答案 2 :(得分:0)

这应该有效:

varSheetB.Cells(iRow, iCol).Interior.ColorIndex = 36

如果你想保持范围,那么:

wrksheet.Range().Interior.Color = 75