vbams-word

Paste as body text in Word Document unless it is a table


I have set up some templates where the users can copy from elsewhere and paste into the document and the pasted text will always default to body text using the script below which works great except when they want to paste a table in. I have also removed the paste options from the ribbon along with a lot of other options to control what users are able to change.

When tables are pasted in they would like to keep the formatting of a table (ideally using the destination formatting but one step at a time) From my research I have found that it is not possible to know if the copied text is a table as the clipboard doesn't store that specific information in word (unless this has changed since the posts I have read) and I have not found anything that would suggest the paste event has anything that would identify it as a table either unless it is pasted into a blank document first. I am wondering if it is possible to identify whether it is a table from the source as long as the source is still open obviously, using VBA somehow?

Nothing in my research so far has suggested it is possible identify a table is being copied/pasted but I thought I would ask anyway

Dim newText As String
    Dim clipboardText As String


Selection.TypeText vbCrLf
Selection.Style = "Body Text"

    clipboardText = GetClipboardText()

    newText = vbCrLf & clipboardText
     
    ' Applying formatting to the pasted text
    With Selection
        .Font.Bold = False
        .Font.Size = 11
        .Font.Color = wdColorBlack
        .Font.Name = "Calibri"
        .ParagraphFormat.Alignment = wdAlignParagraphLeft
        .ParagraphFormat.SpaceAfter = 1
        .Range.HighlightColorIndex = wdNoHighlight
    End With

   ' Pasting text at the current selection
    Selection.TypeText newText

Solution

  • It doesn't take all that long to execute something like this, and you might be able to do some or all of your table formatting in the temp document, perhaps (haven't checked) inserting into the actual document using .FormattedText.

    But maybe too laggy for all the times they aren't inserting a table.

    Function IncludesATable() As Boolean
    Dim d As Word.Document
    Application.ScreenUpdating = False
    On Error Goto problem
    With Application.Documents.Add(Visible:False)
      .Content.Paste
      IncludesATable = (.Content.Tables.Count > 0)
      .Close SaveChanges:=wdDoNotSaveChanges
    End With
    
    problem:
    Application.ScreenUpdating = True
    End Function
    
    ' Test routine
    Sub TableNoTable()
    If IncludesATable Then
      Selection.TypeText "There's a table."
    Else
      Selection.TypeText "There isn't a table."
    End If
    End Sub