Sunday, May 30, 2010

The Incredible Shrinking Sentence

The Cannonball Run (1981)
He's my shrink. He was committed yesterday. 

If you have a block of code with long lines that you quote in a document, the long lines can wrap around to the next line which looks really bad and makes the code harder to understand.  To fix this problem, we start with a macro found over at WordTips and add a conditional statement so that it only is executed for a certain style (in this case Code Box). The macro reduces the font by ChangeSize and then checks if the paragraph fits on one line. It then repeats this process until it fits on one line.

Sub forceParaOneLine()
    Dim objPara As Paragraph
    Const ChangeSize = 0.5
   
    For Each objPara In ActiveDocument.Paragraphs
        If objPara.Style = ActiveDocument.Styles("Code Box") Then
            With objPara.Range
                While .Information(
wdFirstCharacterLineNumber) <> .Characters(Len(.Text)).Information(wdFirstCharacterLineNumber)
                    .Font.Size = .Font.Size - ChangeSize
                Wend
            End With
        End If
    Next objPara
               
End Sub

Note that if you have really long lines, this will reduce the font so that it is impossible to read.  To avoid this, I suggest using 2 styles in your document: one for code that can be shrunk, and one that is not shrunk.

[source WordTips]

No comments:

Post a Comment