Excel VBA筛选后的范围xlCellTypeVisible

3
我想要实现的目标是:从特定地址打开一个工作簿,过滤第一列等于36或541的值(我已经完成了这个部分),然后检查第三列是否存在值为2,如果存在,则将除第三列中值为2之外的所有内容过滤掉;如果第三列中不存在值为2,则跳过。
我尝试使用SpecialCells(xlCellTypeVisible)来命名新范围,但我一定使用不正确,因为它给我返回的是仅存在于未过滤数据的旧范围中的值为2的结果。
感谢您的时间!
Sub filters()

Dim wb As Workbook
Dim nwb As Workbook

Set wb = ThisWorkbook

Set nwb = Workbooks.Open("ADDRESS.FILE.xlsx")

With ActiveSheet

.AutoFilterMode = False
.Range("$A$1:$AD$5000").AutoFilter Field:=1, Criteria1:="=36", Operator:=xlOr, Criteria2:="=541"
'.Range("$A$1:$AD$5000").AutoFilter Field:=3, Criteria1:="2"

End With

Dim newrange As Range

Set newrange = ActiveSheet.AutoFilter.Range.SpecialCells(xlCellTypeVisible)

Dim i As Integer, intValueToFind As Integer
intValueToFind = 2
For i = 1 To 5000    ' Revise the 5000 to include all of your values
    If newrange(i, 3).Value = intValueToFind Then
        MsgBox ("Found value on row " & i)
        Exit Sub
    End If
Next i

' This MsgBox will only show if the loop completes with no success
MsgBox ("Value not found in the range!")


End Sub

你不能使用语法 newrange(i, 3).Value 来访问多区域范围中的值。 - Tim Williams
即使使用那种语法,它仍然可以运行。当我使用Cells(i, 3).Value代替newrange时,我得到相同的值。 - Mikey
它会运行(即不会抛出错误):只是它不会给你正确的答案... - Tim Williams
哦,好的。所以我修改了它,改为使用“Cells”而不是“newrange”。在筛选后无法检查列中的值吗?谢谢。 - Mikey
1个回答

5

类似以下代码应该是可行的:

Dim newrange As Range, rw as range

Set newrange = ActiveSheet.AutoFilter.Range.SpecialCells(xlCellTypeVisible)

Dim intValueToFind As Integer
intValueToFind = 2
For Each rw in newrange.Rows
    If rw.cells(3).Value = intValueToFind Then
        MsgBox ("Found value on row " & rw.cells(1).Row)
        Exit Sub
    End If
Next rw

谢谢Tim!非常顺利地完成了工作! - Mikey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接