Home » excel » vba – Run an Excel macro if cell "A500" gets visible / on screen

vba – Run an Excel macro if cell "A500" gets visible / on screen

Posted by: admin May 14, 2020 Leave a comment


I’d like to get an Excel macro running as soon as cell “A500”
becomes visible on the screen when scrolling down/up the worksheet.

I remember reading somewhere about an active-x or standard control
that has an “on scrolling into view” event, so this could be done
by placing a control directly on the worksheet near the desired cell.
Finding this control currently eludes me.

A better way of course would be a cell formula, subclassing still is
a bad idea in the long run i guess 🙂

Sub temp_01() 'Excel Vba

'user scrolls down from cell "A1"

'when the user reaches cell "A500" show the following message:
MsgBox "Chapter 2"

End Sub
How to&Answers:

As mentioned above, with the help of the Onupdate event, (catches the mousewheel, not clicking on the scrollbars) (Change Sheetname(s) and Range(s) to yours)

In Class called ClsMonitorOnupdate:

Option Explicit

Private WithEvents objCommandBars As Office.CommandBars
Private rMonitor As Range
Private scrol As Boolean

Public Property Set Range(ByRef r As Range): Set rMonitor = r: End Property

Public Property Get Range() As Range: Set Range = rMonitor: End Property

Private Sub Class_Initialize()
    Set objCommandBars = Application.CommandBars
End Sub

Private Sub Class_Terminate()
    Set objCommandBars = Nothing
End Sub

Private Sub objCommandBars_OnUpdate()
Dim myrng As Range
    If ActiveWorkbook.Name <> ThisWorkbook.Name Then Exit Sub
    If ActiveSheet.Name <> rMonitor.Parent.Name Then Exit Sub
    If TypeName(Selection) <> "Range" Then Exit Sub
    If Intersect(Selection, rMonitor) Is Nothing Then Exit Sub

    Set myrng = Application.Intersect(ActiveWindow.VisibleRange, ActiveSheet.Range("a500"))

    If Not myrng Is Nothing And Not scrol Then scrol = True: MsgBox "chapter"
    If myrng Is Nothing And scrol Then scrol = False

 End Sub

In the ThisWorkbook section:

Option Explicit
Private sRanges As String
Private cMonitor As ClsMonitorOnupdate

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Set cMonitor = Nothing
End Sub
Private Sub Workbook_Open()
  Zetaan ActiveSheet
End Sub
Sub Zetuit()
 Set cMonitor = Nothing
End Sub
Sub Zetaan(sht As Worksheet)
    Select Case sht.Name
        Case "Sheet1": sRanges = "A1:ZZ1000"
        Case "Other Sheet": sRanges = "A1:ZZ1000"
        Case Else: Exit Sub
    End Select
     Set cMonitor = New ClsMonitorOnupdate
    Set cMonitor.Range = Sheets(sht.Name).Range(sRanges)
End Sub
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Zetaan Sh
End Sub
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Set cMonitor = Nothing
End Sub