定义可见行数以仅在可见单元格上实现函数

时间:2015-01-07 09:53:33

标签: excel-vba vba excel

我用过

for i = 2 to activesheet.usedrange.rows.count

但是当我按照某些标准过滤列时,后来放了一些If条件我无法为可见行定义相同的方式。

请帮助

1 个答案:

答案 0 :(得分:0)

这是我创建的一个函数,用于计算已过滤列表中的可见行,它还适用于隐藏行的非过滤范围。您必须小心使用过滤范围。 (如果源数据中的行是连续的,那么它们可能在过滤后的数据中是连续的。所以三行可能= 1个区域。)因此,为了解决这个问题,我循环遍历每个区域,然后计算每个区域中的行。

Function CountVisibleRowsInFilteredAreas(Optional myRange As Range)
Dim lCount As Long
Dim lCount2 As Long
Dim CurrRng As Range
Dim vArrRows As Variant
Dim vArrUnqRows As Variant
Dim iRow As Long
Dim iUnq As Long
Dim nUnq As Long
Dim rw As Range
Dim isUnq As Boolean

'if range to use was not specified in the code, then use the ActiveSheets' UsedRange
If myRange Is Nothing Then Set myRange = ActiveSheet.UsedRange

'this is created for autofiltered ranges, or non-autofiltered ranges with hidden rows,
'to count the number of rows that are visible.
'it assumes there is a header row and will count that as a row

'count the number of rows in each area to get the upper bound for the array that
 'will contain the row numbers of all of the rows in each area.
 lCount = 0
    For Each CurrRng In myRange.SpecialCells(xlCellTypeVisible).Areas
        lCount = lCount + CurrRng.Rows.Count
    Next CurrRng

'dim the array and give it upper and lower bounds, Set up a second counter to identify
'which row the loop is on, then loop through each row in each area,
'and get the row number and store it in an array.
ReDim vArrRows(1 To lCount)
    lCount2 = 0
    For Each CurrRng In myRange.SpecialCells(xlCellTypeVisible).Areas
        For Each rw In CurrRng.Rows
            lCount2 = lCount2 + 1
            vArrRows(lCount2) = rw.Row
        Next rw
    Next CurrRng

'remove duplicates/count unique rows
ReDim vArrUnqRows(1 To lCount2)
nUnq = 0
For iRow = 1 To lCount2
    isUnq = True
    'first one in vArrRows is always unique, and added to vArrUnqRows, the rest are compared
    'against the known unique ones in vArrUnqRows, if they are unique then they are added
    'to vArrUnqRows
    For iUnq = 1 To nUnq
        If vArrRows(iRow) = vArrUnqRows(iUnq) Then
            isUnq = False
            Exit For
        End If
    Next iUnq
    'add unique row numbers to vArrUnqRows
    If isUnq = True Then
        nUnq = nUnq + 1
        vArrUnqRows(iUnq) = vArrRows(iRow)
    End If
Next iRow
ReDim Preserve vArrUnqRows(1 To nUnq)
'creates an array of the row numbers of visible rows, but that is not used here and only the
'count of the visible rows is returned (nUnq)
CountVisibleRowsInFilteredAreas = nUnq

End Function