情况很简单,如果我将单元格A1
命名为MY_CELL
,然后将 CUT AND PASTE 从单元格A2
命名为单元格MY_CELL
,然后MY_CELL
将丢失该名称并再次命名为A1
。
但是,当我从A2
到MY_CELL
COPY AND PASTE 时,就不会发生这种情况。
如何阻止Excel重置 CUT AND PASTE 上的单元格名称?
答案 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
注意:相关表单的“表单”代码区域中的代码。见下面的截图。