Microsoft Word Select Specific Range and Delete VBA

Microsoft Word Select Specific Range and Delete VBA

Delete

Method deletes specific range text which is under selection. In this article we will try to delete selection using code.

Syntax

Selection.Delete(unit, count)

  1. Unit: An optional parameter, The unit by which the collapsed selection is to be deleted. Can be one of the WdUnits constants as wdItem, wdLine, wdParagraph etc.
  2. Count: An optional variable, determines number of units to be deleted from selected range.

Example

Consider following line in a word document where we will delete first three characters from the selection:

Code example

Sub DeleteSelection()
    'bind selection
    Dim oSelection As Selection
    Set oSelection = Selection
    
    'Perform delete first 3 chars
    Dim oResult As Long
    oResult = oSelection.Delete(unit:=wdCharacter, Count:=3)
    
    MsgBox "You have delete " & oResult & " Characters from current selection"
    
    'Memory cleanup
    Set oSelection = Nothing
End Sub

Output

Next >> Understand Custom Dictionary in Word using VBA code example

Leave a Reply

Your email address will not be published.