我正在尝试在另一个Sub中运行下面的Sub。
我遇到的问题是wRange.AutoFilter(3, "")
用TRUE
填充wRange中的所有单元格,覆盖之前的数据。
为了查看它是否可以解决TRUE
问题,我将行If wCell = "" Then
更改为If wCell = "True"
,我发现它不会删除每一行,而是每隔一个行。
Sub DeleteBlankRows()
Dim wRange As Range
Dim wRange2 As Range
Dim lastrow As Integer
lastrow = Range("A7").End(xlDown).Row
Set wRange = Range("$C$7:$C$" & lastrow)
wRange = wRange.AutoFilter(3, "")
Range("$A$10000").Select
Selection.End(xlUp).Select
If ActiveCell.Row <> 5 Then
Set wRange2 = wRange.SpecialCells(xlCellTypeVisible)
For Each wCell In wRange2
If wCell = "" Then
wCell.EntireRow.DELETE
End If
Next wCell
End If
wRange = wRange.AutoFilter(3)
End Sub
你能明白为什么会这样做吗?
感谢您的帮助。
P.S。作为旁注,我最初让子有Sub DeleteBlankRows(ByRef wRange)
并且它没有问题,我没有说wRange2
是什么。这两个Dims
都在较大的Sub中说明,但这对我来说没有意义。
答案 0 :(得分:2)
如果C列中的相关单元实际上是空的,而不是返回的公式&#34;&#34;例如,你可以使用这样的东西:
Sub DeleteBlankRows()
Dim wRange As Range
Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
If lastrow > 7 Then
On Error Resume Next
Set wRange = Range("C7:C" & lastrow).SpecialCells(xlCellTypeBlanks)
On Error GoTo 0
If Not wRange Is Nothing Then wRange.EntireRow.Delete
ElseIf lastrow = 7 Then
If Len(Range("C7").Value) = 0 Then Rows(7).Delete
End If
End Sub
答案 1 :(得分:1)
When deleting rows individually, always work from the bottom to the top. The nature of a For Each wCell In wRange2
is such that you are working from the top to the bottom.
In any event, deleting the rows in bulk would be preferred.
Sub DeleteBlankRows()
Dim wRange As Range
Dim lastrow As Long
With ActiveSheet '<-set this worksheet erference properly!
If .AutoFilterMode Then .AutoFilterMode = False
lastrow = .Range("A7").End(xlDown).Row
Set wRange = .Range("$A$7:$C$" & lastrow)
With wRange
.AutoFilter field:=3, Criteria1:=""
With .Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count)
If CBool(Application.Subtotal(103, .Columns(1))) Then
.SpecialCells(xlCellTypeVisible).EntireRow.Delete
End If
End With
.AutoFilter field:=3
End With
End With
End Sub
As per your sample code, I've left the autofilter active but cleared the filter.
答案 2 :(得分:0)
A better way to check if there is any information in a cell is the IsEmpty function:
If IsEmpty(cell(1, 1)) = True
wCell.EntireRow.DELETE
endif