IsEmptyfunction问题
任何人都可以请告诉我,我在做什么这个程序错了吗? 它应该删除我的文件中的大约6行,但是当我运行它,没有效果。 在大约6行中,B和C列没有数据,它们的位置是dynamic的,我想摆脱这些行。
谢谢
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
第二个问题是performance。 一次删除一行将使你的macros非常慢,大量的行,就像你在这里寻找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
另一个scheme
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