簡體   English   中英

獲取過濾范圍內的隨機單元格

[英]Get random cells in a filtered range

為了在過濾范圍內獲得隨機單元格,我在下面使用此方法,但有時會選擇隱藏的單元格。

如何限制隨機選擇以選擇可見的單元格?

Set areaRng = Sheet1.Range("table_area").SpecialCells(xlCellTypeVisible)
Dim randomCell As Long
randomCell = Int(Rnd * areaRng.Cells.Count) + 1
On Error Resume Next      
With areaRng.Cells(randomCell)
    .Select        
End With`

在整個范圍內隨機分配一個位置,然后交叉檢查該位置是否在可見單元格內。

    Dim areaAllRng As Range, areaVisibleRng As Range
    Dim randomCell As Long

    With Sheet6
        Set areaAllRng = .Range("table_area").Cells
        Set areaVisibleRng = .Range("table_area").SpecialCells(xlCellTypeVisible)

        randomCell = Int(Rnd * areaAllRng.Cells.Count) + 1

        Do While Intersect(areaAllRng.Cells(randomCell), areaVisibleRng) Is Nothing
            'Debug.Print areaAllRng.Cells(randomCell).Address(0, 0)
            randomCell = Int(Rnd * areaAllRng.Cells.Count) + 1
        Loop

        Debug.Print areaAllRng.Cells(randomCell).Address(0, 0)
        areaAllRng.Cells(randomCell).Select

    End With

不偏倚結果但仍利用Areas屬性的替代方法,從而避免了運行時間因隨機機會而耗盡的風險

Sub Demo()
    Dim rngVisible As Range
    Dim arr As Range
    Dim CellsToCount As Long
    Dim RandCell As Range

    Set rngVisible = Sheet1.Range("table_area").SpecialCells(xlCellTypeVisible)

    CellsToCount = Int(Rnd * rngVisible.Count) + 1

    For Each arr In rngVisible.Areas
        If arr.Cells.Count >= CellsToCount Then
            Set RandCell = arr.Cells(CellsToCount)
            Exit For
        Else
            CellsToCount = CellsToCount - arr.Cells.Count
        End If
    Next

    RandCell.Select

End Sub

暫無
暫無

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

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