简体   繁体   English

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

[英]excel vba - Using autofilter - can't pass the filtered range to a sub, it keeps passing the entire sheet range

I can't seem to figure this one out. 我似乎无法弄清楚这一点。 I have a function and a sub where I call the function to get the unique values (from column N (text values)) from the range I've already selected from the autofilter. 我有一个函数和一个子函数,在其中调用函数以从已经从自动过滤器中选择的范围中获取唯一值(从N列(文本值))。 Somehow, the range keeps being the entire sheet range and not the selected. 不知何故,范围始终是整个图纸范围,而不是选定范围。

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

any suggestions? 有什么建议么?

Instead of 代替

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

use 采用

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

In response to the additional question asked in the comments, you could copy varArray to another sheet (assumed to already exist, and being referred to by the object wsOutput, and output to be written to column A) as follows 为了回应注释中提出的其他问题,您可以将varArray复制到另一张表(假定已经存在,并由对象wsOutput引用,并输出到A列),如下所示

Dim r as Integer
For r = LBound(varArray) To UBound(varArray)
    wsOutput.Cells(r, 1).Value = varArray(r)
Next

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM