So have to check, otherwise will get run error.
Checking to see if something exists usually will generate an error if it
doesn't, so you simply need to plan for the error. Here's one approach among
several. This one depends on "On Error Resume Next" being in effect *at
least* for the line "nm = ...", to avoid the error if Name doesn't exist.
You can turn any "regular" error handling back on *after* that, if desired.
***********************************
Sub SomeCode
On Error GoTo ErrHandler
Dim nm As String
......Other Code
On Error Resume Next
nm = ThisWorkbook.Names("TestRange").RefersTo
On Error GoTo ErrHandler
If Len(nm) = 0 Then
' Doesn't exist. Add it
ThisWorkbook.Names.Add Name:="TestRange", RefersToR1C1:"=Sheet1!R1C1"
Else
' Does exist. Delete it
ThisWorkbook.Names("TestRange").Delete
End If
.....More Code
ExitHere:
Exit Sub
ErrHandler:
MsgBox Err.Number & " " & Err.Description, "ERROR!"
Resume ExitHere
End Sub
******************************************************
HTH,