我试图通过导入.CSV文件来更新工作表。 我可以阅读并更新所有信息。更新后,我想删除一些数据。必须删除所有D为空的行(整行)。
为此,我有一个foreach检查D3:D486(是最后一行)。 运行宏后,会删除一些行,但不会删除所有行。
Dim rCell As Range
Dim rRng As Range
Debug.Print CStr(LastRow)
Set rRng = Worksheets("sheet1").Range("D3:D" + CStr(LastRow))
For Each rCell In rRng.Cells
If Not IsEmpty(rCell) Then
Debug.Print rCell.Row
Else
Debug.Print "Empty"
Worksheets("sheet1").Rows(rCell.Row).Delete
End If
Next rCell
我想for-each存在问题。例如,如果他删除第100行,下一次他去101行..但那是前一行102 .. 我可以将单元格保存在一个数组中,但它会是相同的。 除非我走另一条路(从下到上)。我该如何解决这个问题?
答案 0 :(得分:7)
我认为你已经回答了自己的问题:从下到上......
您也可以尝试使用range.EntireRow.Delete方法,如下所示
Dim rCell As Range
Dim lastRow, i
lastRow = 1000
For i = lastRow To 1 Step -1
' if condition met
Worksheets("Sheet1").Range("D:" + i).EntireRow.Delete
Next
答案 1 :(得分:2)
我会这样做:
Dim i As Integer
Dim rRng As Range
Debug.Print CStr(LastRow)
Set rRng = Worksheets("sheet1").Range("D3:D" + CStr(LastRow))
For i = 1 To rRng.Cells.Count
If Not IsEmpty(Worksheets("Sheet1").Range("D:" + i).Value) Then
Debug.Print rCell.Row
Else
Debug.Print "Empty"
Worksheets("Sheet1").Range("D:" + i).EntireRow.Delete
i = i - 1
End If
Next
答案 2 :(得分:1)
雷克斯的回答是正确的,如果你想变得可爱,你也可以这样做:
Sub DeleteRowsWithCriteria()
Dim rng As Range, rngCell As Range, rngDelete As Range
Set rng = Worksheets("sheet1").UsedRange.Columns("D:D").Cells 'Watch out here, if columns A-C are not all used, this doesn't work
For Each rngCell In rng
If rngCell.Value = "" Then
If rngDelete Is Nothing Then
Set rngDelete = rngCell
Else
Set rngDelete = Union(rngDelete, rngCell)
End If
End If
Next rngCell
rngDelete.EntireRow.Delete xlShiftUp
End Sub