简体   繁体   中英

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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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