Excel VBA代码忽略已滤除(隐藏)的行

时间:2016-10-26 01:30:12

标签: excel vb.net vba excel-vba

我在excel中有一段VB代码来隐藏少于2个数据条目的列(标题为最少),我需要知道如何使用它来隐藏列,同时忽略过滤出的行中的信息:

Sub HideCols()
Dim LC As Integer, j As Integer
Dim cl As Range, rng As Range

Set rng = Range("Table1").SpecialCells(xlCellTypeVisible)

LC = Cells(3, Columns.Count).End(xlToLeft).Column

    For j = 3 To LC
        Columns(j).Hidden = WorksheetFunction.CountA(Columns(j)) < 2
    Next j


Application.ScreenUpdating = True

End Sub

这就是我所拥有的,很多没有意义,需要整理,但这只是因为我一直试图找到自己的方式无济于事。

谢谢!

2 个答案:

答案 0 :(得分:0)

检查它是否先隐藏

Sub HideCols()
Dim LC As Integer, j As Integer
Dim LR As Integer, curCnt as Integer
Dim cl As Range, rng As Range
Dim Data As Variant

Set rng = Range("Table1").SpecialCells(xlCellTypeVisible)

LC = Cells(3, Columns.Count).End(xlToLeft).Column

    For j = 3 To LC
        LR = Cells(Rows.Count, j).End(xlUp).Row
        curCnt = 0
        ' its faster to iterate a variant array than it is Cells
        Data = Range( Cells(1, 1), Cells(LR, LC) )
        for k = 1 to LR
           if Rows(k).Hidden = False and Data(k, j) <> "" Then _
           curCnt = curCnt + 1
        next k
        Columns(j).Hidden = curCnt < 2
    Next j


Application.ScreenUpdating = True

End Sub

答案 1 :(得分:0)

我喜欢以下

Option Explicit

Sub HideCols()
    Dim cols As Range
    Dim iCol As Long

    With Range("Table1")
        Set cols = .Resize(1, 1).Offset(, .Columns.Count + 1)
        For iCol = 1 To .Columns.Count
             If Application.WorksheetFunction.Subtotal(103, .Columns(iCol).SpecialCells(xlCellTypeVisible)) < 2 Then Set cols = Union(cols, .Cells(1, iCol))
        Next iCol
        Set cols = Intersect(.Columns, cols)
        If Not cols Is Nothing Then cols.EntireColumn.Hidden = True
    End With
End Sub

作为旁注,如果使用Autofilter()方法进行过滤,则不会过滤掉标题行。在这种情况下,您可能希望将“检查”的正确术语更改为< 3

相关问题