宏删除除包含某些文本的行以外的所有行

时间:2013-10-25 12:41:50

标签: excel vba excel-vba

我正在尝试编写一个宏,除了包含某些特定文本的宏之外,它将删除每一行。

我需要有以下标准:

  • 永远不要删除前两行
  • 排除可在C或D列中找到“Somme”字样的行。

注意,单词Somme,如果是C或D列中字符串的一部分。找到的文本示例如下:

  

Somme alpha / 000284727819293

到目前为止我所拥有的代码是删除Somme中的行,但是我需要相反:

Sub CleanUp()
    Dim c As Range
    Dim SrchRng

    Set SrchRng = ActiveSheet.Range("D3", ActiveSheet.Range("D65536").End(xlUp))
    Do
        Set c = SrchRng.Find("Somme", LookIn:=xlValues)
        If Not c Is Nothing Then c.EntireRow.Delete
    Loop While Not c Is Nothing
End Sub

1 个答案:

答案 0 :(得分:1)

试一试:

Sub SaveSomeRows()
    Dim N As Long, L As Long, r As Range
    Dim s As String, v As String
    Set r = ActiveSheet.Range("D3", ActiveSheet.Range("D65536").End(xlUp))
    N = r.Count
    s = "somme"
    For L = N To 1 Step -1
        v = LCase(r(L).Value)
        If InStr(1, v, s) = 0 Then
            r(L).EntireRow.Delete
        End If
    Next L
End Sub

修改#1

宏的初始版本忽略了列 C .....请尝试这样做:

Sub SaveSomeRows()
    Dim N As Long, L As Long, r As Range
    Dim s As String, v As String
    Set r = ActiveSheet.Range("D3", ActiveSheet.Range("D65536").End(xlUp))
    N = r.Count
    s = "somme"
    For L = N To 1 Step -1
        v = LCase(r(L).Value & r(L).Offset(-1, 0).Value)
        MsgBox v
        If InStr(1, v, s) = 0 Then
            r(L).EntireRow.Delete
        End If
    Next L
End Sub