Word VBA:如果前面的字符是数字,请替换行尾的空格 [英] Word VBA: Replace the space at the end of a line if the preceding character is a digit

查看:262
本文介绍了Word VBA:如果前面的字符是数字,请替换行尾的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此处发现了类似的问题,但是我不知道如何使其适合我的需求.

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

如果在行末添加数字("[0-9]"),则需要在行末替换空格(" ").替换文本将是一个不间断的空格("^s").因此,例如,在我的整个文档中,我可能都用"2019年9月24日"这样的格式写日期,电话号码,诸如在8天之内"之类的短语.我需要确保数字和下一个单词之间的行不中断,因此用不间断的空格替换了该空格.

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.

我的代码在另一台PC上,所以要包含它并不容易,到目前为止,我所做的只是复制上面链接的代码,但由于我不确定我需要哪些部分而无法正常工作修改.因此,请查看上面的链接以了解到目前为止的内容,或者当然欢迎任何可能更有效的新代码.

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.

预先感谢您:)

推荐答案

这应该可以解决您的问题:

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

我将Left更改为Right,添加了对数字字符串的检查,并添加了不间断空格(NBS)来代替行中的最后一个字符,该字符应为空格.我添加了And子句只是为了仔细检查/验证.

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.

这篇关于Word VBA:如果前面的字符是数字,请替换行尾的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆