Search code examples
vbatextms-wordhyperlinkinsert

Word VBA insert plain text spaces before and after all hyperlinks


I want to add spaces after timestamps, in a transcript which pasted with no space between the timestamp hyperlinks and the surrounding text.

oLink.Range.InsertBefore " " inserts plain text, but oLink.Range.InsertAfter " " appends the added text formatted as hyperlink - which means anything typed after the space is also formatted as hyperlink text.

How do I insert a space after, in the underlying style? screenshot


Solution

  • Here's how I inserted plain text after hyperlinks

    Sub H___AddSpace_PlainTextBeforeAndAfterHyperlinks()
    
    Dim oLink As Hyperlink
    
    '======= R___PRESELECTED_RANGE_SetAndRESELECTafterLOOPS macro
    '1.===== Name pre-selected range (if LOOP is going to be executed or called on a TABLE) R___PRESELECTED_RANGE_SetAndRESELECTafterLOOPS Macro
        Dim PRESELECTED_RANGE As Range
            
        '1a.________ if no selection, msgbox select all, dont select or exit
        If Selection.Range = "" Then
            SELECT_RANGE = MsgBox("Select whole document?" & vbNewLine & _
                    "Cancel to make selection manually!" & vbNewLine & _
                    "No will run only on the selection type the cursor is in.", _
                    vbYesNoCancel + vbDefaultButton2)
                If SELECT_RANGE = vbYes Then
                    Selection.WholeStory 'selects whole document - then save selection below
                ElseIf SELECT_RANGE = vbCancel Then
                    Exit Sub
                End If 'SELECT_RANGE options (will continue with no selection made if yes or cancel not pressed)
        End If
    
        '1b.________ set preselected range
        Set PRESELECTED_RANGE = Selection.Range 'needs to be set after every preselected range dim, and after every loop
    
    
    '2.======= Loop
         For Each oLink In PRESELECTED_RANGE.Hyperlinks
    
    '2a.---- insert space before (inerts as plain text)
        oLink.Range.InsertBefore " "
    
    '2b.----- INSERT SPACE AFTER
        oLink.Range.Select
            Selection.MoveRight Unit:=wdCharacter, Count:=1 'COLLAPSES TO END
            Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend 'select following letter
            Selection.Copy 'copy following character
            Selection.TypeText Text:=" " 'type space over letter
            Selection.PasteAndFormat (wdFormatOriginalFormatting) 'paste the copied letter after the space
        
    Next oLink
    Set oLink = Nothing
    
    '3.====== reselect range for exit or next action (in MAIN macro, before LOOP macros called, +after each "next" command)
    PRESELECTED_RANGE.Select 'add after every "next" - for exit or next procedure
    
    MsgBox "done"
    End Sub