In my workbook, I am trying to make it so if the user pastes any data from another cell in the workbook (or from another workbook), it will only paste the values from the original cell(s), but nothing else, such as the formatting, borders, cell background color, etc. I found some code in another forum for doing this:
https://stackoverflow.com/questions/34800859/excel-vba-always-paste-values-only
I put the code in the ThisWorkbook module, in the Workbook_SheetChange sub, because I want it to apply to ALL sheets of the workbook.
Here’s the code:
The code works exactly as it should if I try to copy & paste data within the same worksheet. BUT, if I copy a cell on one worksheet, and then paste it onto the cell in a different worksheet (inside the same workbook), it does not paste only the values. It also pastes the number formatting, background color, etc.
How can I make it so no matter what sheet in my workbook I am on, the paste function will only ever paste the value, and nothing else?
https://stackoverflow.com/questions/34800859/excel-vba-always-paste-values-only
I put the code in the ThisWorkbook module, in the Workbook_SheetChange sub, because I want it to apply to ALL sheets of the workbook.
Here’s the code:
Code:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim UndoList As String
Application.ScreenUpdating = False
Application.EnableEvents = False
On Error GoTo Whoa
If Application.CommandBars("Standard").Controls("&Undo").Enabled = True Then
'~~> Get the undo List to capture the last action performed by user
UndoList = Application.CommandBars("Standard").Controls("&Undo").List(1)
'~~> Check if the last action was not a paste nor an autofill
If Left(UndoList, 5) <> "Paste" And UndoList <> "Auto Fill" _
Then GoTo LetsContinue
'~~> Undo the paste that the user did but we are not clearing the
'~~> clipboard so the copied data is still in memory
Application.Undo
If UndoList = "Auto Fill" Then Selection.Copy
'~~> Do a pastespecial to preserve formats
On Error Resume Next
'~~> Handle text data copied from a website
Target.Select
ActiveSheet.PasteSpecial Format:="Text", Link:=False, _
DisplayAsIcon:=False
Target.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
On Error GoTo 0
'~~> Retain selection of the pasted data
Union(Target, Selection).Select
End If
LetsContinue:
Application.ScreenUpdating = True
Application.EnableEvents = True
On Error GoTo 0
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
The code works exactly as it should if I try to copy & paste data within the same worksheet. BUT, if I copy a cell on one worksheet, and then paste it onto the cell in a different worksheet (inside the same workbook), it does not paste only the values. It also pastes the number formatting, background color, etc.
How can I make it so no matter what sheet in my workbook I am on, the paste function will only ever paste the value, and nothing else?
Last edited: