10

我需要查找屏幕上是否可见单元格。

可见,我不是说隐藏。我特别想找出一个单元格当前是否显示在活动工作表中,或者它是否未显示,即:它已从可见活动工作表中滚动出来。

我在网上看了,只能找到以下似乎对我不起作用的代码:

Private Sub CommandButton1_Click()
    With Worksheets(1).Cells(10, 10)
        'MsgBox "Value: " & .Value & ", Top: " & .Top & ", Left: " & .Left
        Dim visibleCells As Range
        Set visibleCells = Range("A1").CurrentRegion.SpecialCells(xlCellTypeVisible)
        If Intersect(Worksheets(1).Cells(10, 10), visibleCells) Is Nothing Then
            MsgBox "This cell is not visible."
        End If
    End With
End Sub

在此先感谢您的帮助,

马旺

4

2 回答 2

17

这是一个可以满足您要求的功能:

Function CellIsInVisibleRange(cell As Range)
CellIsInVisibleRange = Not Intersect(ActiveWindow.VisibleRange, cell) Is Nothing
End Function

至少我认为是的。直到现在我才知道 VisibleRange 属性。

像这样称呼它:

If CellIsInVisibleRange(ActiveSheet.Range("A35")) Then
    MsgBox "Cell is visible"
Else
    MsgBox "Cell isn't visible"
End If
于 2012-08-13T22:35:52.033 回答
1

@DougGlancy 的函数在大多数情况下都可以使用,但如果 R​​ange 的行高或列宽设置为零,它会失败。此函数添加了处理该问题的逻辑以及一些错误处理。

Function Range_IsVisibleInWindow(ByVal target As Excel.Range) As Boolean
' Returns TRUE if any cell in TARGET (Range) is visible in the Excel window.
'
'   Visible means (1) not hidden, (2) does not have row height or column width of
'   zero, (3) the view is scrolled so that the Range can be seen by the user at
'   that moment.
'
'   A partially visible cell will also return TRUE.

    If target Is Nothing Then
        ' Parameter is invalid.  Raise error.
        Err.Raise 3672, _
                  "Range_IsVisibleInWindow()", _
                  "Invalid parameter in procedure 'Range_IsVisible'."

    Else
        ' Parameter is valid.  Check if the Range is visible.
        Dim visibleWinLarge As Excel.Range
        Dim visibleWinActual As Excel.Range

        On Error Resume Next
        Set visibleWinLarge = Excel.ActiveWindow.VisibleRange ' active window range -INCLUDING- areas with zero column width/height
        Set visibleWinActual = visibleWinLarge.SpecialCells(xlCellTypeVisible) ' active window range -EXCLUDING- areas with zero column width/height
        Range_IsVisibleInWindow = Not Intersect(target, visibleWinActual) Is Nothing ' returns TRUE if at least one cell in TARGET is currently visible on screen
        On Error GoTo 0

    End If
End Function
于 2019-06-15T01:52:09.370 回答