0
votes

I've got a macro written to add parentheses around a sentence in Microsoft Word:

Sub AddParentheses()
 Dim iCount As Integer
 iCount = 1
 While Right(Selection.Text, 1) = " " Or _
 Right(Selection.Text, 1) = Chr(13)
 Selection.MoveLeft Unit:=wdCharacter, Count:=1, _
  Extend:=wdExtend
 iCount = iCount + 1
 Wend

 Selection.InsertAfter ")"
 Selection.InsertBefore "("
 Selection.MoveRight Unit:=wdCharacter, Count:=iCount
End Sub

It works great when I select only a sentence and run it, but if I accidentally highlight a paragraph break at the end of the sentence, the macro starts slowly highlighting everything in the document, moving from the beginning of my selection to the beginning of the whole document, which invariably crashes the program.

Can anyone point me in the direction of a solution?

2

2 Answers

0
votes

The default value assigned by VBA is short integer, this goes from -32,768 to 32,767. I think that if a lot of white spaces are found in your selection, the counter does not go beyond that value, so the method stays hanged in in infinite while.

Try out UInteger or Ulong:

Dim ULong As iCount
iCount = 1

Or you can try handling the exception when the counter reaches a certain point warning the user.

Hope that helps

0
votes

Your request shows that you have not read and understood the MS help pages for Selection.InsertAfter and Selection.InsertBefore.

In the VBA IDE you put the cursor on a keyword and press F1. This brings up the help page for the Keyword (VBA or Office object models) if one is available.

If you had read these help pages you would know that the behaviour of InsertAfter is different depending on whether or not the range includes an end of paragraph marker.

There is example code in the help pages that shows how to deal with this difference in behaviour.