上下文:我有一系列的单元格,其中有些有相同的内容。我试图遍历单元格,并根据该值找到匹配的次数(最多为7次)采取特定的操作。如果有帮助,我希望根据找到的匹配将某些信息范围移到不同的行。
我所做的:我让它在范围内循环,但问题是它会多次击中相同的范围。
我想要的是:如果可能的话,我想在匹配值结束后继续For循环。
For i = 1 To lastRow
If Cells(i, 4).Value = Cells(i + 1, 4).Value Then 'Checks first and second levels
Debug.Print "First and second levels ["; Cells(i, 4).Address & "," & Cells(i + 1, 4).Address & "]"
If Cells(i, 4).Value = Cells(i + 2, 4).Value Then 'Checks second and third levels
Debug.Print "Second and third levels ["; Cells(i, 4).Address & "," & Cells(i + 2, 4).Address & "]"
If Cells(i, 4).Value = Cells(i + 3, 4).Value Then 'Checks third and fourth levels
Debug.Print "Third and fourth levels ["; Cells(i, 4).Address & "," & Cells(i + 3, 4).Address & "]"
Else
'If Cells(i, 14).Value = "No" Then 'Only first & second level procedures
Debug.Print "Only first and second levels ["; Cells(i, 4).Address & "," & Cells(i + 2, 4).Address & "]"
End If
Else
If Cells(i, 14).Value = "No" Then 'Only first & second level procedures
End If
End If
Else
Debug.Print "No match [" & Cells(i, 4).Address & "," & Cells(i + 1, 4).Address & "]"
End If
Next i
'End With
End Sub这就是当前Debug.Print输出的样子(D8:D11完全匹配):
一级和二级$D$8,$D$9
二级和三级$D$8,$D$10
三级和四级$D$8,$D$11
一级和二级$D$9,$D$10
二级和三级$D$9,$D$11
只有一级和二级$D$9,$D$11
发布于 2018-01-08 18:38:10
好的,修复很简单:根据匹配的值更改i整数值。代码如下
For i = 2 To lastRow
If Cells(i, 4).Value = Cells(i + 1, 4).Value Then 'Checks first and second levels
Debug.Print "First and second levels ["; Cells(i, 4).Address & "," & Cells(i + 1, 4).Address & "]"
If Cells(i, 4).Value = Cells(i + 2, 4).Value Then 'Checks second and third levels
Debug.Print "Second and third levels ["; Cells(i, 4).Address & "," & Cells(i + 2, 4).Address & "]"
If Cells(i, 4).Value = Cells(i + 3, 4).Value Then 'Checks third and fourth levels
Debug.Print "Third and fourth levels ["; Cells(i, 4).Address & "," & Cells(i + 3, 4).Address & "]"
Else
i = i + 2 '<~~~CHANGE
If Cells(i, 14).Value = "No" Then 'Only first & second level procedures
Debug.Print "Only first and second levels ["; Cells(i, 4).Address & "," & Cells(i + 2, 4).Address & "]"
End If
End If
Else
i = i + 1 '<~~~CHANGE
If Cells(i, 14).Value = "No" Then 'Only first & second level procedures
End If
End If
Else
Debug.Print "No match [" & Cells(i, 4).Address & "," & Cells(i + 1, 4).Address & "]"
End If
Next i
End Sub发布于 2018-01-08 18:55:19
https://stackoverflow.com/questions/48155939
复制相似问题