[英]How to compare values of corresponding cells in multiple named column ranges and change interior color in another corresponding cell
I want to write a code in Excel VBA that compares the values in corresponding cells in 3 named ranges (say, "Peter", "Paul" & "John"), and if all three values are >= 3, then the interior color of the corresponding cell in a fourth named range say, "James", is changed to Green.我想在 Excel VBA 中编写一个代码,比较 3 个命名范围(例如“Peter”、“Paul”和“John”)中相应单元格中的值,如果所有三个值都 >= 3,则内部颜色在第四个命名范围内的相应单元格中,例如“James”,更改为绿色。 I wrote the code using offset but the code doesn't work properly if I insert new columns in-between "Peter", "Paul" and "John".
我使用偏移量编写了代码,但如果我在“Peter”、“Paul”和“John”之间插入新列,代码将无法正常工作。 Please can you help me write a code that uses named ranges, to avoid an error when new columns are added?
请您帮我编写一个使用命名范围的代码,以避免在添加新列时出错? Thank you.
谢谢你。
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
This works这有效
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
This solves the problem you mentioned, but it still presumes all ranges are the same length and single column这解决了你提到的问题,但它仍然假定所有范围都是相同的长度和单列
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.