PDA

View Full Version : Align a line based on a value in the line



meet
10-18-2019, 07:06 AM
I have a text file with over 50,000 rows (lines).
There's a character in each line - say 'XX' and 'YY', which doesn't occur otherwise


For each line with 'XX', I want the line to be left aligned, and for 'YY' I need it right aligned. (As of now, all the lines are left aligned.)
There's no particular sequence in XX or YY type repetition. (XX and YY type lines occur randomly.) And at each change from XX to YY or vice versa, I need a new line character.


Let me clarify this with an example.

Data:



(Left-aligned) XX: ABCD
(Left-aligned) YY: EFGH
(Left-aligned) YY: IJK
(Left-aligned) XX: LMN
(Left-aligned) XX: OPQ
(Left-aligned) YY: STU



Output Required:



(Left-aligned) XX: ABCD


(Right-aligned) YY: EFGH
(Right-aligned) YY: IJK


(Left-aligned) XX: LMN
(Left-aligned) XX: OPQ


(Right-aligned) YY: STU


I tried with this but it doesn't give desired result. Please guide me to fix the code to get the result.



Private Sub alignText()
With Selection.Find.Execute FindText:="YY", Forward:=True
Selection.ParagraphFormat.Alignment = wdAlignParagraphRight
End With
End Sub

gmayor
10-18-2019, 07:58 AM
How about the following, however note that text files do not support such formatting.


Private Sub alignText()
Dim orng As Range
Set orng = ActiveDocument.Range
With orng.Find
Do While .Execute(findText:="YY", Forward:=True)
orng.Paragraphs(1).Range.ParagraphFormat.Alignment = wdAlignParagraphRight
orng.Collapse 0
Loop
End With
End Sub

gmaxey
10-18-2019, 08:00 AM
Alignment in Word is a paragraph (not line) attribute. So unless each line is a paragraph, there isn't much you can do. If each line is a paragraph, and as the text with "XX" is already left aligned then all you need is:


Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey
Dim oPar As Paragraph
For Each oPar In ActiveDocument.Paragraphs
If InStr(oPar.Range.Text, "YY") Then oPar.Alignment = wdAlignParagraphRight
Next oPar
lbl_Exit:
Exit Sub
End Sub

gmaxey
10-18-2019, 08:02 AM
Opps, Graham beat me to the reply. In a large large document like you describe, his method would be faster.

gmaxey
10-18-2019, 08:06 AM
Howsoever, this would be faster yet:


Private Sub alignText()
Dim orng As Range
Set orng = ActiveDocument.Range
With orng.Find
.Text = "YY"
.Replacement.ParagraphFormat.Alignment = wdAlignParagraphRight
.Execute Replace:=wdReplaceAll
End With
lbl_Exit:
Exit Sub
End Sub


Thanks Graham, for the stoking the brain to think!!