excel vba check if named range exists code example

Example 1: excel vba test if target is a named range

'VBA inline code to test if Target is a named range:

If Not Intersect(Target, [NamedRangeName]) Is Nothing Then
    If Target.Cells.Count = [NamedRangeName].Cells.Count Then
        If Target.row = NamedRange.row Then
            If Target.Column = NamedRange.Column Then  
                'Place code here to execute when Target is
                'the named range.
            End If
        End If    
    End If
End If



'Or encapsulated into a function:

Function TargetIsNamedRange(Target As Range, NamedRange As Range) As Boolean
    If Not Intersect(Target, NamedRange) Is Nothing Then
        If Target.Cells.Count = NamedRange.Cells.Count Then
            If Target.Row = NamedRange.Row Then
                If Target.Column = NamedRange.Column Then
                    TargetIsNamedRange = True
                    Exit Function
                End If
            End If
        End If
    End If
End Function


'
'
'

Example 2: excel vba named range exists

Function NamedRangeExist(ByRef pWorkBook As Workbook, pName As String) As Boolean
    Dim nName As Name
    For Each nName In pWorkBook.Names
        If nName.Name = pName Then
            NamedRangeExist = True
            Exit Function
        End If
    Next nName
End Function

Tags:

Vb Example