Вы обращаетесь к неправильному диапазону. То, как вы пытаетесь это сделать, эффективно действует как Offset
по сравнению с Cell
. Лучшим способом написания этого было бы следующее:
Public Sub ChangeColour()
Dim PC As Range, LastRow As Range
Dim ColorIndexValue As Long
Dim cell
' Set your desired range - Should reference Relevant worksheet as well
Set PC = Range("A7:H1000")
' Find last used row in that range - This will help limit the number of loops on a fixed range and speed up execution
Set LastRow = PC.Find(what:="*", _
after:=Cells(PC.Row, PC.Column), _
lookat:=xlWhole, _
LookIn:=xlValues, _
searchorder:=xlByRows, _
searchdirection:=xlPrevious)
If Not LastRow Is Nothing Then
' Resize PC to actual used range instead of working on entire sheet
Set PC = PC.Cells(1).Resize(LastRow.Row, PC.Columns.Count)
' Loop through all cells in range in Column D
For Each cell In PC.Columns("D").Cells
' Set ColorIndexValue variable based on cell value
Select Case cell.Value2
Case "GBBRS", "GBLPL", "GBSOU": ColorIndexValue = 35
Case "FIHNO", "SEGOT": ColorIndexValue = 36
Case "BEANR", "DEBRH": ColorIndexValue = 37
Case "FRLEH": ColorIndexValue = 38
Case "BEZEE", "NLRTM": ColorIndexValue = 40
Case "ZADUR", "ZAELS", "ZAPLZ": ColorIndexValue = 45
Case Else: ColorIndexValue = 0
End Select
' Set cell Color. Skip 0 as assume cell is 0 by default
If ColorIndexValue > 0 Then
' Calculates applicable range from cell and PC context
With Range(cell.Offset(0, PC.Cells(1).Column - cell.Column), cell.Offset(0, PC.Cells(1, PC.Columns.Count).Column - cell.Column))
.Interior.ColorIndex = ColorIndexValue
End With
End If
Next cell
End If
End Sub