Excel VBA删除单元格中的内容,然后删除总行数
我正在编程来查看范围,从单元格区域中删除内容,然后删除已经清除内容的整行单元格。 目前,我运行代码,所有的行都被删除。 另外,我很欣赏build议,使代码干。
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
在你最后的For循环中,你有
Rows.EntireRow.Delete
你应该在哪里
VarCase.EntireRow.Delete
这可能是一般删除的原因。
对于每个构造并不总是愉快地工作,正在改变的范围(这里通过行删除),所以要小心。 您可能会通过联盟累积一系列删除目标,并在最后的一个语句中删除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
只需将此代码放在VBA中的数据工作表下的此代码下
Sub Alfredo() Dim msg As String Dim VarCase As Range For Each VarCase In ActiveSheet.Range("D:D") If VarCase.Value2 = "John" Or VarCase.Value2 = "Thompson" Or VarCase.Value2 = "Mattson" Then VarCase.ClearContents End If Next VarCase For Each VarCase In ActiveSheet.Range("D:D") If VarCase.Value = "" Then VarCase.EntireRow.Delete End If Next VarCase End Sub
为什么循环两次?
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