使用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
答案 0 :(得分:0)
Find返回一个Range对象,该对象表示找到该信息的第一个单元格。
您可以使用FindNext和FindPrevious方法重复搜索
此示例查找工作表上范围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