简体   繁体   English

Selection.SpecialCells() 方法返回意外范围(Excel VBA)

[英]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".当我 select 三个单元格的范围说 B3:B5 时,该方法按预期运行并显示三个消息,分别为“3”、“4”和“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.问题是当我 select 只有一个单元格时: Selection.SpecialCells(xlCellTypeVisible)返回工作表上的所有可见单元格并从单元格 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 为了消除使用“ specialCells”时范围错误的问题,只需将这一行添加到代码中

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. 只有当实际销售的区域包含多个单元格时,excell才会使用这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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