问题
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