簡體   English   中英

定義可見行數以僅在可見單元上實現功能

[英]define visible rows count to implement functions on visible cells only

我用了

對於i = 2到activesheet.usedrange.rows.count

但是當我根據某些條件過濾列並稍后放置一些If條件時,我無法為可見行定義相同的方式。

請幫助

這是我創建的用於對過濾列表中可見行進行計數的函數,它也適用於隱藏行的非過濾范圍。 您必須小心使用過濾范圍。 (如果源數據中的行是連續的,那么它們在過濾后的數據中可能是連續的。所以三行可能= 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM