从Word文档中删除前导空格

时间:2013-03-22 02:20:07

标签: ms-word word-vba

如何从Word文档的第一页删除所有前导空格(空格,空行)?

1 个答案:

答案 0 :(得分:1)

编辑:事实证明我想要的是从文档的开头删除所有空段落或仅由空格组成的段落。以下宏DeleteLeadingWhitespace执行此操作并保留格式。

' return True if the character at the given position is a whitespace character.
' codepoints courtesy of http://en.wikipedia.org/wiki/Whitespace_character#Unicode
Function IsSpace(ByVal Text As String, Optional ByVal Position As Long = 1)

    Select Case AscW(Mid(Text, Position, 1))
        Case &H9, &HA, &HB, &HC, &HD, &H20, &H85, &HA0, _
                &H1680, &H180E, &H2000, &H2001, &H2002, &H2003, &H2004, &H2005, &H2006, _
                &H2007, &H2008, &H2009, &H200A, &H2028, &H2029, &H202F, &H205F, &H3000
            IsSpace = True

        Case Else
            IsSpace = False
    End Select

End Function

' return True if the paragraph consists only of whitespace
Function IsParagraphEmpty(ByVal pg As Paragraph)

    Dim i As Long

    For i = 1 To Len(pg.Range.Text)
        If Not IsSpace(pg.Range.Text, i) Then
            IsParagraphEmpty = False
            Exit Function
        End If
    Next

    IsParagraphEmpty = True
End Function

' delete leading whitespace from the given document.
Sub DeleteLeadingWhitespaceFrom(ByVal Document As Document)

    While IsParagraphEmpty(Document.Paragraphs.First)
        Dim i As Long
        i = Document.Paragraphs.Count

        Document.Paragraphs.First.Range.Delete

        ' no change in number of paragraphs, bail
        If i = Document.Paragraphs.Count Then Exit Sub

    Wend

End Sub

' macro: delete leading whitespace from the active document
Sub DeleteLeadingWhitespace()

    DeleteLeadingWhitespaceFrom ActiveDocument

End Sub