上下文:我有一系列单元格,其中一些单元格具有相同的内容。我试图遍历单元格并根据值找到匹配的次数(最多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]
答案 0 :(得分:0)
好的,修复很简单:根据匹配的值来更改 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
答案 1 :(得分:0)