IsEmpty功能问题

时间:2016-08-26 19:08:55

标签: excel vba

任何人都可以告诉我这个程序我做错了什么吗?它应该删除我的文件中的大约6行,但是当我运行它时,没有任何效果。在大约6行中,B列和C列中没有数据,它们的位置是动态的,我想摆脱这些行。

谢谢

Dim lastrow As Integer

lastrow = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("ISSUES").Range("D1:D5000"))

For i = 1 To lastrow
    If IsEmpty(ThisWorkbook.Sheets("ISSUES").Cells(i, 2)) = True And IsEmpty(ThisWorkbook.Sheets("ISSUES").Cells(i, 3)) = True Then
        ThisWorkbook.Sheets("ISSUES").Cells(i, 2).EntireRow.Delete
    End If
Next i

2 个答案:

答案 0 :(得分:2)

第二个问题是表现。一次删除一行将使您的宏对于大型行非常慢,就像您在这里寻找5000行一样。

最好的办法是将他们聚在一起,然后一次性删除。还有助于避免反向循环。

Sub test()


Dim lastrow          As Long
Dim rngDelete        As Range

lastrow = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("ISSUES").Range("D1:D5000"))

For i = 1 To lastrow
    If IsEmpty(ThisWorkbook.Sheets("ISSUES").Cells(i, 2)) = True And IsEmpty(ThisWorkbook.Sheets("ISSUES").Cells(i, 3)) = True Then
        'ThisWorkbook.Sheets("ISSUES").Cells(i, 2).EntireRow.Delete

        '/Instead of deleting one row at a time, club them in a range. Also no need for reverse loop
        If rngDelete Is Nothing Then
            Set rngDelete = ThisWorkbook.Sheets("ISSUES").Cells(i, 2)
        Else
            Set rngDelete = Union(rngDelete, ThisWorkbook.Sheets("ISSUES").Cells(i, 2))
        End If


    End If
Next i


    '/ Now delete them in one go.
    If Not rngDelete Is Nothing Then
        rngDelete.EntireRow.Delete
    End If

End Sub

答案 1 :(得分:0)

另一种解决方案:

Dim lastrow As Integer
Dim cond1, cond2 As Range

lastrow = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("ISSUES").Range("D1:D5000"))

For i = lastrow To 1 Step -1
    Set cond1 = ThisWorkbook.Sheets("ISSUES").Cells(i, 2)
    Set cond2 = ThisWorkbook.Sheets("ISSUES").Cells(i, 3)

    If cond1.Value = "" Then
        cond1.ClearContents
    End If
    If cond2.Value = "" Then
        cond2.ClearContents
    End If

    If IsEmpty(cond1.Value) = True And IsEmpty(cond2.Value) = True Then
        ThisWorkbook.Sheets("ISSUES").Cells(i, 2).EntireRow.Delete
    End If
Next i