menteith
menteith

Reputation: 678

Add characters before and after selection using VBA

I tried to write a macro to would add a certain character before a selected text in Word. This works fine. I'd like to add one more feature. When no selection is made the macro should select a word where the cursor is and then add a certain character.

I have the following code:

Sub AddChar()
If Len(Trim(selection.Text)) >= 1 Then
    Trim (selection.Text)
    selection.InsertBefore Chr(187)
    selection.InsertAfter Chr(171)
Else
selection.Words(1).Select
selection.InsertBefore Chr(187)
selection.InsertAfter Chr(171)
End If
End Sub

Upvotes: 0

Views: 1393

Answers (1)

user1379931
user1379931

Reputation:

I am assuming that your question is about the case where you have a "point" selection.

When you have a "point" selection, although it looks as if nothing is selected, the Selection object actually contains the character after the insertion point (you can check by typing

?Selection

in the Visual Basic Editor's Immediate window)

So the problem is that the selection will still have a length of 1, so your initial test

If Len(Trim(selection.Text)) >= 1 Then

will not work.

What you need to do is check the Selection.Type. You will find that the Object Browser lists several types, but for example the following code will solve the immediate problem:

If Selection.Type = wdSelectionType.wdSelectionIP Then
  ' code for a "point" selection
Else
  ' code for the case where something is already selected
End If

Upvotes: 1

Related Questions