View Single Post
 
Old 06-02-2022, 06:32 AM
Bikram Bikram is offline Windows 10 Office 2007
Advanced Beginner
 
Join Date: Jul 2021
Location: Nepal
Posts: 94
Bikram is on a distinguished road
Default I have a code in vba to delete trailing spaces but it is deleting others text too.

Code:
Sub Remove_Trailing_spaces()
  Dim i As Integer, rng As Range, d As Integer, e As Integer, para As Paragraph
For e = 1 To ActiveDocument.Paragraphs.Count
Set para = Selection.Paragraphs(1)
'On Error Resume Next
With para.Range
    Select Case para.Range.words(1).Text
        Case "Now", "So", "Again", "Also", "Given", "Here", "Then", "Let"


        Case "or", "Or", "i", "ii", "iii", "iv", "v", "vi", "vii", "vii", "a", "b", "c", "d", "e", "f", "g", "&", " "

            d = para.Range.words(1).Characters.Count

            If .Characters(d).Next.Text = "." Or .Characters(d).Next.Text = ")" Or .Characters(d).Next.Text = "," Then
            d = d + 2
            End If
            If .words(2).Text <> "," Then
                For i = d To .Characters.Count
                    If .Characters(d).Text = " " Or .Characters(i).Text = Chr(9) Then
                        .Characters(i).Delete
                        If i = 10 Then Exit For
                    Else
                       Exit For
                    End If
                Next
             Else
             For i = d To .Characters.Count
                    If .Characters(i).Text = " " Or .Characters(i).Text = Chr(9) Then
                        .Characters(i).Delete
                        i = d
                        If i = 10 Then Exit For
                    Else
                        .Characters(d).InsertAfter vbTab
                       Exit For
                    End If
                Next
            End If
    Case Chr(40), Chr(38)
        For i = d To .Characters.Count
                   If .Characters(i).Text = " " Or .Characters(i).Text = Chr(9) Then
                        .Characters(i).Delete
                        If i = 10 Then Exit For
                    Else
                        Exit For
                    End If
                Next
        .Characters(1).InsertAfter vbTab

    Case Else

       
        If .words(1) <> "vbtab" Then
        .words.First.InsertBefore vbTab

        End If

    End Select
End With
Next

End Sub
It works fine for some documents and does not work in the same way for others. I have attached the document where I ran the code. Plz, Check it out.
Any other feedback on this code will be welcomed.
Attached Files
File Type: docx sample.docx (13.4 KB, 11 views)

Last edited by Bikram; 06-03-2022 at 05:57 AM.
Reply With Quote