查找和删除没有特定单词的标题列。

时间:2013-10-28 06:18:32

标签: excel vba

我需要:  1.在标题中找到包含“target”一词的列。 (从P1到QI1的范围)  2.删除标题中没有“target”的所有其他列。

代码:

Sub Cleanup()
    Dim rng As Range
    With ActiveSheet.Range("P1:QI1")
        Set rng = ActiveSheet.Range("P1:QI1").Find(What:="target", _
            LookAt:=xlPart, MatchCase:=False)
        Do While Not rng Is Nothing
            rng.EntireColumn.Delete
            Set rng = .FindNext
        Loop
    End With
End Sub

上面的代码是删除所有带有'target'一词的列。我想反过来说。我需要保留这些列。

提前谢谢。

1 个答案:

答案 0 :(得分:0)

测试 - 享受:)

Sub test()
Dim erange As Range
Dim str As String
    For Each erange In Range("A1:E1")
      If not erange.Value = "Target" Then
      '  If InStr(erange.Value, "Target") <> 0 Then
            If str <> "" Then
                str = str & "," & erange.EntireColumn.Address
            Else
                str = erange.EntireColumn.Address
            End If
        End If
    Next erange
str = Replace(str, "$", "")
' Delete columns in single shot
Range(str).Delete
End Sub