如果它具有值,则仅在范围中选择随机单元格 - Excel

时间:2014-04-09 13:13:36

标签: excel excel-vba random vba

所以这是我正在使用的以下VBA代码。它工作得很完美,但我需要扩大范围以检查其他单元格,但其中一些单元格可能包含空单元格,我不想选择它们。

有没有办法绕过那些空单元?

Dim RNG1 As Range
Set RNG1 = Range("H1:H30")

Dim randomCell1 As Long
    randomCell1 = Int(Rnd * RNG1.Cells.Count) + 1

With RNG1.Cells(randomCell1)
.Select
'will do something else here, like copy the cell, fill the cell with a color, etc
End With

5 个答案:

答案 0 :(得分:6)

这应该只选择非空单元格:

Sub marine()
    Dim RNG1 As Range, r As Range, c As Collection
    Set c = New Collection
    Set RNG1 = Range("H1:H30")
    For Each r In RNG1
        If r.Value <> "" Then
            c.Add r
        End If
    Next r
    Dim N As Long
    N = Application.WorksheetFunction.RandBetween(1, c.Count)
    Set rselect = c.Item(N)
    rselect.Select
End Sub

注意:

这是一般技术的一个例子。要从范围的子集中随机选择,请收集子集并从集合中进行选择。

答案 1 :(得分:2)

有点太晚但没有伤害发布:)

Sub test()

Dim rng As Range, cel As Range
Dim NErng
Dim i As Integer

Set rng = Range("A1:A15")

For Each cel In rng
    If Len(cel) <> 0 Then
        If IsArray(NErng) Then
            ReDim Preserve NErng(UBound(NErng) + 1)
            NErng(UBound(NErng)) = cel.Address
        ElseIf IsEmpty(NErng) Then
            NErng = cel.Address
        Else
            NErng = Array(NErng, cel.Address)
        End If
    End If
Next

i = Int((UBound(NErng) - LBound(NErng) + 1) * Rnd + LBound(NErng))
Debug.Print Range(NErng(i)).Address

End Sub

答案 2 :(得分:2)

如果H列中的值为XlConstants,则使用SpecialCells

Sub Option_B()
Dim rng1 As Range
Dim rng2 As Range
Dim lngCel As Long

On Error Resume Next
Set rng1 = Range("H1:H30").SpecialCells(xlCellTypeConstants)
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub

Dim randomCell1 As Long
randomCell1 = Int(Rnd * rng1.Cells.Count) + 1

For Each rng2 In rng1.Cells
'kludgy as there will be multiple areas in a SpecialFCells range with blank cells
lngCel = lngCel + 1
    If lngCel = randomCell1 Then
        Application.Goto rng2
        Exit For
    End If
Next

End Sub

答案 3 :(得分:1)

编辑 - @brettdj是对的。调整这个以更好地回答&#34;跳过这些细胞&#34;问题

试试这个:

DangThisCellIsBlank:
RandomCell = Int(Rnd * RNG1.Cells.Count) + 1

With RNG1.Cells(RandomCell)
    If .Value <> "" Then
        'do stuff
    Else
        'go back and pick another cell
        GoTo DangThisCellIsBlank
    End If
End With

答案 4 :(得分:0)

尝试使用IsEmpty(RNG1.Cells(randomCell1))

Dim RNG1 As Range
Set RNG1 = Range("H1:H30")

Dim randomCell1 As Long
randomCell1 = Int(Rnd * RNG1.Cells.Count) + 1

'Keep Looping until you find a non empty cell
Do While IsEmpty(RNG1.Cells(randomCell1))
    randomCell1 = Int(Rnd * RNG1.Cells.Count) + 1
Loop
'================================================

With RNG1.Cells(randomCell1)
    .Select
    'will do something else here, like copy the cell, fill the cell with a color, etc
End With