Home » excel » Excel/Excel VBA cut and copy resets cell name

Excel/Excel VBA cut and copy resets cell name

Posted by: admin April 23, 2020 Leave a comment


The situation is simple, if I name cell A1 to be MY_CELL and then CUT AND PASTE from cell A2 to cell MY_CELL, then MY_CELL will lose that name and be named A1 again.

However, this does not happen when I COPY AND PASTE from A2 to MY_CELL.

How can I prevent Excel from resetting cell names on CUT AND PASTE?

How to&Answers:

Logic: Trap the changes to Cell A1 using the Worksheet_Change event and recreate the name if it is lost.


Private Sub Worksheet_Change(ByVal Target As Range)
    Dim DoesRngNameExists As Boolean
    Dim sName As String

    On Error GoTo Whoa

    Application.EnableEvents = False

    '~~> You named range
    sName = "MY_CELL"

    If Not Intersect(Target, Range("A1")) Is Nothing Then
        '~~> Check if the Range exists
        On Error Resume Next
        DoesRngNameExists = Len(Names(sName).Name) <> 0
        On Error GoTo 0

        '~~> If not then recreate it
        If DoesRngNameExists = False Then _
        ThisWorkbook.Names.Add Name:=sName, RefersToR1C1:="=Sheet1!R1C1"
    End If

    Application.EnableEvents = True
    Exit Sub
    MsgBox Err.Description
    Resume Letscontinue
End Sub

Note: The codes in the Sheet code area of the relevant sheet. See screenshot below.

enter image description here