How can I use VBA to delete all columns which are empty apart from a specific header?

前端 未结 2 1691
甜味超标
甜味超标 2021-01-27 04:43

I\'d like to delete all columns in a worksheet which meet the following criteria:

  • row 1 = \"foobar\"
  • rows 2-1000 are empty

It sounds simpl

2条回答
  •  梦谈多话
    2021-01-27 05:11

    Fastest way to delete rows as per your requirement (TRIED AND TESTED).

    I am assuming that Row1 Has Column Headers

    Option Explicit
    
    Sub Sample()
        Dim aCell As Range, rng As Range
        Dim LastCol As Long, LastRow As Long, i As Long
    
        With Sheets("Sheet1")
            Set aCell = .Rows(2).Find(What:="foobar", LookIn:=xlValues, _
            Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)
    
            If Not aCell Is Nothing Then .Rows(2).Delete
    
            LastRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row
    
            LastCol = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByColumns, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Column
    
            Set rng = Range("A1:" & Split(Cells(, LastCol).Address, "$")(1) _
                      & LastRow)
    
            ActiveSheet.AutoFilterMode = False
    
            For i = 1 To LastCol
                rng.AutoFilter Field:=i, Criteria1:=""
            Next i
    
            rng.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    
            ActiveSheet.AutoFilterMode = False
        End With
    End Sub
    

提交回复
热议问题