Home > other >  Including the Table Column with name but getting an error
Including the Table Column with name but getting an error

Time:12-29

I am trying to Include the Table Column with name but getting an error Scrupt out of Range I do not know why. Your help will be much appreciated.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Dim userSelectedDate As Date
    Dim DateRange As Range
    
    DateRange = ActiveSheet.ListObjects("T_EMP").ListColumns("[START DATE]").DataBodyRange
            
    'Show calendar form if selected cell falls within "DateRange" named range
    If Not Intersect(ActiveCell, Sheet2.Range("DateRange")) Is Nothing Then
        If IsDate(ActiveCell.value) Then userSelectedDate = ActiveCell.value
    
        'Call CalendarForm
        userSelectedDate = CalendarForm.GetDate(SelectedDate:=userSelectedDate)
            
        'Make sure user selected a valid date from the CalendarForm
        If userSelectedDate <> 0 Then ActiveCell.value = userSelectedDate
    End If
    
End Sub

CodePudding user response:

  • You're missing Set: Set DateRange = ....
  • Variables don't belong inside quotes, and you already have a Range variable: DateRange, not Sheet2.Range("DateRange")
  • Use Target and Me in place of ActiveCell and ActiveSheet.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.CountLarge > 1 Then Exit Sub ' only proceed if one cell selected

    Dim userSelectedDate As Date
    Dim DateRange As Range
    
    Set DateRange = Me.ListObjects("T_EMP").ListColumns("[START DATE]").DataBodyRange
            
    'Show calendar form if selected cell falls within "DateRange" named range
    If Not Intersect(Target, DateRange) Is Nothing Then
        If IsDate(Target.Value) Then userSelectedDate = Target.Value
    
        'Call CalendarForm
        userSelectedDate = CalendarForm.GetDate(SelectedDate:=userSelectedDate)
            
        'Make sure user selected a valid date from the CalendarForm
        If userSelectedDate <> 0 Then Target.Value = userSelectedDate
    End If
    
End Sub
  • Related