获取过滤范围内的随机单元格

时间:2016-02-23 07:51:17

标签: excel excel-vba vba

要获得过滤范围内的随机单元格,我使用下面的方法,但有时会选择隐藏的单元格。

如何限制随机选择以选择可见细胞?

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`

2 个答案:

答案 0 :(得分:0)

随机化整个范围内的位置,并交叉检查是否在可见单元格内。

    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

答案 1 :(得分:0)

替代方法不会偏倚结果但仍使用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