我想在Excel VBA中编写一个代码,以比较3个命名范围(例如,“ Peter”,“ Paul”和“ John”)中相应单元格中的值,如果所有三个值均> = 3,则在第四个命名范围“ James”中,相应单元的内部颜色更改为绿色。我使用offset编写了代码,但是如果我在“ Peter”,“ Paul”和“ John”之间插入新列,则代码将无法正常工作。请您帮我编写一个使用命名范围的代码,以避免在添加新列时出错?谢谢。
If Cell.Value >= 3 Then
If Cell.Offset(0, 1).Value >= 3 Then
If Cell.Offset(0, 2).Value >= 3 Then
If Cell.Offset(0, 3).Value >= 3 Then
Cell.Offset(0, 4).Interior.ColorIndex = 4
End If
End If
End If
End If
Next Cell
尝试一下
Dim xCel as Range, rPtr as Long
rPtr = 0
For Each xCel In Range("Peter").Cells
rPtr = rPtr + 1
If xCel.Value >= 3 Then
If Range("Paul").Cells(rPtr, 1).Value >= 3 Then
If Range("John").Cells(rPtr, 1).Value >= 3 Then
Range("James").Cells(rPtr,1).Interior.ColorIndex = 34
End If
End If
End If
Next xCel
' Done
这解决了您提到的问题,但仍假定所有范围都是相同的长度和单个列