vbams-word

How to prevent styles from being introduced into the destination document when pasting from other documents?


I have set up a MS Word Document (.docx) for my colleagues to use with boilerplate text and neatly sorted styles to choose from the style gallery. Problem is, they often paste from other documents thereby introducing new styles into the template. Restricting them to a few styles via the formatting restrictions is no option since this also disables font formatting. The following code (partly taken from this question) kinda does what I want but might there be a better option?

Sub EditPaste()
'PURPOSE: Prevent styles from other documents from being introduced into this document.
    
    Dim k As Long

    k = ActiveDocument.Styles.Count
    
    Selection.Range.Paste
    If k <> ActiveDocument.Styles.Count Then
        ActiveDocument.Undo
        On Error GoTo F
            Selection.PasteSpecial Link:=False, _
            DataType:=wdPasteText, Placement:=wdInLine, _
            DisplayAsIcon:=False
    Exit Sub

F:  MsgBox ("An error has occurred.")
    End If

End Sub

Solution

  • I wouldn't intercept the standard paste command. Pasting formatted content like tables or fields won't work. Instead, use a macro that has an alternate key combination like Alt + V to run a macro like this:

    Sub PasteUnformattedText()
      On Error GoTo ClipboardNotText
        Selection.PasteSpecial DataType:=wdPasteText
        Exit Sub
    ClipboardNotText:
      Err.Clear
      On Error GoTo ClipboardNotUnicodeText
      Selection.PasteSpecial DataType:=22 'Paste Unicode Text
      Exit Sub
    ClipboardNotUnicodeText:
      Selection.Paste
      Err.Clear
    End Sub