文章背景: 在工作生活中,存在文件共享的情况。在数据处理时,单元格公式中往往要引用原始数据源。多人操作时,每个人的操作习惯不同,如果数据源的单元格不小心被人为移动或删除,会导致单元格公式引用失效,产生#REF! 错误。如果进行的是跨表引用
,这种错误往往还很难发现。
http://mpvideo.qpic.cn/0bf2zmabiaaatqanajhbmvqfbs6dctfqafaa.f10002.mp4?dis_k=c63776ce22f5f6c42d4ea00d2a92b284&dis_t=1663655675&vid=wxv_1943075564186042368&format_id=10002&support_redirect=0&mmversion=false
针对单元格被移动
的风险,本文通过VBA代码进行一定程度的规避。
示例:针对单个共享工作簿,关闭单元格自动填充
功能(避免单元格被移动);针对工作簿中源数据所在的工作表,禁用剪切
功能。
打开VB窗口,在ThisWorkbook
内,添加如下代码:
Option Explicit
Private Sub Workbook_Activate()
Application.CellDragAndDrop = False
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.CellDragAndDrop = True
End Sub
Private Sub Workbook_Deactivate()
Application.CellDragAndDrop = True
End Sub
在sheet(源数据)
内,添加如下代码:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'禁用剪切功能
Select Case Application.CutCopyMode
Case Is = False
'do nothing
Case Is = xlCopy
'do nothing
Case Is = xlCut
MsgBox "请不要使用 Cut and Paste;可以使用 Copy and Paste。"
Application.CutCopyMode = False 'clear clipboard and cancel cut
End Select
End Sub
代码块输入区域和运行效果展示:http://mpvideo.qpic.cn/0bf27yabkaaakaancgxbn5qfb7wdcx7aafia.f10002.mp4?dis_k=2f694323e57cf7dbe700df175483c03f&dis_t=1663655675&vid=wxv_1943077021606019073&format_id=10002&support_redirect=0&mmversion=false
参考资料:
[1] How do I completely disable drag-n-drop features in one workbook (not all) in excel (https://www.mrexcel.com/board/threads/how-do-i-completely-disable-drag-n-drop-features-in-one-workbook-not-all-in-excel.739294/)
[2] Disabling "cut" from excel with vba (https://stackoverflow.com/questions/41680490/disabling-cut-from-excel-with-vba)