Excel / Excel VBA剪切和复制重置单元名称

时间:2013-04-11 14:56:51

标签: excel excel-vba vba

情况很简单,如果我将单元格A1命名为MY_CELL,然后将 CUT AND PASTE 从单元格A2命名为单元格MY_CELL ,然后MY_CELL将丢失该名称并再次命名为A1

但是,当我从A2MY_CELL COPY AND PASTE 时,就不会发生这种情况。

如何阻止Excel重置 CUT AND PASTE 上的单元格名称?

1 个答案:

答案 0 :(得分:2)

逻辑:使用A1事件捕获对单元格Worksheet_Change的更改,并在名称丢失时重新创建名称。

<强>代码

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

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

注意:相关表单的“表单”代码区域中的代码。见下面的截图。

enter image description here