excel vba从自动筛选结果中将单元格值分配给变量

时间:2016-07-29 20:35:43

标签: excel vba excel-vba

我需要从第N2和M2列获取值,在使用自动过滤器后,分配仅给出整个工作表中不存在于自动过滤器范围内的值。

Sub mainSub()
Dim fRngb as Range

For Each key In fCatId.Keys
With wshcore
    llastrow = wshcore.Range("A" & Rows.Count).End(xlUp).Row
    .AutoFilterMode = False
    .Range("A1:N" & llastrow).AutoFilter
    .Range("A1:N" & llastrow).AutoFilter Field:=1, Criteria1:=fCatId(key)
    min = WorksheetFunction.Subtotal(5, Range("H:H"))
    max = WorksheetFunction.Subtotal(4, Range("H:H"))

    'This does not work. it gives the first 13,2 value not the filtered one.
     Set fRngb = wshcore.AutoFilter.Range.SpecialCells(xlCellTypeVisible)
     'MsgBox fRngb.Cells(13, 2)
     'I've also tried this:
    'Range("K2:K2").CurrentRegion.Value(2)

     Debug.Print fRngb.Cells(13, 2) & " -  " & Range("K2:K2").CurrentRegion.Value(2)
End With
Next key
End Sub

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

在OP的澄清之后

编辑

  • 使用.Areas()对象的Range属性返回由其组成的所有连续范围的集合

  • 获得第一个"区域"索引1:.Areas(1)

  • 将其第一个单元格调整为一行:.Areas(1).Resize(1)

以下是完整代码:

Sub mainSub()
    Dim fRngb As range

    With wshcore
        With .range("A1:N" & .Cells(.Rows.Count, 1).End(xlUp).Row)
            For Each Key In fCatId.Keys
                .AutoFilter field:=1, Criteria1:=fCatId(Key)
                Min = WorksheetFunction.Subtotal(5, .Columns("H")) 
                Max = WorksheetFunction.Subtotal(4, .Columns("H")) 
                Set fRngb = .Columns("N").Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible) '<--| get all column "N" (relative to considered range) filtered values excluded header row
                MsgBox fRngb.Areas(1).Resize(1).Address '<--| get its first cell
                .AutoFilter
            Next Key
        End With
    End With
End Sub

我猜fCatId是Public类型的Dictionary变量...否则您必须将其作为参数传递给mainSub