如果它有一个值,只在一个范围内select随机单元格 – Excel
所以这里是我目前使用的以下VBA代码。 它完美的作品,但我需要扩大范围来检查额外的单元格,但其中一些单元格可能包含空单元格,我不想select这些。
有没有办法绕过这些空单元?
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
这应该只挑选非空单元格:
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
注意:
这是一个通用技术的例子。 要从范围的子集中进行随机选取,请收集子集并从集合中选取。
如果列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
有点太晚,但没有伤害张贴:)
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
编辑 – @brettdj是正确的。 这是调整,以更好地回答“跳过这些细胞”的问题。
试试这个:
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
尝试使用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