VBA循环根据标准定位某些细胞
我目前正在试图实现一个macros,它通过列D循环,并根据它的价值,我希望它在该特定的行上存在的值的某些多个单元格中的颜色。 这需要发生每一行,它符合一定的标准,但我只能似乎得到它的工作,当活动单元格被选中,而不是一个自动化的过程。 这是我迄今为止:
Sub Validate() Dim rng As Range Dim row As Range Dim cell As Range Set rng = Range("D4:D1000") For Each cell In rng If cell.Value = "Building Blocks" Then ActiveCell.Offset(, 16).Interior.ColorIndex = 7 ElseIf cell.Value = "Test" Then cell.Interior.ColorIndex = 4 End If Next End Sub
任何帮助,将不胜感激。
我不想为你重写你的代码,所以我只是对你做了一些改变:
Sub Validate() Dim rng As Range Dim row As Range Dim cell As Range Dim counter As Long Set rng = Range("D4:D1000") Range("D4").Select For Each cell In rng If cell.Value = "Building Blocks" Then ActiveCell.Offset(counter, 16).Interior.ColorIndex = 7 ElseIf cell.Value = "Test" Then ActiveCell.Offset(counter, 16).Interior.ColorIndex = 4 End If counter = counter + 1 Next End Sub
一个更好的方法,如3-14159265358979323846所指出的,只需要把你原来的代码和Activecell更改为单元格:
Sub Validate()
Dim rng As Range Dim row As Range Dim cell As Range Set rng = Range("D4:D1000") For Each cell In rng If cell.Value = "Building Blocks" Then cell.Offset(, 16).Interior.ColorIndex = 7 ElseIf cell.Value = "Test" Then cell.Offset(, 16).Interior.ColorIndex = 4 End If Next End Sub
您在以下行中引用ActiveCell
…
ActiveCell.Offset(, 16).Interior.ColorIndex = 7
你真正想要的是…
cell.Offset(, 16).Interior.ColorIndex =7
不知道我明白。 这将通过D列,如果它findBuilding Blocks,它将查找该行,为第二个Building Blocks。 如果find它,它将使用colorindex 7将单元格着色。与find相同的想法。 没有testing。
Sub Validate() Dim rng As Range Dim row As Range Dim cell As Range Set rng = Range("D4:D1000") For Each cell In rng If cell.Value = "Building Blocks" Then for i = 2 to 50 'Howverlong your row is, could go to the end too if dynamic if cell(,i).value = cell.value then cell(,i).Interior.ColorIndex = 7 next ElseIf cell.Value = "Test" Then for i = 2 to 50 'Howverlong your row is, could go to the end too if dynamic if cell(,i).value = cell.value then cell(,i).Interior.ColorIndex = 4 next End If Next End Sub