如何确定工作表单元格在VBA中是否可见/显示?

时间:2012-08-13 22:27:18

标签: excel excel-vba vba

我需要查看屏幕上是否有可见的单元格。

通过可见,我并不是说隐藏。我特意试图查找某个单元格当前是否显示在活动工作表中,或者是否未显示,即:它已从可见活动工作表中滚动。

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

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

先谢谢你的帮助,

马尔

2 个答案:

答案 0 :(得分:16)

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

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

答案 1 :(得分:1)

@DougGlancy中的函数将在大多数情况下起作用,但是如果Range将行高或列宽设置为零,则该函数将失败。此功能添加了用于处理该问题的逻辑以及一些错误处理。

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