KazJaw的另一个答案效果很好,但我已经修改以包含一些改进,并希望发布修改以防其他人遇到此问题。
改进包括:
- 更好地记录每个步骤。
- 使用更好的ASCII 控制字符,以便更好地识别段落。
使用更优雅的方法来确定是否在单词中间,通过替换
If Len(Trim(ActiveDocument.Range(char_index - 1, char_index + 1).Text)) < 2 Then
和
If ActiveDocument.Range(char_index).Text = " " Or _
ActiveDocument.Range(char_index).Text = "-" Then
- 带连字符的单词现在可以跨行正确拆分。例如,“servo-valve”现在可以在一行中使用“servo-”,在下一行的开头使用“valve”。
这是修改后的代码,再次感谢 KazJaw 的原始解决方案。
Public Sub wrap_words()
'adapted from stackoverflow
'https://stackoverflow.com/a/19109049/2658159
Dim para_index As Paragraph
Dim para_index_numchars, char_index, para_index_start As Long
'set the max line length constraint
Const line_max As Byte = 50
'loop through each paragraph
For Each para_index In ActiveDocument.Paragraphs
'find number of characters
para_index_numchars = para_index.Range.Characters.Count
'find the paragraph starting point
para_index_start = para_index.Range.Start
'if the paragraph has more than the predetermined amount of characters,
If para_index_numchars > line_max Then
'loop through each character starting with line_max position
'and stepping by line_max position, to the end of the paragraph
For char_index = (para_index_start + line_max) To _
(para_index_start + para_index_numchars) Step line_max
'if there is not a word in this position...
If ActiveDocument.Range(char_index).Text = " " Or _
ActiveDocument.Range(char_index).Text = "-" Then
'...just insert new line mark
ActiveDocument.Range(char_index, char_index).InsertAfter Chr(13)
Else
'... if there is a word, or a hyphenated word that
'can be split, move to the beginnng of word or the
'end of the hyphenated section.
ActiveDocument.Range(char_index, char_index).Select
Selection.MoveLeft unit:=wdWord, Count:=1
'insert newline at the beginning
Selection.InsertBefore Chr(13)
'since a new paragraph created before the word,
'the previous paragraph structure has changed.
'change char_index to reflect that change.
char_index = Selection.Start
End If
Next
End If
Next
End Sub