我正在编程以查看范围,从单元格范围中删除内容,然后删除已清除内容的整行单元格。目前,我运行代码,所有行都被删除。另外,我很感激建议让代码DRY。
Option Explicit
Sub Alfredo()
Dim msg As String
Dim VarCase As Range
Dim ws As Worksheets
Set ws = Sheets("Data")
For Each VarCase In ws.Range("D1:D11000")
If VarCase.Value2 = "John" Or VarCase.Value2 = "Thompson" Or VarCase.Value2 =
"Mattson" Then
VarCase.ClearContents
End If
Next VarCase
For Each VarCase In ws.Range("D1:D11000")
If VarCase.Value = "" Then
Rows.EntireRow.Delete
End If
Next VarCase
End Sub
答案 0 :(得分:3)
在你的最终For循环中,你有
Rows.EntireRow.Delete
你应该在哪里
VarCase.EntireRow.Delete
可能是一般删除的原因。
For Each构造并不总是与正在更改的范围(此处通过行删除)愉快地工作,因此请注意。您可以通过Union累积一系列删除目标,并在最后一个语句中删除DRYness,而不清除任何内容。
此外,缩进是你的朋友。
编辑以添加联盟方法的说明:
Sub TestRowDelete()
Dim ARange As Range
Dim DRange As Range
Set DRange = Nothing
For Each ARange In ActiveSheet.UsedRange.Rows
If ARange(1).Value = "d" Then ' testing first cell on each row
If DRange Is Nothing Then
Set DRange = ARange
Else
Set DRange = Union(DRange, ARange)
End If
End If
Next ARange
If Not DRange Is Nothing Then DRange.EntireRow.Delete
End Sub
答案 1 :(得分:0)
只需将此代码放在此代码下的VBA数据工作表
下@coltest = ISNULL(@col + ', ', '') + (QUOTENAME(x.productid) + ', ' + QUOTENAME(x.productid))
答案 2 :(得分:0)
为什么要循环两次?
Application.ScreenUpdating = False
Dim VarCase As Range
Dim ws As Worksheet
Set ws = Sheets("Data")
For Each VarCase In ws.Range("D1:D11000")
If VarCase.Value2 = "John" Or VarCase.Value2 = "Thompson" Or VarCase.Value2 = "Mattson" Then
VarCase.ClearContents
VarCase.EntireRow.Delete
End If
Next VarCase