Search code examples
excelvbanamed-ranges

Name a Cell Range After Checking it Doesn't Have a Range Name


I'm trying to cycle through a selection of cells and rename those cells based on text values on the spreadsheet.

Sub naming()

    Dim cel As Range
    Dim selectedRange As Range
    Dim to_offset As Integer

    Set selectedRange = Application.Selection

    Answer = InputBox("Column Where Named Are?")
    col_number = Range(Answer & 1).Column

    For Each cel In selectedRange.Cells
        cel.Name.Delete
        to_offset = col_number - cel.Column
        cel.Name = cel.Offset(0, to_offset).Value
    Next cel

End Sub

The delete command is the problem - so I thought I'd check for names using Len() but get a 1004 error.

If there are no names already defined for the cell it works (but I can't leave the delete code in).
If there are names already defined for the cell it works (and I use the delete).

I need to use the delete for existing names - but have it step over blank names.


Solution

  • A quick and dirty way would be to wrap the line in question between On Error Resume Next and On Error Goto 0, so the code would look like that

        On Error Resume Next   'skip line in case of an error
        cel.Name.Delete
        On Error GoTo 0        'reset error handling
    

    Using On Error Resume Next tells VBA to ignore the error and continue on. There are specific occasions when this is useful. Most of the time you should avoid using it. I think this might be a case where you could use it.

    Or you wrap the code in a sub

    Sub deleteName(rg As Range)
    
        On Error GoTo EH
        rg.Name.Delete
        
        Exit Sub
    
    EH:
        
    End Sub
    

    and use it like that

    For Each cel In selectedRange.Cells
            deleteName cel
            to_offset = col_number - cel.Column
            cel.Name = cel.Offset(0, to_offset).Value
    Next cel
    

    But in this case this is IMHO not much of a difference.

    Further reading on Error handling