简体   繁体   中英

Selection.SpecialCells() method returns unexpected range (Excel VBA)

When I select a range of three cells say B3:B5, the method acts as expected and displays three messages with "3", "4" and "5".

Sub visTest()
    Dim c As Range
    For Each c In Selection.SpecialCells(xlCellTypeVisible)
        MsgBox c.row
    Next c
End Sub

The problem is when I select only one cell: the Selection.SpecialCells(xlCellTypeVisible) returns ALL visible cells on the worksheet and starts from the cell A1.

How do I make it return only one visible cell within the one selected cell? Why the problem occurs?

Thanks!

This will perform the correct restriction:

Sub visTest()
    Dim c As Range
    For Each c In Intersect(Selection, Selection.SpecialCells(xlCellTypeVisible))
        MsgBox c.Row
    Next c
End Sub

它返回工作表上所有已使用的单元格的原因是,与Excel中的许多其他方法一样,SpecialCells方法假定如果您指定的范围仅包含单个单元格,则您需要工作表的已使用范围

to eliminate the problem with incorrect range when using "specialCells" just put this line to the code

If Selection.Cells.Count > 1 Then Selection.SpecialCells(xlCellTypeVisible).Select End If

This way excell will use this method only when actually sellected region consists of more than one cell.

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