从范围变量调用过滤行

时间:2015-04-10 13:10:45

标签: excel vba excel-vba

我使用VBA在Excel中过滤我的表并将其保存在范围变量中。例如:我有1000个字段,过滤后只有200个字段。我将数据保存在一个范围内并随机选择此范围内的一个数字。

在此之后,我想在过滤后的行中更改信息。但是,我不知道这是怎么回事。例如,如果我使用Cells(Line, 10),则vba会考虑所有行并打印出范围。

如何仅按编号或地址更改已过滤的单元格?

Dim Rng As Range
ActiveSheet.Range("A1:AE" & tlast_row).AutoFilter Field:=1, Criteria1:="teste"
Set Rng= Range("A2", Range("A2").End(xlDown)).Cells.SpecialCells(xlCellTypeVisible)
tSelCell = WorksheetFunction.RandBetween(1, RngC.Count)
Rng.SpecialCells(xlCellTypeVisible).Cells(tSelCell, 3) = "TEST" '< Here is the problem

1 个答案:

答案 0 :(得分:1)

假设我们有以下数据:

enter image description here

我们会过滤&#34; Happy&#34;:

enter image description here

可见单元形成不相交的范围。要从不相交的范围进行随机选择,我们首先创建一个可见单元格地址的数组,然后从该数组中随机选择:

Option Base 1

Sub PickARandomVisibleRow()
    Dim rDisjoint As Range, ary() As Variant, NrD As Long
    Dim tSelCell As Long
    Set rDisjoint = Range("A2:A24").Cells.SpecialCells(xlCellTypeVisible)
    NrD = rDisjoint.Count
    ReDim ary(1)

    i = 1
    For Each r In rDisjoint
        If i = 1 Then
        Else
            ReDim Preserve ary(i)
        End If
        ary(i) = r.Address
        i = i + 1
    Next r

    msg = ""
    For i = LBound(ary) To UBound(ary)
        msg = msg & vbCrLf & i & vbTab & ary(i)
    Next i
    MsgBox msg

    tSelCell = Application.WorksheetFunction.RandBetween(1, UBound(ary))
    msg = "Random Pick item: " & tSelCell & " which is cell: " & ary(tSelCell)
    MsgBox msg
End Sub