如何用标题删除空列?

时间:2015-02-16 13:16:22

标签: excel

我有列标题,如材料1,材料2,...材料15.如果没有数据,则列在这些标题下方,即列是否为空。然后应自动删除整个列。

示例:如果材料5,材料7,材料15列为空,则应将其删除。

我正在尝试下面的代码,但是在删除2或3列之后,它在材料15列之前停止工作。请帮助我。



Sub clearcol()
On Error Resume Next
 Dim lRealLastRow, lRealLastCol As Long
    lRealLastRow = Cells.Find("*", Range("A1"), xlValues, , xlByRows, xlPrevious).Row
    lRealLastCol = Cells.Find("*", Range("A1"), xlValues, , xlByColumns, xlPrevious).Column
    For i = 1 To lRealLastCol
        If lRealLastRow - WorksheetFunction.CountBlank(Intersect(Columns(i), ActiveSheet.UsedRange)) <= 1 Then _
            Columns(i).EntireColumn.Delete
    Next i

End Sub
 
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

如果删除一列,并同时递增计数器,则跳过一些列。要解决此问题,请颠倒For循环

的顺序
For i = lRealLastCol To 1 Step -1

答案 1 :(得分:0)

考虑这个选择:

Sub KolumnKiller()
    Dim N As Long, i As Long, Kount As Long
    Dim wf As WorksheetFunction
    Set wf = Application.WorksheetFunction
    N = Cells(1, Columns.Count).End(xlToLeft).Column
    For i = N To 1 Step -1
        Kount = wf.CountA(Cells(1, i).EntireColumn)
        If Kount = 1 Or Kount = 0 Then
            Cells(1, i).EntireColumn.Delete
        End If
    Next i
End Sub