PDA

View Full Version : [SOLVED:] Easy question: adding a paragraph for each row of a document AFTER 20 characters



charles
10-05-2016, 08:13 AM
Dear All,

I have a pretty easy question for you experimented programmers :)
As explained in the title, I want to count 20 characters on a row, insert a paragraph, and do that for all rows of the document. Easy no ? It's days I try to do that. 
Thank you in advance 

I use Word 2010

gmaxey
10-05-2016, 05:45 PM
A word document doesn't consist of rows unless it is a table. Perhaps something like this:


Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey
Dim oRng As Range
Set oRng = ActiveDocument.Range
oRng.Collapse wdCollapseStart
Do
oRng.Select
oRng.End = oRng.End + 20
If InStr(oRng, Chr(13)) > 0 Then
oRng.Start = InStr(oRng, Chr(13))
oRng.End = oRng.Start
Else
oRng.Start = oRng.End
oRng.InsertBefore vbCr
oRng.Start = oRng.Start + 1
End If
Loop Until ActiveDocument.Range.End - oRng.End < 20
lbl_Exit:
Exit Sub

End Sub

charles
10-06-2016, 04:36 AM
Thank you, Greg. I'll try and let you know.

I'm surprised about the code, thought it wd be much easier..

gmaxey
10-06-2016, 04:46 AM
You should be able to get rid of the "oRng.Select" line in the code.

charles
10-06-2016, 05:10 AM
It works. However, I forgot to mention additional constraint I had: if at 20 characters you find yourself in a word, it should go at the beginning of this word and apply the paragraph, how do you do that ? 


I've been trying this with macro recorder and the code looked like : 


Selection.MoveRight Unit:=wdCharacter, Count:=20 

Selection.MoveLeft Unit:=wdWord, Count:=1 

Selection.TypeParagraph 


Why is the coding completely different than that ?  


What is
Chr(13) please ? 


Thank you again very much.

gmayor
10-06-2016, 06:44 AM
The following should address the break in the middle of a word.
Chr(13) is a paragraph break. Chr(32) to avoid you asking :) is a space.


Sub ScratchMacro1()
'A basic Word macro coded by Greg Maxey
'with mods by
'Graham Mayor - http://www.gmayor.com - 06/10/2016
Dim oRng As Range
Set oRng = ActiveDocument.Range
oRng.Collapse wdCollapseStart
Do
oRng.End = oRng.End + 20
While Not oRng.Characters.Last = Chr(32)
oRng.End = oRng.End - 1
Wend
If InStr(oRng, Chr(13)) > 0 Then
oRng.Start = InStr(oRng, Chr(13)) + 1
oRng.Collapse wdCollapseEnd
Else
oRng.Collapse wdCollapseEnd
oRng.InsertBefore vbCr
oRng.Start = oRng.Start + 1
End If
DoEvents
Loop While oRng.Start < ActiveDocument.Range.End - 20
lbl_Exit:
Exit Sub
End Sub

charles
10-06-2016, 07:40 AM
This works awesome.  
I could have tried few more months..  

Thank you to you two

gmaxey
10-06-2016, 12:56 PM
You know there are over 100 words in the English that are twenty characters longs and many more with 20+ characters. I doubt that you will find anything that work in every scenario.