View Single Post
 
Old 07-15-2016, 05:22 PM
Guessed's Avatar
Guessed Guessed is offline Windows 10 Office 2013
Expert
 
Join Date: Mar 2010
Location: Canberra/Melbourne Australia
Posts: 4,176
Guessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant future
Default

You can either ignore the error and then test for
strPrevChar is Nothing

or test if
Selection.Range.Start > 0

Rather than testing every character that way, it is more efficient to ensure your range won't throw that error before the loop begins.
Code:
Sub wtf()
  Dim rng As Range
  Set rng = Selection.Range
  If rng.Start = 0 Then rng.MoveStart Unit:=wdCharacter, Count:=1
  If rng.End = ActiveDocument.Range.End Then rng.MoveEnd Unit:=wdCharacter, Count:=-1
  For Each strChar In rng.Characters
      Set strPrevChar = strChar.Previous(wdCharacter, 1)
      Set strNextChar = strChar.Next(wdCharacter, 1)
      If strPrevChar <> "!" Then
        ' Perform the operation
      End If
  Next strChar
End Sub
__________________
Andrew Lockton
Chrysalis Design, Melbourne Australia
Reply With Quote