When your code comes across a content control field, it reads the first character in the paragraph as an empty string. This behavior can be observed by checking the oChar.First.Text
field in the local variables window. Asc()
will throw an error when passed an empty string. This can be easily reproduced by running this procedure.
Sub throwError5()
Debug.Print Asc("")
End Sub
You will need to test the value of oChar(var) to ensure it is not an empty string prior to returning its ASCII value.
Option Explicit
Sub deleteEmptyParagraphs()
Dim oPara As Word.Paragraph
Dim var
Dim SpaceTabCounter As Long
Dim oChar As Word.Characters
For Each oPara In ActiveDocument.Paragraphs
If Len(oPara.Range) = 1 Then
oPara.Range.Delete
Else
SpaceTabCounter = 0
Set oChar = oPara.Range.Characters
For var = 1 To oChar.Count
If oChar(var) <> "" Then ' stops Asc from throwing runtime error 5
Select Case Asc(oChar(var)) ' no more errrors!
Case 32, 9
SpaceTabCounter = SpaceTabCounter + 1
End Select
End If
Next
If SpaceTabCounter + 1 = Len(oPara.Range) Then
' paragraph contains ONLY spaces
oPara.Range.Delete
End If
End If
Next
End Sub
I don't work with the Word object model often, so I have no idea why the fields' first character is an empty string. Please note that my comment about having to call oChar(index).Text
was wrong. Text is the default property of a characters item.