【问题标题】:VBA Get values from the filter function in Excel 2007VBA 从 Excel 2007 中的筛选函数中获取值
【发布时间】:2015-08-06 14:36:51
【问题描述】:

在 Excel 2007 的“版本”菜单中使用“过滤器”功能时,标题单元格的右下方会显示小箭头。单击一个时,会弹出该列中每个不同值的列表,并提供选择它们的选项。

如何获取这些值并使用 VBA 循环遍历它们?

我试过了:

Dim Filter As Range
For Each Filter In Range(Cells(2, 1), Cells(2, 1).End(xlDown)).SpecialCells(xlCellTypeVisible).Cells
    MsgBox (Filter.value)
Next Filter

但它不起作用(它循环遍历列的所有单元格)。也许是因为在运行宏时没有“点击”箭头。我在a post 中发现了这个For Each 循环,讨论的是Excel 2002。

[编辑]

以下不是我正在寻找的解决方案,因为它的执行时间比原生 Excel 方式要多得多,但它是一种可以接受的解决方法。

Dim values As New Collection
Dim RowCount As Long
RowCount = Cells(Rows.Count, "A").End(xlUp).Row
Dim IsUnique As Boolean
For i = 2 To RowCount
    IsUnique = True
    For Each value In values
        If value = Range("A" & i).value Then
            IsUnique = False
        End If
    Next value
    If IsUnique Then
        values.Add Range("A" & i).value
    End If
Next i

【问题讨论】:

  • 你的意思是你只想要一个没有重复的值列表? (这就是您的过滤器显示的内容,对吧?)
  • 是的,过滤器弹出窗口显示了一个没有重复的所有值的列表,这就是我想要的。
  • 2 个好答案,取决于你想要什么:stackoverflow.com/questions/11835771/…
  • 谢谢,但这不是我想要的。

标签: vba excel


【解决方案1】:

Find 返回一个 Range 对象,该对象表示找到该信息的第一个单元格。

您可以使用 FindNext 和 FindPrevious 方法重复搜索

本示例在工作表 1 的 A1:A500 范围内查找包含值 2 的所有单元格,并将其更改为 5。

With Worksheets(1).Range("a1:a500") 
Set c = .Find(2, lookin:=xlValues) 
If Not c Is Nothing Then 
    firstAddress = c.Address 
    Do 
        c.Value = 5 
        Set c = .FindNext(c) 
    Loop While Not c Is Nothing And c.Address <> firstAddress 
End If 
End With

【讨论】:

  • 对不起,这不是我想要做的。我更多的是寻找带有解释的是/否答案。
猜你喜欢
  • 2013-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 2016-02-04
  • 1970-01-01
  • 2013-06-30
相关资源
最近更新 更多