2

I have a Macro that deletes a column if the header contains "Group time:"

Sub remove_columns()
    For i = ActiveSheet.Columns.Count To 1 Step -1
        If InStr(1, Cells(1, i), "Group time:") Then Columns(i).EntireColumn.Delete
    Next i
End Sub

I have other columns I need to delete "Total time", "Last page", "Start language" ... about 10 in all.

I could create 10 versions of the above macro but is there a way to have only one macro that has a list of names and deletes those columns

Thanks

4

1 回答 1

3
Sub remove_columns()

    Dim rngFound As Range
    Dim rngDel As Range
    Dim arrColumnNames() As Variant
    Dim varName As Variant
    Dim strFirst As String

    arrColumnNames = Array("Group time:", "Total time", "Last page", "Start language")

    For Each varName In arrColumnNames
        Set rngFound = Rows(1).Find(varName, Cells(1, Columns.Count), xlValues, xlPart)
        If Not rngFound Is Nothing Then
            strFirst = rngFound.Address
            Do
                If rngDel Is Nothing Then Set rngDel = rngFound Else Set rngDel = Union(rngDel, rngFound)
                Set rngFound = Rows(1).Find(varName, rngFound, xlValues, xlPart)
            Loop While rngFound.Address <> strFirst
        End If
    Next varName

    If Not rngDel Is Nothing Then rngDel.EntireColumn.Delete

    Set rngFound = Nothing
    Set rngDel = Nothing
    Erase arrColumnNames

End Sub
于 2013-08-13T15:58:48.440 回答