Consulting

Results 1 to 4 of 4

Thread: Replacing a Carriage Return with a Tab every other paragraph

  1. #1

    Replacing a Carriage Return with a Tab every other paragraph

    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

  2. #2
    Knowledge Base Approver VBAX Guru macropod's Avatar
    Joined
    Jul 2008
    Posts
    4,435
    Location
    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
    Cheers
    Paul Edstein
    [Fmr MS MVP - Word]

  3. #3
    Microsoft Word MVP 2003-2009 VBAX Guru gmaxey's Avatar
    Joined
    Sep 2005
    Posts
    3,335
    Location
    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
    Greg

    Visit my website: http://gregmaxey.com

  4. #4
    Knowledge Base Approver VBAX Guru macropod's Avatar
    Joined
    Jul 2008
    Posts
    4,435
    Location
    Cheers
    Paul Edstein
    [Fmr MS MVP - Word]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •