excel剪切、复制和粘贴操作,使它们不会破坏已设置的单元格格式
时间:2023-01-25 22:03:24
基于表格的用户接口的最大问题是:由于采用Excel黙认方式来处理数据的剪切、复制、粘贴以及拖放,而数据输入表中大多数用于编辑的单元格都被指定了特定样式、数据验证或条件格式,因此Excel默认的复制/粘贴会覆盖掉被粘贴单元格中的各种格式,同时Excel默认的剪切方式会将被剪切单元格的格式设置为“通用样式”。Excel的拖放功能也与剪切/复制类似,同样会破坏单元格中的格式。
为避免发生上述情况,可以屏蔽Excel的拖放功能,并编写自已的剪切、复制和粘贴程序。
Dim mbCut As Boolean
Dim mrngSource As Range
‘初始化单元格的复制-粘贴
Public Sub InitCutCopyPaste()
Application.OnKey “^X”, “DoCut”
Application.OnKey “^x”, “DoCut”
Application.OnKey “+{DEL}”, “DoCut”
Application.OnKey “^C”, “DoCopy”
Application.OnKey “^c”, “DoCopy”
Application.OnKey “^{INSERT}”, “DoCopy”
Application.OnKey “^V”, “DoPaste”
Application.OnKey “^v”, “DoPaste”
Application.OnKey “+{INSERT}”, “DoPaste”
Application.OnKey “{ENTER}”, “DoPaste”
Application.OnKey “~”,”DoPaste”
‘关闭拖放操作
Application.CellDragAndDrop = False
End Sub
‘处理剪切单元格
Public Sub DoCut()
If TypeOf Selection Is Range Then
mbCut = True
Set mrngSource = Selection
Selection.Copy
Else
Set mrngSource = Nothing
Selection.Cut
End If
End Sub
‘处理复制单元格
Public Sub DoCopy()
If TypeOf Selection Is Range Then
mbCut = False
Set mrngSource = Selection
Else
Set mrngSource = Nothing
End If
Selection.Copy
End Sub
‘处理粘贴单元格
Public Sub DoPaste()
If Application.CutCopyMode And Not mrngSource Is Nothing Then
Selection.PasteSpecial xlValues
If mbCut Then
mrngSource.ClearContents
End If
Application.CutCopyMode = False
Else
ActiveSheet.Paste
End If
End Sub
将上述代码复制到VBE中,试着运行并熟悉其原理。可以将上述程序嵌入到你正在开发的应用程序的合适位置,结合实际稍作调整,使应用程序更健壮。