How can I find lines with very wide spaces in a Word document in VBA?
How do I find all the lines that have very wide spaces because of the width alignment, like in the picture?
2 answers
You need to look not for spaces (they are the most common), but for the reason for this behavior of the string. In particular, in this case, the stretching of the line seems to occur because the line ends with a line feed character (indicated by the number 2 in the figure) instead of a paragraph end character (indicated by the number 1). The line itself with such a stretch is marked with an arrow.
To see the difference visually, enable the display mode for non-printable characters. the icon.
If you want to search for these characters programmatically, via VBA, then the newline character has the notation vbLf
, and the paragraph character vbCrLf
' Поиск строк с низкой заполненностью
Sub CheckLowFillLines()
Dim Doc As Document
Set Doc = ActiveDocument
Dim WordApp As Application
Set WordApp = Application
LowFillThreshold = 61
Dim R1 As Range
Set R1 = Doc.GoTo(wdGoToLine, wdGoToFirst)
R1.Select
WordApp.Selection.Expand wdLine
Do While WordApp.Selection.MoveDown(wdLine, 1) = 1
WordApp.Selection.Expand wdLine
If R1.Start = WordApp.Selection.Range.Start And R1.End = WordApp.Selection.Range.End Then
Exit Do
End If
Set R1 = WordApp.Selection.Range
If WordApp.Selection.Tables.Count <> 0 Then
WordApp.Selection.Tables(1).Select
WordApp.Selection.Collapse (0)
Else
If WordApp.Selection.Characters.Last <> Chr(13) And WordApp.Selection.Characters.Count < LowFillThreshold Then
If WordApp.Selection.Paragraphs.Alignment = 3 Then ' wdAlignParagraphJustify
LineNumber = WordApp.Selection.Information(10) 'wdFirstCharacterLineNumber)
PageNumber = WordApp.Selection.Information(1) ' wdActiveEndPageNumber
StdErr.WriteLine "Low fill factor in line = " & LineNumber & " on page = " & PageNumber
FileName = ErrorFileNamePrefix & "Малое заполнение строки на странице " & PageNumber & ", строка " & LineNumber & ".pdf"
WordApp.Selection.Range.HighlightColorIndex = wdYellow
Call ExportPageAsPdf(Doc, FileName)
Doc.Undo
End If
End If
End If
Loop
End Sub