Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

Word VBA: Replace the space at the end of a line if the preceding character is a digit

I've found this similar issue here, but I don't know how to make it work for what I need.

I need to replace the space (" ") at the end of a line if it's preceded by a digit ("[0-9]"). Replacement text will be a non-breaking space ("^s"). So for example, throughout my document I might have dates written in this format "24 September 2019", phone numbers, phrases like "in 8 days" etc. I need to ensure the line doesn't break between the digit and the following word, hence replacing the space with a non-breaking space.

My code is on a different PC so it's not easy for me to include it, and all I've done so far is copy the one linked above but it doesn't work because I'm not sure which parts I need to amend. So please see the link above for what I've got so far, alternatively any new code that might be more effective is of course welcome.

Thank you in advance :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should resolve your issue:

Sub testNBS()

Dim myRange As Range

Set myRange = ActiveDocument.Range(ActiveDocument.Range.Start, ActiveDocument.Range.Start)
myRange.Select
Selection.Expand wdLine

While Selection.End < ActiveDocument.Range.End
    If Right(Selection.Text, 1) = " " And IsNumeric(Left(Selection.Words.Last, 1)) = True Then
        Selection.Characters.Last = Chr(160)
    End If

    Selection.MoveDown wdLine, 1
    Selection.Expand wdLine
Wend
End Sub

I changed Left to Right, added the check for a numeric string, and added in the addition of a non-breaking space (NBS) in place of the last character in the line, which should be a space. I added the And clause just to double-check/verify.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...