如何比较多个命名列范围中相应单元格的值并更改另一个相应单元格中的内部颜色
How to compare values of corresponding cells in multiple named column ranges and change interior color in another corresponding cell
我想在 Excel VBA 中编写代码,用于比较 3 个命名范围(例如 "Peter"、"Paul" 和 "John"),并且如果所有三个值都 >= 3,则第四个命名范围 "James" 中相应单元格的内部颜色将更改为绿色。我使用偏移量编写代码,但如果我在 "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
Dim xSht As Worksheet
Set xSht = ActiveSheet
rPtr = 0
For Each xCel In xSht.Range("Peter").Cells
rPtr = rPtr + 1
If xCel.Value >= 3 Then
If xSht.Range("Paul").Cells(rPtr, 1).Value >= 3 Then
If xSht.Range("John").Cells(rPtr, 1).Value >= 3 Then
xSht.Range("James").Cells(rPtr, 1).Interior.ColorIndex = 34
End If
End If
End If
Next xCel
这解决了您提到的问题,但它仍然假设所有范围都是相同的长度和单列
我想在 Excel VBA 中编写代码,用于比较 3 个命名范围(例如 "Peter"、"Paul" 和 "John"),并且如果所有三个值都 >= 3,则第四个命名范围 "James" 中相应单元格的内部颜色将更改为绿色。我使用偏移量编写代码,但如果我在 "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
Dim xSht As Worksheet
Set xSht = ActiveSheet
rPtr = 0
For Each xCel In xSht.Range("Peter").Cells
rPtr = rPtr + 1
If xCel.Value >= 3 Then
If xSht.Range("Paul").Cells(rPtr, 1).Value >= 3 Then
If xSht.Range("John").Cells(rPtr, 1).Value >= 3 Then
xSht.Range("James").Cells(rPtr, 1).Interior.ColorIndex = 34
End If
End If
End If
Next xCel
这解决了您提到的问题,但它仍然假设所有范围都是相同的长度和单列