VBA MS Word - How do I find a tab that's only at the beginning of a line and replace it with nothing?

I need to take tabs and remove them if they are at the beginning of a line in MS word. I have to do this...a lot. It looks like a battlefield of tab characters.


Example               

I have a script that finds the numbers and makes it pretty. The script just ignores lines when they start with a tab character. I found I'm doing this in many documents that I'm translating to a new format for the company. Any ideas? My guess is that it's simple but I just don't know the VBA vocabulary to do it.

Thanks for your help!

Answer
Answer

Try this. The first paragraph is treated separately.

Sub RemoveLeadingTabs()
    If ActiveDocument.Range(0, 1).Text = vbTab Then
        ActiveDocument.Range(0, 1).Delete
    End If
    With ActiveDocument.Content.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "^p^w"
        .Replacement.Text = "^p"
        .Forward = True
        .Wrap = wdFindStop
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute Replace:=wdReplaceAll
    End With
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.

Answer
Answer

A more comprehensive approach is to use a wildcard Find/Replace, where:

Find = ([^13^l])^t

Replace = \1

The other solutions you've been offered work only if the new line is preceded by a paragraph break; the above handles manual line breaks as well. As a Find/Replace, neither the above nor Suzanne's will do anything with the first paragraph in the document. For that, you need a macro like the one Hans posted:

Sub RemoveLeadingTabs()
Application.ScreenUpdating = False
With ActiveDocument.Range
  .InsertParagraphBefore
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "([^13^l])^t"
    .Replacement.Text = "\1"
    .Forward = True
    .Format = False
    .MatchWildcards = True
    .Wrap = wdFindContinue
    .Execute Replace:=wdReplaceAll
    End With
    .Characters.First.Text = vbNullString
End With
Application.ScreenUpdating = True
End Sub

Cheers
Paul Edstein
(Fmr MS MVP - Word)

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,449 Applies to: