How to delete of paragraph of spaces with VBA?

Word 2010 (just starting VBA coding)

Word Document First Paragraph has 20 spaces and a paragraph sign; I would like to delete this paragraph under VBA control.

My code:

 

Dim MyText as String

     Set MyRangePP = ActiveDocument.Range(Start:=ActiveDocument.Paragraphs(1).Range.Start, _
                                                                           End:=ActiveDocument.Paragraphs(1).Range.End)
     MyText = MyRangePP.Text
     If MyText = "                    " Then
          Selection.EndKey Unit:=wdLine, Extend:=wdExtend
          Selection.Delete Unit:=wdCharacter, Count:=1
    End If

 

A breakpoint is placed on the

      If MyText = "                   " Then

statement.

I examine the value of MyText and it displays "                    " in the popup window as expected.

However, the statements within the If - End If block are not executed.

Any guidance would be very much appreciated.

Thanks...

 

Answer
Answer

You can shorten

 

     Set MyRangePP = ActiveDocument.Range(Start:=ActiveDocument.Paragraphs(1).Range.Start, _
                                                                           End:=ActiveDocument.Paragraphs(1).Range.End)

 

to

 

     Set MyRangePP = ActiveDocument.Paragraphs(1).Range

 

The text of this range will include the paragraph marker at the end (vbCr = character with code 13).

Instead of a string with 20 spaces (hard to count, so easy to make a mistake), you can use Space(20).

To delete the paragraph, you don't have to select it. Simply use MyRangePP.Delete.

So the code becomes:

 

Sub Test()
    Dim MyText As String
    Dim MyRangePP As Range

    Set MyRangePP = ActiveDocument.Paragraphs(1).Range
    MyText = MyRangePP.Text
    If MyText = Space(20) & vbCr Then
        MyRangePP.Delete
    End If
End Sub

---
Best wishes, HansV
https://www.eileenslounge.com

Was this reply helpful?

Sorry this didn't help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

 
 

Question Info


Last updated October 5, 2021 Views 2,329 Applies to: