Check for Numeric Value in Word Macro using Regular Expressions

…衆ロ難τιáo~ 提交于 2021-01-27 20:58:18

问题


Is it possible to directly use regular expressions in Word macros?

I want to check if a string contains only numbers and the following code does not work.

isNumber = RegEx.IsMatch("234", "[0-9]+$")

I simply need it to return true or false.


回答1:


You can create an instance of the VBScript.Regexp object within your code, but an easier solution would be to use the existing VBA function IsNumeric. Both methods are included below:

Sub testNumeric()

    'Use IsNumeric
    MsgBox (IsNumeric("12345"))     'Returns true
    MsgBox (IsNumeric("123a"))      'Returns false

    'Alternatively, using Regexp Object
    Dim regexp
    Set regexp = CreateObject("VBScript.Regexp")
    regexp.Pattern = "[0-9]+$"
    MsgBox (regexp.test("12345"))   'Returns true
    MsgBox (regexp.test("123a"))   'Returns false

End Sub

Note that the regex pattern does not strictly return numbers, but also any string that ends with numbers (i.e. testing "a123" returns true). To make the regex check strictly numeric, the pattern could be ^[0-9]+$. Thanks to @mike for pointing this out.



来源:https://stackoverflow.com/questions/22210995/check-for-numeric-value-in-word-macro-using-regular-expressions

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