簡體   English   中英

Excel-VBA:循環突出顯示單元格

[英]Excel-VBA: Loop to highlight cells

我的代碼的后半部分(循環)如果不等於另一個工作表,則需要突出顯示單元格。 在循環的“ 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

Range不是Range.() ,而是Range()

但是,范圍將為該列期望一個字符串,並且您要傳遞一個數字。

在這種情況下,請使用Cells(),這將允許為該列使用數字:

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

但是您需要確保iRowiCol不會從0開始,這取決於您的設置和數組填充的方式,您可能會從0開始。

另外,除非您從A1開始加載陣列,否則列和行將關閉。

現在經過測試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM