基于表格的用戶接口的最大問題是:由于采用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中,試著運行并熟悉其原理。可以將上述程序嵌入到你正在開發的應用程序的合適位置,結合實際稍作調整,使應用程序更健壯。