删除Excel中先前删除的行之间的行

时间:2014-05-22 18:46:20

标签: excel vba excel-vba delete-row subtotal

我要写VBA代码,删除某些行(列中的某些单词)。我有一个在下面。我还有删除两个先前删除的行(小计)之间的所有行的问题(*并且条件是它们之间只有一行,如果更多则不删除它们)

请问请问有没有办法解决这个问题? 如果这个问题含糊不清(我是新人),请告诉我。

Sub DeleteRows()
Dim c As Range
Dim SrchRng As Range
Dim SrchStr As String

Set SrchRng = ActiveSheet.Range("F1", ActiveSheet.Range("F10000").End(xlUp))
SrchStr = InputBox("Please Enter A Search String")
Do
    Set c = SrchRng.Find(SrchStr, LookIn:=xlValues)
    If Not c Is Nothing Then c.EntireRow.Delete
Loop While Not c Is Nothing

End Sub

1 个答案:

答案 0 :(得分:0)

您已经感兴趣的列(在这种情况下为F),并且您还提示用户指定要删除的字符串,这听起来像是狡猾地使用Range.Autofilter方法的完美配方。 (这是MSDN链接:http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.autofilter(VS.80).aspx

假设您正在操作的数据块来自A:F,您可以写:

Option Explicit
Sub DeleteRowsWithAutoFilter()

Dim DataRng As Range, DeleteMe As Range
Dim SrchStr As String

'set references up-front
Set DataRng = ActiveSheet.Range("A1", ActiveSheet.Range("F10000").End(xlUp))
SrchStr = InputBox("Please Enter A Search String")

'turn off alerts for delete action
Application.DisplayAlerts = False
DataRng.AutoFilter Field:=6, Criteria1:=SrchStr '<~ apply autofilter
With DataRng
    Set DeleteMe = .Offset(1, 0) '<~ set the delete range
    DeleteMe.Delete
End With
ActiveSheet.AutoFilterMode = False
Application.DisplayAlerts = True

End Sub