我必须遍历1到5,以确定是否需要保留或删除ID。例如,我循环遍历所有1,存在多个“是”,而我保持1。循环遍历所有2,没有“是”,因此我删除了两个2。出于相同的原因,我保留所有3,删除所有4,然后保留所有5。
我不确定如何设置这些长度不同的循环。有人可以帮忙吗?
编辑:我使用条件格式来突出显示每个ID的第一个条目,但是我不确定如何使用它...任何想法都值得赞赏!
答案 0 :(得分:1)
假设您的数据保存在以下范围A2:B16中,
Sub KeepMyData()
Dim rngData As Range
Dim rngRow As Range
Dim valuesToKeep() As Integer
Dim iCounter As Integer
Dim blnKeep As Boolean
Set rngData = ThisWorkbook.Worksheets(1).Range("A2:B16")
' Run through the loop to find the values to keep
For Each rngRow In rngData.Rows
If rngRow.Cells(1, 2) = "yes" Then
ReDim Preserve valuesToKeep(0 To iCounter)
valuesToKeep(iCounter) = rngRow.Cells(1, 1)
iCounter = iCounter + 1
End If
Next
' Delete the unwanted values
For Each rngRow In rngData.Rows
blnKeep = False
' Check if the current value is inside the values to keep
For iCounter = 0 To UBound(valuesToKeep)
If rngRow.Cells(1, 1).Value = valuesToKeep(iCounter) Then
blnKeep = True
Exit For
End If
Next
' Use this if you want to delete the entire row
' If Not blnKeep Then rngRow.Delete xlUp
' Use this if you just want to clear the row
If Not blnKeep Then rngRow.Clear
Next
End Sub