excel vba - 使用自动过滤器 - 无法将过滤后的范围传递给子,它会不断传递整个工作表范围

时间:2016-07-28 19:37:02

标签: excel vba excel-vba

我似乎无法想出这个。我有一个函数和一个子函数,我在其中调用函数来从已经从自动过滤器中选择的范围中获取唯一值(来自列N(文本值))。不知何故,范围保持整个工作表范围而不是选定范围。

Function UniquesFromRange(rng As Range)
Dim d As Object, c As Range, tmp
Set d = CreateObject("scripting.dictionary")
For Each c In rng.Cells
   tmp = Trim(c.Value)
   If Len(tmp) > 0 Then
        If Not d.Exists(tmp) Then d.Add tmp, 1
   End If
Next c
UniquesFromRange = d.Keys
End Function




Sub mainSub()
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)
        lwmin = WorksheetFunction.Subtotal(5, Range("H:H"))
        lwmax = WorksheetFunction.Subtotal(4, Range("H:H"))

        'This does not work,  I want to get the unique values from column N
        'that are already in the filtered range. So far this shows
        'all the values in the column not only the ones already filtered.

         varArray = UniquesFromRange(Range("N:N"))
         'I've also tried this:
        'varArray = UniquesFromRange(Range.Cells)


         'Debug.Print fCatId(key) & " - " & key & "   " & lwmin & "-" & lwmax  & fData(key) & " - " & Join(varArray, vbNewLine)



    End With
Next key
Application.ScreenUpdating = True
End Sub

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

而不是

pip.exe

使用

varArray = UniquesFromRange(Range("N:N"))

在回复评论中提到的其他问题时,您可以将varArray复制到另一个工作表(假设已存在,并由对象wsOutput引用,输出将写入A列),如下所示

varArray = UniquesFromRange(Range("N1:N" & llastrow).SpecialCells(xlCellTypeVisible))