Внесите следующие изменения. Это должно работать.
Поскольку вы сравниваете с "_Compare"
листами, вы должны исключить эти листы из l oop.
Измените это: If ws.Name <> "Cover Sheet" Or ws.Name <> "Revision Sheet"
на
If ws.Name <> "Cover Sheet" And ws.Name <> "Revision Sheet" And Not (ws.Name Like "*_Compare")
Изменить Sheets(ws)
на Sheets(ws.Name)
Изменить Sheet(ws + "_Compare")
на Sheets(ws.Name + "_Compare")
Отредактированный код:
Public Sub Differentiate()
Dim ws As Worksheet
Dim wsRow As Integer
Dim wsCol As Integer
Dim i As Integer
Dim j As Integer
Set ws = ActiveSheet
For Each ws In Worksheets
If ws.Name <> "Cover Sheet" And ws.Name <> "Revision Sheet" And Not (ws.Name Like "*_Compare") Then
If InStr(LCase(ws.Name), LCase("Compared")) = 0 Then
With ws.UsedRange
wsRow = .Rows.Count
wsCol = .Columns.Count
End With
For i = 1 To wsRow
For j = 1 To wsCol
If Sheets(ws.Name).Cells(i, j) = Sheets(ws.Name + "_Compare").Cells(i, j) Then
Sheets(ws.Name).Cells(i, j).Interior.ColorIndex = 4 'Green
Sheets(ws.Name + "_Compare").Cells(i, j).Interior.ColorIndex = 4 'Green
Else
Sheets(ws.Name).Cells(i, j).Interior.ColorIndex = 3 'Red
Sheets(ws.Name + "_Compare").Cells(i, j).Interior.ColorIndex = 3 'Red
End If
Next j
Next i
End If
End If
Next ws
End Sub
РЕДАКТИРОВАТЬ : код для проверки наличия или отсутствия листа.
Option Explicit
Function WorksheetExists(ByVal WorksheetName As String) As Boolean
Dim Sht As Worksheet
For Each Sht In ThisWorkbook.Worksheets
If Application.Proper(Sht.Name) = Application.Proper(WorksheetName) Then
WorksheetExists = True
Exit Function
End If
Next Sht
WorksheetExists = False
End Function
Затем вызовите вышеуказанную функцию следующим образом:
MsgBox WorksheetExists("Sheet1_Compare")