特殊字符的VBA RegEx

时间:2014-11-05 17:38:18

标签: regex excel vba excel-vba

当用户输入&#34;另存为&#34;我宏的输出名称,我想检查一下在保存文件时会出错的特殊字符 - [\/:*?<>|]

我像这样使用RegExp:

Dim regEx As New RegExp
Dim strSpecChar As String: strSpecChar = "*[\/:*?<>|]*" 'Compile Error here
Dim OutputFileName As String: OutputFileName = InputBox("Enter File Name")
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = True
    .Pattern = strSpecChar
End With
If regEx.Test(OutputFileName) Then
        'error msg
End If

由于条形(Compile Error: Invalid Character)字符,我收到|错误。我试过用反斜杠逃避吧,但它没有用。有人可以帮忙吗?我已经阅读了一些帖子,包括this one,但它没有帮助。

解决方案:查看下面blog.tkacprow.pl的评论和Alex的答案(他帮助指出了拼写错误并解释了错误5018.从上面的strSpecChar变量中删除*

2 个答案:

答案 0 :(得分:2)

未检查您的正则表达式是否正确,但您在正则表达式中包含了字符",其中vba将其视为字符串的结尾。您可以使用chr(34)替换双引号:

strSpecChar = "*[\/:*?" & Chr(34) & "<>]|*"

答案 1 :(得分:2)

实际上没有必要使用正则表达式引擎来测试字符串中是否存在一组字符。您可以简单地使用VBA Like Operator来完成相同的任务,而无需引用外部库:

Const strSpecChar As String = "*[\/:*?<>|]*"
Dim OutputFileName As String: OutputFileName = InputBox("Enter File Name")
If OutputFileName Like strSpecChar Then
    MsgBox "Error Message"
End If

或者,如果您想将双引号作为要排除的字符之一:

Const strSpecChar As String = "*[\/:*?<>|""]*"

请注意在字符类中使用doubled双引号,以告诉VBA包含该引号而不是标记字符串的结尾。

相关问题