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

本小妞迷上赌 提交于 2020-02-08 10:24:40

问题


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 :)


回答1:


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.



来源:https://stackoverflow.com/questions/59628421/word-vba-replace-the-space-at-the-end-of-a-line-if-the-preceding-character-is-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!