PDA

View Full Version : Replacing a Carriage Return with a Tab every other paragraph



dpeisenbeisz
08-08-2017, 03:58 PM
I have a Vba routine wherein I need to remove the carriage return (vbCR, Chr(13), or ^p) from the end of every other paragraph and replace it with a tab (vbTab, Chr(9), or ^t) character. I set it up to count the paragraphs in the document and then cycle through the count with the variable updating each time by two, so that part works fine. What isn't working is when I replace the carriage return with a a tab character, it comes right back and now I just have an extra tab at the end of every other paragraph. Here's the section of code I'm working with:

Dim PGe As Integer
Dim ptext As String
Dim pmodtext As String


PGe = ActiveDocument.Paragraphs.Count
For k = 2 To PGe

Options.ReplaceSelection = True

ptext = ActiveDocument.Paragraphs(k).Range.Text
pmodtext = Replace(ptext, Chr(13), Chr(9))
ActiveDocument.Range(ActiveDocument.Paragraphs(k).Range.Start, ActiveDocument.Paragraphs(k).Range.End).Select
Selection.TypeText (pmodtext)


k = k + 1


Next k

macropod
08-08-2017, 05:40 PM
It seems to me you could get the desired result with:

Dim i As Long
With ActiveDocument
For i = .Paragraphs.Count - 1 - .Paragraphs.Count Mod 2 To 1 Step -2
.Paragraphs(i).Range.Characters.Last = vbTab
Next
End With

gmaxey
08-08-2017, 06:52 PM
Paul,

You always dazzle with your Math! Slightly modified could be used to easily process every 3rd, 4th, etc.


Sub Test()
ForEveryIndex 2
End Sub
Function ForEveryIndex(lngIndex As Long)
Dim i As Long
With ActiveDocument
For i = .Paragraphs.Count - .Paragraphs.Count Mod lngIndex To 1 Step -lngIndex
If Not .Paragraphs(i).Range.Start = .Paragraphs.Last.Range.Start Then
.Paragraphs(i).Range.Characters.Last = vbTab
End If
Next
End With
End Function

macropod
08-08-2017, 09:01 PM
:beerchug: