具有不同迭代次数的嵌套循环

问题描述 投票:0回答:1

我必须遍历1到5,以确定是否需要保留或删除ID。

enter image description here

例如

  • 我循环遍历所有1,有不止零个“是”,我保持1。
  • 循环显示所有2,没有“是”,因此我将两个2都删除。
  • 出于相同的原因,我保留所有3,删除所有4,然后保留所有5。

如何设置这些长度不同的循环?

下面,我使用条件格式突出显示每个ID的第一个条目,但是我不确定如何使用它。

enter image description here

excel vba
1个回答
1
投票

假设您的数据保持在以下范围A2:B16中,

enter image description here

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
热门问题
推荐问题
最新问题