Regexp生成#NAME? UDF中的错误

时间:2016-02-04 20:21:30

标签: regex excel vba excel-vba

我在网上找到很多东西,告诉我如何创建这个功能以及如何实现它,但没有什么可以帮助我找出它为什么不能接受这个功能的名字。< / p>

我在开发人员下打开了Visual Basic部分。我输入了我的代码,我认为就是这样吗? Ctrl + S只让我保存工作表,而不是代码。

我的代码的目的是取一个字符串并删除前7个字符,其中一个将是a;以下6个是随机数。我还有一些工作要做,比如从最后删除4个随机字符,但我想先测试一下。

这是我的代码:

Function simpleCellRegex(Myrange As Range) As String
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim strOutput As String


strPattern = "^[;][0-9]{6}"

If strPattern <> "" Then
    strInput = Myrange.Value
    strReplace = ""

    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = strPattern
    End With

    If regEx.test(strInput) Then
        simpleCellRegex = regEx.Replace(strInput, strReplace)
    Else
        simpleCellRegex = "Not matched"
    End If
End If
End Function

我不确定是否有一个我遗漏的步骤会让excel接受我的代码。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

查看此主题。您很可能错过了添加对Microsoft VBScript Regular Expressions 5.5的引用。您可以在&#34;如何使用&#34;:

下找到它

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

答案 1 :(得分:1)

我已经重新编写了下面的代码来清理变量并使用后期绑定

此外,您当前的代码不会测试将多个单元格放入范围内的用户。

Function simpleCellRegex(Myrange As Range) As String
Dim regEx As Object
Dim strPattern As String
Dim strReplace As String

Set regEx = CreateObject("vbscript,regexp")

strPattern = "^[;][0-9]{6}"
If Len(strPattern) = 0 Then Exit Sub

simpleCellRegex = "Not matched"
strReplace = vbNullString

With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
    If .test(Myrange) Then simpleCellRegex = .Replace(Myrange.Value2, strReplace)
End With

End Function