如何使用VBA删除除特定标题外的所有空列?

我想删除工作表中符合以下条件的所有列:

  • 第1行=“foobar”
  • 行2-1000是空的

这听起来很简单,但我还没有设法完全工作。 任何帮助将大规模赞赏。

谢谢!

怎么样

dim col as Long, lastCol as Long, r as range lastCol = ActiveSheet.Usedrange.columns(Activesheet.Usedrange.columns.count).column for c=lastCol to 1 Step -1 set r = Range(Cells(1, c), Cells(1000, c)) if r.Rows(1) = "foobar" Then if WorksheetFunction.CountA(Range(r.Rows(2), r.Rows(r.Rows.Count))) = 0 then Columns(c).delete end if end If next 

[由OP编辑:添加缺less的空间]

按照您的要求删除行的最快方法( TRIED AND TESTED )。

我假设Row1有列标题

 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