Excel VBA根据多个列标准删除行

时间:2014-09-15 23:16:53

标签: excel vba excel-vba

我正在尝试根据行是否满足不同列中的2个条件来对一张数据进行一些切割,即如果列D中的值是>如果列F的相邻单元格中的值> -2或NA,然后删除整行。如果只满足1个条件或没有条件,则应保留该行。以下是我到目前为止的情况。当我运行宏时,它将永远持续下去,但我不知道这应该是怎么回事,因为它对我来说看起来不像是一个无限循环(公平地说我只让它坐了45分钟,但那里只有大约15,000个数据行,因此实际上不应超过10分钟)。任何帮助将不胜感激。

Sub Cuts()
    Dim wb1 As Workbook, sh1 As Worksheet
    Dim lastrow1 As Long, lastrow2 As Long
    Set wb1 = Workbooks(“ovaryGisticARRAYRNAseq.final.xlsx")
    Set sh1 = wb1.Sheets(“Cuts”)
    lastrow1 = sh1.Cells(Rows.Count, 4).End(xlUp).Row
    lastrow2 = sh1.Cells(Rows.Count, 6).End(xlUp).Row
    For i = 1 To lastrow1
        For j = 1 To lastrow2
            If sh1.Cells(i, 4).Value > -2 Then
                If sh1.Cells(j, 6).Value > -2 Then
                    sh1.Cells(j, 6).EntireRow.Delete
                ElseIf sh1.Cells(j, 6).Value = “NA” Then
                    sh1.Cells(j, 6).EntireRow.Delete
                End If
            End If
        Next j
    Next i
End Sub

1 个答案:

答案 0 :(得分:2)

我不确定您希望如何处理列标题中的空白单元格或文本,但我建议您进行此修改。

Sub Cuts()
    Dim wb1 As Workbook
    Dim lr As Long, i As Long
    Set wb1 = Workbooks(“ovaryGisticARRAYRNAseq.final.xlsx")
    With wb1.Sheets("Cuts")
        lr = Application.Max(.Cells(Rows.Count, 4).End(xlUp).Row, _
          .Cells(Rows.Count, 6).End(xlUp).Row)
        For i = lr To 1 Step -1
            If .Cells(i, 4).Value > -2 And _
              (.Cells(i, 6).Value > -2 Or UCase(.Cells(i, 6).Value) = "NA") Then
                .Rows(i).EntireRow.Delete
            End If
        Next i
    End With
End Sub