Delete blank lines

D

Deejay

I'm trying to delete some blank lines in my document which are above a
bookmark. I want the macro to count the number of blank lines immediately
above the bookmark till the line that contains text. If there is more than 1
blank line it should delete it/them so as to leave a single blank line.

Many thanks.
 
J

Jay Freedman

<lecture> Before getting to the code, I want to say that in Word, having
empty paragraph marks as "blank lines" is a really bad idea. It messes up
the use of styles, the "keep with next" paragraph property, and any number
of other things. Instead, you should be designing your styles to use the
Space Before and Space After settings to provide visual space with _no_
empty paragraph marks. It's only when you're dealing with files that are
meant for other purposes (such as text files that will be stored in a
database) that two paragraph marks together become unavoidably necessary.
</lecture>

You don't really need to count the number of blank lines, you just need to
know when there are more than one. Further, one blank line is created by two
consecutive paragraph marks (represented by the VBA constant vbCr).

This macro starts by assigning a Range object (myRg) to hold the range of
the bookmark (which I supposed to have the name "bk1"). I collapse myRg to
the beginning of the bookmark, and then extend the start of myRg backward
until the preceding character is no longer a paragraph mark. That leaves the
range covering all the consecutive paragraph marks that immediately precede
the bookmark. If the length of that range is more than two characters, I set
the text of the range to two paragraph marks.

Sub demo()
Dim myRg As Range

If ActiveDocument.Bookmarks.Exists("bk1") Then
Set myRg = ActiveDocument.Bookmarks("bk1").Range
With myRg
.Collapse wdCollapseStart
.MoveStartWhile cset:=vbCr, Count:=wdBackward
If .Characters.Count > 2 Then
.Text = vbCr & vbCr
End If
End With
End If
End Sub

Unfortunately this simple code will alter the bookmark. If you need the
bookmark to stay put for later processing, post back.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 
D

Deejay

Thank you and I note your points. The problem is that the document I'm
working with is prepared as pre formatted letters by a case manager program
and I have not control over blank lines. Therefore the only recourse I have
is to eliminate them by macro.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top