Search code examples
vbaobjectrangeintersect

Passing public Range variable to intersect


I created a public Range object within my worksheet and initialized it whithin Worksheet_Activate(). Afterwards I tryed to intersect the range within Worksheet_Change(ByVal Target As Range) but I can't figure out how to do it. Maybe I am doing something totally wrong or there might be an easy way to fix it.

Public myRange As Range

Private Sub Worksheet_Activate()  
Set myRange = Worksheets("Sheet1").Range("D6:D8")
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target,myRange) Is Nothing Then
"Do Something"
Else
"Do Something Differenz"
End If

End Sub

Solution

  • MyRange is set only when sheet 1 is activated, so if sheet 1 is selected when the file is first opened, myRange is not set. Rather, it would be good to put a syntax to set myRange in change_event.

    Public myRange As Range
    
    Private Sub Worksheet_Change(ByVal Target As Range)
        Set myRange = Worksheets("Sheet1").Range("D6:D8")
        If Intersect(Target, myRange) Is Nothing Then
            MsgBox "Nothing"
        Else
            MsgBox "not Nothing"
        End If
    
    End Sub